The Superlend Looping Protocol is a comprehensive DeFi system that enables users to perform leverage operations using Aave V3 flash loans and universal DEX swaps. It allows users to either increase their leverage (loop) or decrease it (unloop) in a single atomic transaction through a modular architecture consisting of looping helpers and user-specific strategy contracts.
The protocol consists of two main layers:
- Looping Layer (
/src/looping/): Core flash loan and swap execution logic - Strategy Layer (
/src/strategy/): User-specific strategy management contracts
LoopingHelper: Main contract for executing loop/unloop operations via Aave V3 flash loansLoopingHelperSwaps: Handles token swaps through universal DEX moduleLoopingHelperEncoding: Manages parameter encoding/decoding for flash loan callbacksDataTypes: Library containing data structures for loop/unloop operations
LoopingHelper: Inherits fromFlashLoanSimpleReceiverBase,ReentrancyGuard,LoopingHelperSwaps,LoopingHelperEncodingLoopingHelperSwaps: Abstract contract for swap operationsLoopingHelperEncoding: Abstract contract for parameter encoding/decoding
Operationenum: Defines two operationsLOOP: For increasing leverageUNLOOP: For decreasing leverage
LoopCallParams: Parameters for initiating loop operationsUnloopCallParams: Parameters for initiating unloop operationsLoopParams: Internal parameters for loop execution during flash loan callbackUnloopParams: Internal parameters for unloop execution during flash loan callback
-
loop(DataTypes.LoopCallParams memory params)- Initiates a leverage increase operation
- Transfers supply tokens from user to contract
- Executes flash loan for additional leverage
- Handles token approvals and supplies
-
unloop(DataTypes.UnloopCallParams memory params)- Initiates a leverage decrease operation
- Uses flash loan to repay debt
- Withdraws collateral and handles swaps
executeOperation(address, uint256 amount, uint256 premium, address, bytes calldata params)- Callback function for Aave V3 flash loans
- Routes to appropriate operation based on encoded params
- Handles both loop and unloop operations
-
_executeLoop(DataTypes.LoopParams memory loopParams, uint256 amount, uint256 premium)- Core logic for loop operations during flash loan callback
- Manages token supplies, borrows, and swaps
- Handles leftover amounts and flash loan repayment
-
_executeUnloop(DataTypes.UnloopParams memory unloopParams, uint256 amount, uint256 premium)- Core logic for unloop operations during flash loan callback
- Manages debt repayment and collateral withdrawal
- Handles token swaps and flash loan repayment
-
_handleLeftOverAmounts(address supplyToken, address borrowToken, uint256 leftOverSupplyAmount, uint256 leftOverBorrowAmount, address user)- Handles any remaining tokens after operations
- Supplies leftover yield tokens back to Aave
- Repays leftover debt tokens
The Superlend Looping Strategy system enables each user to deploy dedicated strategy contracts that manage their leveraged positions. This pattern provides isolation, flexibility, and user-specific control over leverage and unloop operations.
SuperlendLoopingStrategyFactory: Ownable factory for deploying user strategy contractsSuperlendLoopingStrategy: Ownable contract managing a user's looped position, inherits fromSuperlendLoopingStrategyStorageSuperlendLoopingStrategyStorage: Abstract contract holding configuration and state for each strategy instance
userStrategies: Mapping from user address to their deployed strategy contractsexistingStrategies: Mapping to prevent duplicate strategies for the same asset pair and eMode
-
createStrategy(address _loopingHelper, address _pool, address _yieldAsset, address _debtAsset, uint8 _eMode)- Deploys a new strategy contract for the user
- Ensures uniqueness per asset pair and eMode
- Emits
StrategyDeployedevent
-
getUserStrategies(address _user): Returns all strategy addresses for a user -
getUserStrategy(address _user, address _pool, address _yieldAsset, address _debtAsset, uint8 _emode): Returns a specific strategy address -
getStrategyId(address pool, address yieldAsset, address debtAsset, uint8 eMode): Generates unique strategy ID
-
openPosition(uint256 supplyAmount, uint256 flashLoanAmount, uint256 borrowAmount, ExecuteSwapParams memory swapParams, uint256 delegationAmount)- Transfers user collateral to the strategy
- Delegates borrowing power to the looping helper contract
- Calls
loopon LoopingHelper to open a leveraged position
-
closePosition(uint256 repayAmount, uint256 withdrawAmount, ExecuteSwapParams memory swapParams, uint256 aTokenAmount, uint256 exitPositionAmount)- Optionally repays debt and unloops via LoopingHelper
- Withdraws collateral from the lending pool to the user
-
setLoopingHelper(address __loopingHelper): Updates the looping helper contract address -
skim(address[] memory tokens): Emergency function to recover stuck tokens
- Holds addresses for pool, yield asset, debt asset, aToken, variableDebtToken, and looping helper
- Manages eMode configuration and validation
- Provides getter functions for all configuration parameters
-
Reentrancy Protection
- Uses OpenZeppelin's ReentrancyGuard
- All public functions are marked with
nonReentrant - Prevents reentrancy attacks during complex operations
-
Access Control
- Flash loan callback verification
- Strict checks for flash loan caller (only Aave pool)
- User-specific operations with proper authorization
-
Input Validation
- Parameter validation through structs
- Swap parameter validation
- Amount validation for operations
-
Safe Token Handling
- Proper approval management using SafeERC20
- Balance checks before operations
- Safe transfer operations
-
Access Control
- Only the owner (user) can operate their strategy contract
- Factory ownership controls for administrative functions
-
Factory Uniqueness
- Prevents duplicate strategies for the same asset pair/eMode
- Unique strategy ID generation based on configuration
-
Delegation
- Uses Aave credit delegation for safe borrowing
- Proper approval management for aTokens
-
E-Mode Validation
- Validates E-Mode consistency between yield and debt assets
- Ensures proper asset correlation for higher collateralization ratios
- User calls
openPositionon their strategy contract - Strategy transfers yield tokens from user and approves looping helper
- Strategy sets up credit delegation if specified
- Strategy calls
loopon LoopingHelper with parameters - LoopingHelper executes flash loan
- During flash loan callback:
- Supplies combined amount (user tokens + flash loan) to Aave
- Borrows specified amount from Aave
- Swaps borrowed tokens back to yield tokens
- Handles leftover amounts
- Repays flash loan
- User calls
closePositionon their strategy contract - Strategy approves aTokens for looping helper
- Strategy calls
unloopon LoopingHelper with parameters - LoopingHelper executes flash loan
- During flash loan callback:
- Repays borrowed tokens using flash loan funds
- Withdraws supplied tokens from Aave
- Swaps withdrawn tokens to repay flash loan
- Handles leftover amounts
- Repays flash loan
- Strategy withdraws remaining tokens to user
- User calls
createStrategyon the factory - Factory generates unique strategy ID
- Factory deploys new
SuperlendLoopingStrategycontract - Factory registers strategy in user's strategy list
- User interacts with their strategy contract to open/close positions
- Flash loan functionality
- Lending pool operations (supply, borrow, repay, withdraw)
- Reserve data access
- Credit delegation
- E-Mode configuration
- Token swaps for loop/unloop operations
- Price execution
- Slippage protection
- Multi-DEX routing
- ERC20 token handling
- SafeERC20 for secure transfers
- Proper approval management
- Price impact during swaps
- Slippage considerations
- Market volatility effects
- Flash loan premium costs
- Aave protocol changes
- DEX protocol changes
- Token listing/delisting
- E-Mode category changes
- Complex operations may be gas-intensive
- Multiple token approvals required
- Strategy deployment costs per user
- Flash loan execution costs
- One strategy per asset pair/eMode per user
- Strategy uniqueness constraints
- E-Mode validation requirements
- Credit delegation limits
-
Token Approvals
- Verify sufficient token approvals for strategy contract
- Check looping helper approvals
- Validate credit delegation amounts
-
Balance Verification
- Ensure sufficient token balances
- Check Aave position health factors
- Validate swap parameters
-
Configuration Validation
- Verify E-Mode compatibility
- Check asset pair configuration
- Validate strategy contract setup
-
Execution Confirmation
- Verify successful operation execution
- Check final token balances
- Monitor gas costs
-
Position Monitoring
- Track health factors
- Monitor collateralization ratios
- Check for any leftover amounts
-
Position Monitoring
- Regular health factor checks
- Monitor market conditions
- Track protocol updates
-
Fee Management
- Account for flash loan premiums
- Consider swap fees and slippage
- Monitor gas costs
-
Emergency Procedures
- Keep strategy contract addresses safe
- Monitor for stuck tokens
- Have emergency exit strategies