### Install Project Dependencies Source: https://github.com/openleveragedev/openleverage-contracts/blob/main/README.md Install the necessary Node.js dependencies for the OpenLeverage contracts using npm. This command should be run after cloning the repository. ```bash npm install ``` -------------------------------- ### Install Ganache CLI for Local Blockchain Source: https://github.com/openleveragedev/openleverage-contracts/blob/main/README.md Install Ganache CLI globally using npm. This tool provides a personal blockchain for development, allowing you to run and test smart contracts locally. ```bash npm install -g ganache-cli ``` -------------------------------- ### Clone OpenLeverage Contracts Repository Source: https://github.com/openleveragedev/openleverage-contracts/blob/main/README.md Clone the OpenLeverage contracts repository from GitHub to get started with the project. Ensure you have Git installed. ```bash git clone https://github.com/OpenLeverageDev/openleverage-contracts.git ``` -------------------------------- ### DexAggregator: Get Current and Average Prices Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Retrieve current spot prices, time-weighted average prices (TWAP), and historical TWAP from AMM pools. Requires pre-encoded DEX data. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./dex/DexAggregatorInterface.sol"; // ============================================ // GET PRICES // ============================================ bytes memory dexData = abi.encodePacked(uint8(1), uint24(3000)); // Get current spot price (uint256 price, uint8 decimals) = dexAgg.getPrice( tokenA, // desToken (desired/quote) tokenB, // quoteToken (base) dexData ); // price = amount of tokenB per tokenA, scaled by 10^decimals // Get TWAP (time-weighted average price) (uint256 avgPrice, uint8 decimals, uint256 timestamp) = dexAgg.getAvgPrice( tokenA, tokenB, 60, // secondsAgo: TWAP window in seconds dexData ); // Get comprehensive price data (current, cAvg, hAvg) ( uint price, uint cAvgPrice, // Current TWAP uint256 hAvgPrice, // Historical TWAP (last recorded) uint8 decimals, uint256 timestamp ) = dexAgg.getPriceCAvgPriceHAvgPrice( tokenA, tokenB, 60, dexData ); ``` -------------------------------- ### DexAggregator: Get Liquidity Information Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Query the liquidity available for a pair of tokens in AMM pools. Can retrieve liquidity for one or both tokens. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./dex/DexAggregatorInterface.sol"; // ============================================ // GET LIQUIDITY // ============================================ // Get single token liquidity uint token0Liquidity = dexAgg.getToken0Liquidity(token0, token1, dexData); // Get both token liquidities (uint token0Liq, uint token1Liq) = dexAgg.getPairLiquidity(token0, token1, dexData); ``` -------------------------------- ### Compile OpenLeverage Smart Contracts Source: https://github.com/openleveragedev/openleverage-contracts/blob/main/README.md Compile the Solidity smart contracts for the OpenLeverage Protocol using Truffle. This step is required before testing or deployment. ```bash truffle compile ``` -------------------------------- ### Check Margin Ratio for OpenLevV1 Positions Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Retrieves margin ratios (current, TWAP-based, and historical) and the liquidation threshold for a given position. Use this to determine if a position is healthy or requires liquidation. Ratios are compared against the limit (e.g., 3000 for 30%). ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; // ============================================ // CHECK MARGIN RATIO // ============================================ // Returns margin ratios for health monitoring ( uint current, // Current margin ratio using spot price uint cAvg, // Margin ratio using current TWAP uint hAvg, // Margin ratio using historical TWAP uint32 limit // Liquidation threshold (e.g., 3000 = 30%) ) = openLev.marginRatio( traderAddress, marketId, longToken, // false for token0 long, true for token1 long dexData ); // Position is healthy if all ratios > limit // Example: current=8052 means 80.52% margin ratio (healthy if limit=3000) bool isHealthy = (current > limit) && (cAvg > limit) && (hAvg > limit); ``` -------------------------------- ### Check LPool Balances and Rates Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Provides functions to query LPool contract state, including user LToken and underlying balances, current exchange rates, interest rates, total borrows, and available liquidity for borrowing. Use these to understand pool status and individual account positions. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./liquidity/LPoolInterface.sol"; // ============================================ // CHECK BALANCES AND RATES // ============================================ // Get LToken balance uint lTokenBalance = pool.balanceOf(userAddress); // Get underlying balance (includes accrued interest) uint underlyingBalance = pool.balanceOfUnderlying(userAddress); // Get current exchange rate (underlying per LToken) uint exchangeRate = pool.exchangeRateCurrent(); // Get interest rates (scaled by 1e18, per block) uint borrowRate = pool.borrowRatePerBlock(); uint supplyRate = pool.supplyRatePerBlock(); // Get account snapshot (uint tokenBalance, uint borrowBalance, uint exchangeRateMantissa) = pool.getAccountSnapshot(userAddress); // Get total borrows uint totalBorrows = pool.totalBorrowsCurrent(); // Get available liquidity for borrowing uint available = pool.availableForBorrow(); ``` -------------------------------- ### Run Truffle Contract Tests Source: https://github.com/openleveragedev/openleverage-contracts/blob/main/README.md Execute the contract tests for OpenLeverage using Truffle. Ensure ganache-cli is running in the background to provide a test environment. ```bash truffle test ``` -------------------------------- ### GovernorAlpha: Create a Protocol Proposal Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Submit a proposal to modify protocol parameters or upgrade contracts. Requires a minimum of 1% of total xOLE supply to propose. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./gov/GovernorAlpha.sol"; // ============================================ // CREATE PROPOSAL // ============================================ // Proposer must have >= 1% of total xOLE supply address[] memory targets = new address[](1); uint[] memory values = new uint[](1); string[] memory signatures = new string[](1); bytes[] memory calldatas = new bytes[](1); targets[0] = controllerAddress; values[0] = 0; signatures[0] = "setInterestParam(uint256,uint256,uint256,uint256)"; calldatas[0] = abi.encode(newBaseRate, newMultiplier, newJumpMultiplier, newKink); uint proposalId = governor.propose( targets, values, signatures, calldatas, "Update interest rate parameters for all pools" ); ``` -------------------------------- ### GovernorAlpha: Query Governance Parameters Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Retrieve key parameters for the governance system, including quorum requirements, proposal thresholds, and voting periods. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./gov/GovernorAlpha.sol"; // ============================================ // QUERY GOVERNANCE PARAMETERS // ============================================ // 4% of total xOLE needed for quorum uint quorum = governor.quorumVotes(block.number); // 1% of total xOLE needed to propose uint threshold = governor.proposalThreshold(); // ~3 days voting period uint votingPeriod = governor.votingPeriod(); ``` -------------------------------- ### GovernorAlpha: Execute a Proposal Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Queue and execute a successful proposal after the timelock delay has passed. This action requires the proposal to have passed the voting period. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./gov/GovernorAlpha.sol"; // ============================================ // EXECUTE PROPOSAL // ============================================ // After voting period ends and proposal succeeded: // 1. Queue the proposal in timelock governor.queue(proposalId); // 2. After timelock delay, execute governor.execute(proposalId); ``` -------------------------------- ### Create Lending Pool Pair with ControllerV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Use the ControllerV1 contract to create new lending pool pairs for any token pair. This function registers the pools with OpenLev for margin trading and allows configuration of margin limits and DEX routing. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./ControllerInterface.sol"; // Creating a new lending pool pair for margin trading // This creates LPool0 for token0 and LPool1 for token1 // Deploy new market with 30% margin limit (3000 = 30.00%) bytes memory dexData = abi.encodePacked( uint8(1), // Uniswap V2 DEX index uint24(3000) // 0.3% fee tier ); controller.createLPoolPair( 0x6B175474E89094C44Da98b954EesdsdfDF3D, // DAI address 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, // WETH address 3000, // marginLimit: 30% minimum margin ratio dexData // DEX configuration ); // Event emitted: // LPoolPairCreated(token0, pool0, token1, pool1, marketId, marginLimit, dexData) ``` -------------------------------- ### Create and Manage XOLE Locks Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Use these functions to lock OLE tokens for governance voting power and fee sharing. Ensure unlock_time is within the valid range (min 2 weeks, max 4 years). ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./XOLEInterface.sol"; // ============================================ // CREATE LOCK // ============================================ // Approve OLE LP tokens for staking IERC20(oleLpToken).approve(xoleAddress, lockAmount); // Lock tokens for voting power // unlock_time must be at least 2 weeks in future, max 4 years uint256 unlockTime = block.timestamp + (365 days); // Lock for 1 year xole.create_lock( 1000 ether, // Amount of OLE LP to lock unlockTime // Unlock timestamp (rounded down to weeks) ); // Lock for another user xole.create_lock_for( recipientAddress, 500 ether, unlockTime ); // ============================================ // INCREASE LOCK // ============================================ // Add more tokens to existing lock IERC20(oleLpToken).approve(xoleAddress, additionalAmount); xole.increase_amount(500 ether); // Extend lock duration uint256 newUnlockTime = block.timestamp + (730 days); // Extend to 2 years xole.increase_unlock_time(newUnlockTime); // ============================================ // WITHDRAW (after lock expires) // ============================================ // Can only withdraw after unlock time xole.withdraw(); // ============================================ // GOVERNANCE DELEGATION // ============================================ // Delegate voting power to another address xole.delegate(delegateeAddress); // Get current votes uint votes = xole.getCurrentVotes(accountAddress); // Get historical votes at specific block uint priorVotes = xole.getPriorVotes(accountAddress, blockNumber); // Get total supply at block (for quorum calculations) uint totalVotingPower = xole.totalSupplyAt(blockNumber); // Check xOLE balance uint balance = xole.balanceOf(userAddress); ``` -------------------------------- ### DexAggregator: Calculate Swap Amounts Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Calculate the expected amount of tokens received when selling, or the amount needed to sell to acquire a specific quantity. Handles tax parameters. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./dex/DexAggregatorInterface.sol"; // ============================================ // CALCULATE SWAP AMOUNTS // ============================================ // Calculate how much you'll receive for selling uint buyAmount = dexAgg.calBuyAmount( buyToken, sellToken, 0, // buyTax (0 if not tax token) 0, // sellTax sellAmount, dexData ); // Calculate how much you need to sell to buy specific amount uint sellAmount = dexAgg.calSellAmount( buyToken, sellToken, 0, 0, buyAmount, dexData ); ``` -------------------------------- ### Redeem Liquidity from LPool Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Enables users to redeem their supplied liquidity from an LPool contract, either by specifying the amount of LTokens to redeem or the amount of underlying assets to receive. This process burns LTokens and returns the corresponding underlying assets plus accrued interest. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./liquidity/LPoolInterface.sol"; // ============================================ // REDEEM LIQUIDITY // ============================================ // Redeem by LToken amount pool.redeem(500 ether); // Redeem 500 LTokens // Redeem by underlying amount pool.redeemUnderlying(1000 ether); // Get exactly 1000 underlying ``` -------------------------------- ### Payoff Leveraged Trade with OpenLevV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Use the OpenLevV1 contract's payoffTrade function to repay borrowed amounts directly with external funds, without needing to sell held tokens. Ensure the repayment token is approved first. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./OpenLevInterface.sol"; // ============================================ // PAYOFF TRADE (repay debt with external funds) // ============================================ // Approve repayment token IERC20(borrowedToken).approve(openLevAddress, repayAmount); // Payoff allows repaying borrowed amount directly without selling held tokens openLev.payoffTrade(marketId, longToken); ``` -------------------------------- ### Open Leveraged Long Position with OpenLevV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Use the OpenLevV1 contract to open leveraged long positions. Ensure tokens are approved first. This function allows specifying the market, collateral, deposit amount, borrow amount, and slippage protection. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./OpenLevInterface.sol"; // ============================================ // OPENING A LONG POSITION // ============================================ // Approve tokens first IERC20(token1).approve(openLevAddress, depositAmount); // Open a long position on token0 using token1 as collateral // Parameters: // - marketId: Market pair identifier // - longToken: false = long token0, true = long token1 // - depositToken: false = deposit token0, true = deposit token1 // - deposit: Amount of deposit token // - borrow: Amount to borrow for leverage // - minBuyAmount: Minimum tokens to receive (slippage protection) // - dexData: DEX routing data bytes memory dexData = abi.encodePacked( uint8(1), // Uniswap V2 uint24(3000) // Fee tier 0.3% ); uint256 heldAmount = openLev.marginTrade( 0, // marketId false, // long token0 true, // deposit token1 as collateral 400 ether, // deposit 400 token1 500 ether, // borrow 500 token1 for ~2.25x leverage 0, // minBuyAmount (0 for no slippage check) dexData ); // For ETH deposits, send value with the transaction: openLev.marginTrade{value: 1 ether}( 1, // ETH/USDC market false, // long ETH (token0) false, // deposit ETH 0, // deposit amount (uses msg.value) 1000e6, // borrow 1000 USDC 0, dexData ); ``` -------------------------------- ### Close Leveraged Position with OpenLevV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Use the OpenLevV1 contract to close leveraged positions, either fully or partially. The function requires the market ID, whether the position is long, the amount of held tokens to close, and slippage protection parameters. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./OpenLevInterface.sol"; // ============================================ // CLOSING A POSITION // ============================================ // Get active trade details (uint deposited, uint held, bool depositToken, uint128 lastBlockNum) = openLev.activeTrades(traderAddress, marketId, longToken); // Close entire position uint256 returnedDeposit = openLev.closeTrade( 0, // marketId false, // longToken (must match open position) held, // closeHeld: amount of held tokens to close 0, // minOrMaxAmount: slippage protection dexData ); // Partial close (close 50%) uint256 partialReturn = openLev.closeTrade( 0, false, held / 2, // Close half the position 0, dexData ); ``` -------------------------------- ### Supply Liquidity to LPool Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Allows users to supply underlying tokens to an LPool contract, receiving LTokens in return. LTokens represent the user's share of the pool and accrue interest. Ensure underlying tokens are approved before minting. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./liquidity/LPoolInterface.sol"; // ============================================ // SUPPLY LIQUIDITY // ============================================ LPoolInterface pool = LPoolInterface(poolAddress); // Approve underlying token IERC20(underlyingToken).approve(poolAddress, supplyAmount); // Mint LTokens by supplying underlying pool.mint(1000 ether); // Supply 1000 tokens // For ETH pools, use mintEth() pool.mintEth{value: 10 ether}(); // Mint to another address pool.mintTo{value: 5 ether}(recipientAddress, 0); ``` -------------------------------- ### DexAggregator - Price Oracle and DEX Integration Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Provides price feeds from AMM pools and executes swaps through Uniswap V2/V3. ```APIDOC ## DexAggregator - Price Oracle and DEX Integration Provides price feeds from AMM pools and executes swaps through Uniswap V2/V3. ### Get Prices #### Get Current Spot Price ```solidity // Get current spot price (uint256 price, uint8 decimals) = dexAgg.getPrice( tokenA, // desToken (desired/quote) tokenB, // quoteToken (base) dexData ); // price = amount of tokenB per tokenA, scaled by 10^decimals ``` #### Get TWAP (Time-Weighted Average Price) ```solidity // Get TWAP (time-weighted average price) (uint256 avgPrice, uint8 decimals, uint256 timestamp) = dexAgg.getAvgPrice( tokenA, tokenB, 60, // secondsAgo: TWAP window in seconds dexData ); ``` #### Get Comprehensive Price Data (Current, cAvg, hAvg) ```solidity // Get comprehensive price data (current, cAvg, hAvg) ( uint price, uint cAvgPrice, // Current TWAP uint256 hAvgPrice, // Historical TWAP (last recorded) uint8 decimals, uint256 timestamp ) = dexAgg.getPriceCAvgPriceHAvgPrice( tokenA, tokenB, 60, dexData ); ``` ### Get Liquidity #### Get Single Token Liquidity ```solidity // Get single token liquidity uint token0Liquidity = dexAgg.getToken0Liquidity(token0, token1, dexData); ``` #### Get Both Token Liquidities ```solidity // Get both token liquidities (uint token0Liq, uint token1Liq) = dexAgg.getPairLiquidity(token0, token1, dexData); ``` ### Calculate Swap Amounts #### Calculate Receive Amount for Selling ```solidity // Calculate how much you'll receive for selling uint buyAmount = dexAgg.calBuyAmount( buyToken, sellToken, 0, // buyTax (0 if not tax token) 0, // sellTax sellAmount, dexData ); ``` #### Calculate Sell Amount to Buy Specific Amount ```solidity // Calculate how much you need to sell to buy specific amount uint sellAmount = dexAgg.calSellAmount( buyToken, sellToken, 0, 0, buyAmount, dexData ); ``` ``` -------------------------------- ### GovernorAlpha - On-Chain Governance Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Allows users to create and vote on protocol proposals to modify parameters or upgrade contracts. ```APIDOC ## GovernorAlpha - On-Chain Governance Create and vote on protocol proposals to modify parameters or upgrade contracts. ### Create Proposal *Proposer must have >= 1% of total xOLE supply.* ```solidity address[] memory targets = new address[](1); uint[] memory values = new uint[](1); string[] memory signatures = new string[](1); bytes[] memory calldatas = new bytes[](1); targets[0] = controllerAddress; values[0] = 0; signatures[0] = "setInterestParam(uint256,uint256,uint256,uint256)"; calldatas[0] = abi.encode(newBaseRate, newMultiplier, newJumpMultiplier, newKink); uint proposalId = governor.propose( targets, values, signatures, calldatas, "Update interest rate parameters for all pools" ); ``` ### Voting #### Cast Vote *(`true` = for, `false` = against)* ```solidity governor.castVote(proposalId, true); ``` #### Cast Vote by Signature (Gasless Voting) ```solidity governor.castVoteBySig(proposalId, support, v, r, s); ``` ### Execute Proposal *After voting period ends and proposal succeeded:* 1. **Queue the proposal in timelock** ```solidity governor.queue(proposalId); ``` 2. **After timelock delay, execute** ```solidity governor.execute(proposalId); ``` ### Query Governance Parameters *4% of total xOLE needed for quorum.* ```solidity // 4% of total xOLE needed for quorum uint quorum = governor.quorumVotes(block.number); // 1% of total xOLE needed to propose uint threshold = governor.proposalThreshold(); // ~3 days voting period uint votingPeriod = governor.votingPeriod(); ``` ``` -------------------------------- ### Update Price Oracle in OpenLevV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Updates the TWAP (Time-Weighted Average Price) observation for a specific market in OpenLeverage V1. This is crucial for accurate margin calculations and liquidations. Call this periodically or when market prices are expected to change significantly. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; // ============================================ // UPDATE PRICE ORACLE // ============================================ // Update TWAP price observation for a market openLev.updatePrice(marketId, dexData); ``` -------------------------------- ### Stake Tokens in Farming Pools Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Stake LP tokens or other eligible tokens to earn OLE rewards. Rewards are distributed linearly over time. Ensure tokens are approved before staking. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./farming/FarmingPools.sol"; // ============================================ // STAKE TOKENS // ============================================ // Approve stake token IERC20(stakeToken).approve(farmingPoolsAddress, stakeAmount); // Stake tokens to earn OLE rewards farmingPools.stake(stakeToken, 100 ether); // ============================================ // CHECK EARNED REWARDS // ============================================ // View pending rewards uint pendingRewards = farmingPools.earned(stakeToken, userAddress); // View reward rate and distribution info ( uint64 duration, uint64 starttime, uint64 periodFinish, uint64 lastUpdateTime, uint256 rewardRate, uint256 rewardPerTokenStored, uint256 totalStaked ) = farmingPools.distributions(stakeToken); // ============================================ // CLAIM REWARDS // ============================================ // Claim OLE rewards for single pool farmingPools.getReward(stakeToken); // Claim from multiple pools at once address[] memory pools = new address[](2); pools[0] = stakeToken1; pools[1] = stakeToken2; farmingPools.getRewards(pools); // ============================================ // WITHDRAW // ============================================ // Withdraw partial stake farmingPools.withdraw(stakeToken, 50 ether); // Exit: withdraw all and claim rewards farmingPools.exit(stakeToken); ``` -------------------------------- ### GovernorAlpha: Cast a Vote Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Vote on an active proposal. Supports direct voting or gasless voting via signature. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "./gov/GovernorAlpha.sol"; // ============================================ // VOTING // ============================================ // Cast vote (true = for, false = against) governor.castVote(proposalId, true); // Cast vote by signature (gasless voting) governor.castVoteBySig(proposalId, support, v, r, s); ``` -------------------------------- ### Liquidate Unhealthy Position in OpenLevV1 Source: https://context7.com/openleveragedev/openleverage-contracts/llms.txt Executes the liquidation of an underwater position in OpenLeverage V1. Liquidators earn a penalty reward for closing positions that fall below the margin limit. Ensure the position meets liquidation criteria before calling. ```solidity // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; // ============================================ // LIQUIDATE UNHEALTHY POSITION // ============================================ // Liquidators earn a penalty reward for closing underwater positions // Position must be below marginLimit to be liquidatable bytes memory dexData = abi.encodePacked(uint8(1), uint24(3000)); openLev.liquidate( ownerAddress, // Owner of the position to liquidate marketId, longToken, 0, // minBuy: minimum tokens to receive from selling held type(uint256).max, // maxSell: maximum held tokens to sell dexData ); // Liquidator receives penalty (default 1% of position value) // Remaining value after debt repayment goes to position owner ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.