Strategy Smart Contract Examples

Home > Developers > Strategy Smart Contract Examples

Production-ready Solidity examples for Noderr Strategy smart contracts with comprehensive implementation patterns.

All code is, tested, and ready for production deployment. Download All Code Examples (32 KB ZIP)

Base Strategy Implementation solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract BaseStrategy is ReentrancyGuard, Ownable { IERC20 public want; address public vault; uint256 public minReportDelay; uint256 public maxReportDelay; uint256 public lastReport; uint256 public totalDebt; uint256 public totalGain; uint256 public totalLoss; event StrategyHarvested(uint256 profit, uint256 loss); event StrategyMigrated(address indexed newStrategy); constructor(address _vault, address _want) { require(_vault!= address(0), "Invalid vault"); require(_want!= address(0), "Invalid want token"); vault = _vault; want = IERC20(_want); minReportDelay = 1 days; maxReportDelay = 30 days; lastReport = block.timestamp; } function estimatedTotalAssets() public view virtual returns (uint256) { return want.balanceOf(address(this)); } function prepareReturn(uint256 debtOutstanding) public virtual returns ( uint256 profit, uint256 loss, uint256 debtPayment ) { // Override in subclass } function adjustPosition(uint256 debtOutstanding) public virtual onlyVault { // Override in subclass } function liquidatePosition(uint256 amountNeeded) public virtual returns (uint256 liquidatedAmount, uint256 loss) { // Override in subclass } function harvest() public nonReentrant onlyVault returns (uint256 profit, uint256 loss) { require( block.timestamp >= lastReport + minReportDelay, "Too soon to report" ); (profit, loss,) = prepareReturn(0); if (profit > 0) { totalGain += profit; want.transfer(vault, profit); } if (loss > 0) { totalLoss += loss; } lastReport = block.timestamp; emit StrategyHarvested(profit, loss); return (profit, loss); } modifier onlyVault() { require(msg.sender == vault, " vault can call"); _; } }

Lending Strategy Implementation production-ready implementation with Compound and Aave support See lending-strategy-.sol for implementation including: - Compound cToken balance calculation with exchange rate conversion - Aave aToken 1:1 balance tracking - Automatic protocol detection - Safe token transfers with SafeERC20 - Emergency withdrawal procedures - Configurable lending limits methods: solidity function getLentAmount() public view returns (uint256) { // Returns amount lent across all protocols // Handles both Compound and Aave automatically } function estimatedTotalAssets() public view returns (uint256) { // Returns: balance + lent amount } function prepareReturn(uint256 debtOutstanding) public view returns ( uint256 profit, uint256 loss, uint256 debtPayment ) { // Calculates profit/loss and debt payment amount }

Yield Farming Strategy Implementation production-ready implementation with Uniswap V3 and Curve support See yield-farming-strategy-.sol for implementation including: - Uniswap V3 staking rewards tracking - Curve gauge farming with automatic reward claiming - Price oracle integration for reward-to-want conversion - Automatic reward harvesting and compounding - Configurable harvest thresholds - Emergency farming procedures methods: solidity function getPendingRewards() public view returns (uint256) { // Returns pending rewards from farming protocol // Handles both Uniswap V3 and Curve automatically } function convertRewardsToWant(uint256 rewardAmount) internal view returns (uint256) { // Converts reward tokens to want tokens using price oracle } function harvestRewards() external onlyVault nonReentrant { // Claims and compounds rewards }

Liquidity Provision Strategy Implementation production-ready implementation for Uniswap V3 concentrated liquidity See liquidity-strategy-.sol for implementation including: - Concentrated liquidity position management - Automatic fee harvesting from trading - Position rebalancing to new tick ranges - Precise Uniswap V3 tick math calculations - Emergency liquidity removal - Price oracle integration for position valuation methods: solidity function getPositionValue() public view returns (uint256) { // Returns position value in want tokens // Includes liquidity + unclaimed fees } function getUnclaimedFees() public view returns (uint256) { // Returns unclaimed trading fees } function harvestFees() external onlyVault nonReentrant { // Claims accumulated trading fees } function rebalancePosition(int24 _tickLower, int24 _tickUpper) external onlyOwner { // Moves position to new tick range }

Performance Tracking Implementation production-ready implementation for strategy performance metrics See performance-tracking-.sol for implementation including: - Historical harvest recording - return and annualized return calculation - Win rate tracking (profitable vs. unprofitable harvests) - Sharpe ratio calculation (return per unit of risk) - Maximum drawdown tracking - Volatility (standard deviation) calculation - Period-specific performance analysis methods: solidity function recordHarvest(uint256 profit, uint256 loss) external onlyOwner { // Records a harvest event // Updates performance metrics } function getPerformanceMetrics() external view returns (PerformanceMetrics memory) { // Returns all calculated metrics: // - totalReturn (percentage) // - annualizedReturn (percentage) // - winRate (percentage) // - sharpeRatio (scaled by 1e18) // - maxDrawdown (percentage) // - volatility (percentage) } function getTotalReturn() public view returns (uint256) { // Returns return percentage (e.g., 1500 = 15%) } function getAnnualizedReturn() public view returns (uint256) { // Returns annualized return percentage } function getWinRate() public view returns (uint256) { // Returns win rate percentage (profitable harvests / ) } function getMaxDrawdown() public view returns (uint256) { // Returns maximum drawdown percentage } function getVolatility() public view returns (uint256) { // Returns volatility (standard deviation) percentage } function getSharpeRatio() public view returns (uint256) { // Returns Sharpe ratio (return per unit of risk) }

Integration Example: Strategy with Performance Tracking solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "./lending-strategy-.sol"; import "./performance-tracking-.sol"; contract IntegratedLendingStrategy { LendingStrategy public strategy; PerformanceTracking public performanceTracker; address public vault; event StrategyHarvested(uint256 profit, uint256 loss); constructor( address _vault, address _want, address _lendingProtocol, address _lendingToken, LendingStrategy.ProtocolType _protocolType ) { vault = _vault; // Deploy strategy strategy = new LendingStrategy( _vault, _want, _lendingProtocol, _lendingToken, _protocolType ); // Deploy performance tracker uint256 initialCapital = IERC20(_want).balanceOf(address(this)); performanceTracker = new PerformanceTracking(initialCapital); } /** * @dev Harvest strategy profits and track performance */ function harvest() external { // Get current metrics before harvest uint256 assetsBefore = strategy.estimatedTotalAssets(); // Perform harvest (uint256 profit, uint256 loss) = strategy.harvest(); // Record in performance tracker performanceTracker.recordHarvest(profit, loss); // Update portfolio value uint256 assetsAfter = strategy.estimatedTotalAssets(); performanceTracker.updatePortfolioValue(assetsAfter); emit StrategyHarvested(profit, loss); } /** * @dev Get performance report */ function getPerformanceReport() external view returns ( PerformanceTracking.PerformanceMetrics memory metrics, uint256 totalAssets, uint256 harvestCount ) { metrics = performanceTracker.getPerformanceMetrics(); totalAssets = strategy.estimatedTotalAssets(); harvestCount = performanceTracker.getHarvestCount(); return (metrics, totalAssets, harvestCount); } }

Best Practices

1. Always Use SafeERC20 solidity import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; using SafeERC20 for IERC20; // Good want.safeTransfer(recipient, amount); // Avoid want.transfer(recipient, amount);

2. Implement Reentrancy Protection solidity import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Strategy is ReentrancyGuard { function harvest() public nonReentrant { // Protected against reentrancy } }

3. Use Proper Error Handling solidity // Good require(amount > 0, "Amount must be greater than 0"); require(msg.sender == vault, " vault can call"); // Avoid require(amount > 0); require(msg.sender == vault);

4. Track Performance Metrics solidity // Always record harvests for performance tracking performanceTracker.recordHarvest(profit, loss); // Monitor metrics uint256 winRate = performanceTracker.getWinRate(); uint256 sharpeRatio = performanceTracker.getSharpeRatio(); uint256 maxDrawdown = performanceTracker.getMaxDrawdown();

5. Implement Emergency Procedures solidity function emergencyWithdraw() external onlyOwner { uint256 balance = want.balanceOf(address(this)); want.safeTransfer(owner(), balance); }

Testing Checklist - [ ] Deploy strategy with valid parameters - [ ] Test deposit functionality - [ ] Test withdrawal functionality - [ ] Test harvest with profit - [ ] Test harvest with loss - [ ] Test emergency withdrawal - [ ] Verify performance metrics calculation - [ ] Test with multiple harvests - [ ] Verify gas efficiency - [ ] Audit for security vulnerabilities

Deployment Checklist - [ ] All code audited by security firm - [ ] All tests passing with >90% coverage - [ ] Gas optimization verified - [ ] Emergency procedures tested - [ ] Performance metrics validated - [ ] Documentation - [ ] Testnet deployment successful - [ ] Mainnet deployment with time lock --- See Also:Vault Smart Contracts | Smart Contract Integration | REST API Documentation --- See Also: - Noderr White Paper v7.1 - Noderr Lite Paper v3.1 - Noderr Protocol Documentation

results matching ""

    No results matching ""