### HTTP GET Request Example Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagerdeployment.md Demonstrates how to query documentation dynamically by making an HTTP GET request to the page URL with an 'ask' query parameter containing a natural language question. ```http GET https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagerdeployment.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.curvance.com/app/protocol-overview/liquidity-markets/collateral-and-debt-caps.md To ask questions and get dynamic answers from the documentation, perform an HTTP GET request on the page URL with the 'ask' query parameter. The question should be specific and in natural language. ```http GET https://docs.curvance.com/app/protocol-overview/liquidity-markets/collateral-and-debt-caps.md?ask= ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.curvance.com/app/miscellaneous/brand-assets.md Use this GET request to ask questions about the documentation. Append the 'ask' query parameter with your question in natural language to the current page URL. ```HTTP GET https://docs.curvance.com/app/miscellaneous/brand-assets.md?ask= ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.curvance.com/app/developer-docs/plugin-and-delegation-system.md Send an HTTP GET request to the current page URL with the 'ask' query parameter to ask a question about the documentation. The question should be specific and self-contained. Use this when the answer is not explicitly present, you need clarification, or want to retrieve related sections. ```http GET https://docs.curvance.com/app/developer-docs/plugin-and-delegation-system.md?ask= ``` -------------------------------- ### Query Documentation via HTTP GET Source: https://docs.curvance.com/app/developer-docs/lending-protocol.md Perform an HTTP GET request to the current page URL with the 'ask' query parameter to ask a question about the documentation. The response will contain a direct answer and relevant excerpts. ```HTTP GET https://docs.curvance.com/app/developer-docs/lending-protocol.md?ask= ``` -------------------------------- ### Query Documentation with AI Source: https://docs.curvance.com/app/developer-docs Perform an HTTP GET request to query the documentation dynamically. Include your question as the 'ask' query parameter. ```HTTP GET https://docs.curvance.com/app/developer-docs.md?ask= ``` -------------------------------- ### Install ethers.js v6 Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/loans-and-collateral.md Install the ethers.js library, version 6.x, to interact with the Curvance Protocol. ```bash npm install ethers@6 ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.curvance.com/app/developer-docs/dynamic-liquidation-engine-dle/bad-debt-socialization.md Perform an HTTP GET request to query documentation dynamically. Include your question as the 'ask' query parameter. ```http GET https://docs.curvance.com/app/developer-docs/dynamic-liquidation-engine-dle/bad-debt-socialization.md?ask= ``` -------------------------------- ### Bad Debt Socialization Example Calculation Source: https://docs.curvance.com/app/developer-docs/dynamic-liquidation-engine-dle/bad-debt-socialization.md Provides a concrete example of bad debt calculation for a borrower with specific debt and collateral values, including the impact of a liquidation incentive. It also demonstrates how bad debt is distributed if liquidation occurs in stages. ```plaintext For example, if a borrower has $900 in debt with $850 in collateral during a liquidation with 5% liquidation incentive, lenders collectively absorb $95 (900 * 1.05 - 850 = 945 - 850 = 95) of the debt as a loss. If the borrower is liquidated across two liquidations, 25% initially then the remaining 75%, borrowers would recognize $23.75 and then $71.25 as bad debt across the liquidations. ``` -------------------------------- ### Query Documentation with HTTP GET Source: https://docs.curvance.com/app/developer-docs/earn-vaults.md Use this method to ask questions about the documentation when the answer is not directly on the page. The question should be specific and self-contained. ```http GET https://docs.curvance.com/app/developer-docs/earn-vaults.md?ask= ``` -------------------------------- ### Query Documentation with GET Request Source: https://docs.curvance.com/app/miscellaneous/privacy-policy.md Use this method to ask questions about the documentation when the answer is not explicitly present on the current page. The question should be specific and self-contained. ```bash GET https://docs.curvance.com/app/miscellaneous/privacy-policy.md?ask= ``` -------------------------------- ### Query Documentation with 'ask' Parameter Source: https://docs.curvance.com/app/developer-docs/overview.md Perform an HTTP GET request to query the documentation dynamically. The question should be specific and in natural language. Use this when the answer is not explicitly present or for clarification. ```HTTP GET https://docs.curvance.com/app/developer-docs/overview.md?ask= ``` -------------------------------- ### LendingOptimizer.sol - Total Assets and Conversion Functions Source: https://docs.curvance.com/app/developer-docs/earn-vaults.md Get the total cached assets and convert between assets and shares using cached accounting. ```Solidity function totalAssets() public view returns (uint256); ``` ```Solidity function convertToShares(uint256 assets) public view returns (uint256 shares); ``` ```Solidity function convertToAssets(uint256 shares) public view returns (uint256 assets); ``` -------------------------------- ### Ask a Question via Documentation API Source: https://docs.curvance.com/app/llms.txt Use this GET request to query the documentation index with a specific question. The response includes direct answers and relevant excerpts. ```http GET https://docs.curvance.com/app/miscellaneous/glossary.md?ask= ``` -------------------------------- ### Deleveraging Setup and ABIs Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/leverage/deleveraging.md Initializes contract instances and defines constants required for deleveraging operations. Includes ABIs for various protocol components like MarketManager, PositionManager, and cTokens. ```javascript import { ethers } from "ethers"; const MARKET_MANAGER = "0x..."; const POSITION_MANAGER = "0x..."; const COLLATERAL_CTOKEN = "0x..."; const DEBT_CTOKEN = "0x..."; const APPROVED_SWAP_TARGET = "0x..."; const PROTOCOL_READER = "0x..."; const COLLATERAL_DECIMALS = 18; const DEBT_DECIMALS = 6; const BPS = 10_000n; const ONE_PERCENT_WAD = ethers.parseUnits("0.01", 18); const MARKET_MANAGER_ABI = [ "function isPositionManager(address positionManager) view returns (bool)", "function isListed(address cToken) view returns (bool)", "function redeemPaused() view returns (uint8)" ]; const POSITION_MANAGER_ABI = [ "function deleverage((address cToken,uint256 collateralAssets,address borrowableCToken,uint256 repayAssets,(address inputToken,uint256 inputAmount,address outputToken,address target,uint256 slippage,bytes call)[] swapActions,bytes auxData) action,uint256 slippage)", "function deleverageFor((address cToken,uint256 collateralAssets,address borrowableCToken,uint256 repayAssets,(address inputToken,uint256 inputAmount,address outputToken,address target,uint256 slippage,bytes call)[] swapActions,bytes auxData) action,address account,uint256 slippage)", "function centralRegistry() view returns (address)", "function setDelegateApproval(address delegate,bool isApproved)" ]; const CTOKEN_ABI = [ "function asset() view returns (address)", "function balanceOf(address account) view returns (uint256)", "function collateralPosted(address account) view returns (uint256)", "function previewRedeem(uint256 shares) view returns (uint256)", "function previewWithdraw(uint256 assets) view returns (uint256)" ]; const DEBT_CTOKEN_ABI = [ ...CTOKEN_ABI, "function debtBalance(address account) view returns (uint256)", "function debtBalanceUpdated(address account) returns (uint256)" ]; const CENTRAL_REGISTRY_ABI = [ "function protocolLeverageFee() view returns (uint256)" ]; const PROTOCOL_READER_ABI = [ "function getPositionHealth(address mm,address account,address cToken,address borrowableCToken,bool isDeposit,uint256 collateralAssets,bool isRepayment,uint256 debtAssets,uint256 bufferTime) view returns (uint256,bool)", "function getLeverageSnapshot(address account,address cToken,address borrowableCToken,uint256 bufferTime) view returns (uint256 collateralUsd,uint256 debtUsd,uint256 collateralAssetPrice,uint256 sharePrice,uint256 debtAssetPrice,uint256 debtTokenBalance,bool oracleError)" ]; const marketManager = new ethers.Contract( MARKET_MANAGER, MARKET_MANAGER_ABI, provider ); const positionManager = new ethers.Contract( POSITION_MANAGER, POSITION_MANAGER_ABI, signer ); const collateralCToken = new ethers.Contract( COLLATERAL_CTOKEN, CTOKEN_ABI, provider ); const debtCToken = new ethers.Contract( DEBT_CTOKEN, DEBT_CTOKEN_ABI, provider ); const protocolReader = new ethers.Contract( PROTOCOL_READER, PROTOCOL_READER_ABI, provider ); const userAddress = await signer.getAddress(); ``` -------------------------------- ### Solidity: Check Available Liquidity for Flash Loan Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment/flash-loans.md Before initiating a flash loan, verify that the cToken contract has sufficient underlying assets. This example shows how to query the available liquidity. ```solidity uint256 availableLiquidity = IBorrowableCToken(borrowableCToken).assetsHeld(); require(loanAmount <= availableLiquidity, "Insufficient liquidity"); ``` -------------------------------- ### Get Static Market Data Source: https://docs.curvance.com/app/developer-docs/protocol-reader.md Fetches immutable configuration data for all markets, including token details, collateral requirements, and liquidation parameters. Use this to understand the structural parameters of each market. ```Solidity function getStaticMarketData() public view returns (StaticMarketData[] memory data); ``` -------------------------------- ### Bad Debt Calculation Examples Source: https://docs.curvance.com/app/developer-docs/dynamic-liquidation-engine-dle/bad-debt-socialization.md Illustrates how bad debt is calculated after a liquidation event. It shows the direct calculation and how it applies when a liquidation is performed in multiple stages. ```plaintext Bad Debt = (Total Account Debt * Liquidation Incentive) - Collateral Value Or, more simply: Bad Debt = Total Account Debt - Liquidator Repayment ``` -------------------------------- ### Get Dynamic Market Data Source: https://docs.curvance.com/app/developer-docs/protocol-reader.md Retrieves real-time data for all markets, including prices, interest rates, liquidity, and utilization. Use this for up-to-date market information. ```Solidity function getDynamicMarketData() external view returns (DynamicMarketData[] memory data) ``` -------------------------------- ### Get Leverage Snapshot Source: https://docs.curvance.com/app/developer-docs/protocol-reader.md Retrieves an account's projected collateral and debt values, including underlying prices and oracle error status. Use for leverage and deleverage sizing. ```solidity function getLeverageSnapshot( address account, address cToken, address borrowableCToken, uint256 bufferTime ) external view returns ( uint256 collateralUsd, uint256 debtUsd, uint256 collateralAssetPrice, uint256 sharePrice, uint256 debtAssetPrice, uint256 debtTokenBalance, bool oracleError ); ``` -------------------------------- ### Setting up and executing a leverage action Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/leverage/leveraging.md This snippet demonstrates how to initialize contracts, check borrowability, calculate amounts, and construct the `leverageAction` object for executing a leverage operation. Ensure all addresses and ABIs are correctly defined. ```javascript const MARKET_MANAGER = "0x..."; const BORROWABLE_CTOKEN = "0x..."; const COLLATERAL_CTOKEN = "0x..."; const AGGREGATOR_ROUTER_ADDRESS = "0x..."; const DEBT_DECIMALS = 6; const ESTIMATED_COLLATERAL_OUT = ethers.parseUnits("0.49", 18); const marketManager = new ethers.Contract( MARKET_MANAGER, MARKET_MANAGER_ABI, provider ); const positionManager = new ethers.Contract( POSITION_MANAGER, POSITION_MANAGER_ABI, signer ); const debtCToken = new ethers.Contract(BORROWABLE_CTOKEN, CTOKEN_ABI, provider); const collateralCToken = new ethers.Contract( COLLATERAL_CTOKEN, CTOKEN_ABI, provider ); const [isPositionManager, debtCap, [, , borrowPaused]] = await Promise.all([ marketManager.isPositionManager(POSITION_MANAGER), marketManager.debtCaps(BORROWABLE_CTOKEN), marketManager.actionsPaused(BORROWABLE_CTOKEN) ]); if (!isPositionManager) throw new Error("PositionManager is not enabled"); if (debtCap === 0n) throw new Error("Debt cToken is not borrowable"); if (borrowPaused) throw new Error("Borrowing is paused for this debt cToken"); const [debtAsset, collateralAsset] = await Promise.all([ debtCToken.asset(), collateralCToken.asset() ]); const borrowAssets = ethers.parseUnits("500", DEBT_DECIMALS); const netSwapInput = await netAfterPositionManagerFee( positionManager, borrowAssets ); const quotedShares = await collateralCToken.previewDeposit( ESTIMATED_COLLATERAL_OUT ); const expectedShares = quotedShares * 9950n / 10_000n; // 0.50% share buffer. // Aggregator calldata must send output to POSITION_MANAGER. const swapCalldata = "0x..."; const swapAction = { inputToken: debtAsset, inputAmount: netSwapInput, outputToken: collateralAsset, target: AGGREGATOR_ROUTER_ADDRESS, slippage: WAD_SLIPPAGE_ONE_PERCENT, call: swapCalldata }; const leverageAction = { borrowableCToken: BORROWABLE_CTOKEN, borrowAssets, cToken: COLLATERAL_CTOKEN, expectedShares, swapAction, auxData: "0x" }; ``` -------------------------------- ### JavaScript Example: Initiating a Flash Loan Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment/flash-loans.md This JavaScript snippet demonstrates how to set up an ethers.js contract instance and execute a flash loan. It includes helper functions for quoting loan details and running the loan. Ensure you replace placeholder addresses and private keys with your actual deployment values. ```javascript import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("YOUR_RPC_URL"); const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const cTokenAddress = "0x..."; const flashBorrowerAddress = "0x..."; const FLASH_CTOKEN_ABI = [ "function asset() view returns (address)", "function flashFee(uint256 assets) view returns (uint256)", "function flashLoan(uint256 assets, bytes data)", "event Flashloan(uint256 assets, uint256 assetsFee, address account)" ]; const ERC20_ABI = [ "function balanceOf(address account) view returns (uint256)", "function decimals() view returns (uint8)" ]; const FLASH_BORROWER_ABI = [ "function executeFlashLoan(uint256 assets, bytes data)" ]; const cToken = new ethers.Contract(cTokenAddress, FLASH_CTOKEN_ABI, wallet); const flashBorrower = new ethers.Contract( flashBorrowerAddress, FLASH_BORROWER_ABI, wallet ); async function quoteFlashLoan(assets) { if (assets === 0n) throw new Error("Flash-loan amount must be greater than zero"); const assetAddress = await cToken.asset(); const underlying = new ethers.Contract(assetAddress, ERC20_ABI, provider); const [available, fee, decimals] = await Promise.all([ underlying.balanceOf(cTokenAddress), cToken.flashFee(assets), underlying.decimals() ]); if (assets > available) { throw new Error("Requested flash loan exceeds cToken underlying balance"); } return { assetAddress, available, fee, totalRepayment: assets + fee, decimals }; } async function runFlashLoan(assets, data = "0x") { const quote = await quoteFlashLoan(assets); console.log( `Fee: ${ethers.formatUnits(quote.fee, quote.decimals)} underlying` ); const tx = await flashBorrower.executeFlashLoan(assets, data); const receipt = await tx.wait(); return receipt; } ``` -------------------------------- ### Get CombinedAggregator Struct Fields Source: https://docs.curvance.com/app/developer-docs/oracles/price-guard.md Use this function to retrieve the dynamic growth start timestamp, per-second growth rate, base price, and minimum price from the CombinedAggregator struct. ```solidity function pg() external view returns (uint40 timestampStart, uint40 ips, uint88 basePrice, uint88 minPrice); ``` -------------------------------- ### Get Stale Debt Balance (View) Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment.md Use the plain `view` version `cUSDC.debtBalance` to get the last-accrued value, suitable for non-critical displays. ```javascript const staleDebt = await cUSDC.debtBalance(wallet.address); ``` -------------------------------- ### Get Current Debt Balance Source: https://docs.curvance.com/app/developer-docs/lending-protocol/borrowablectoken.md Use the `debtBalance()` view function to get an account's current debt balance without accruing pending interest. It uses stored debt amounts and indices, not the cToken exchange rate. ```Solidity function debtBalance(address account) public view returns (uint256 r) ``` -------------------------------- ### Setup Ethers.js Environment and Contracts Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/leverage.md Initialize ethers.js provider, signer, and contract instances for interacting with the Curvance protocol. Ensure you replace placeholder addresses and RPC URLs with your actual deployment details. ```javascript import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("YOUR_RPC_URL"); const signer = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const userAddress = await signer.getAddress(); const MARKET_MANAGER = "0x..."; const CENTRAL_REGISTRY = "0x..."; const POSITION_MANAGER = "0x..."; const C_TOKEN_COLLATERAL = "0x..."; const C_TOKEN_DEBT = "0x..."; const PROTOCOL_READER = "0x..."; const APPROVED_SWAP_TARGET = "0x..."; const ERC20_ABI = [ "function allowance(address owner,address spender) view returns (uint256)", "function approve(address spender,uint256 amount) returns (bool)", "function decimals() view returns (uint8)" ]; const marketManager = new ethers.Contract(MARKET_MANAGER, MARKET_MANAGER_ABI, provider); const centralRegistry = new ethers.Contract(CENTRAL_REGISTRY, CENTRAL_REGISTRY_ABI, provider); const positionManager = new ethers.Contract(POSITION_MANAGER, POSITION_MANAGER_ABI, signer); const collateralCToken = new ethers.Contract(C_TOKEN_COLLATERAL, CTOKEN_ABI, provider); const debtCToken = new ethers.Contract(C_TOKEN_DEBT, CTOKEN_ABI, provider); const protocolReader = new ethers.Contract(PROTOCOL_READER, PROTOCOL_READER_ABI, provider); ``` -------------------------------- ### Get Grace Period Time Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Returns the configured grace period time in seconds for uptime feeds. ```solidity function GRACE_PERIOD_TIME() external view returns (uint256); ``` -------------------------------- ### deployMarket Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagerdeployment.md Deploys a new market by listing specified tokens, initializing their reserve deposits, pausing minting, setting token configurations, and recording a pending one-time mint unpause. ```APIDOC ## deployMarket ### Description Deploys a new market by listing specified tokens, initializing their reserve deposits, pausing minting, setting token configurations, and recording a pending one-time mint unpause. ### Signature ```solidity function deployMarket( address marketManager, address token0, address token1, MarketManagerIsolated.TokenConfig memory config0, MarketManagerIsolated.TokenConfig memory config1 ) external ``` ### Parameters - `marketManager` (address): The address of the market manager. - `token0` (address): The address of the first token. - `token1` (address): The address of the second token. - `config0` (MarketManagerIsolated.TokenConfig): The configuration for the first token. - `config1` (MarketManagerIsolated.TokenConfig): The configuration for the second token. ### Integration Considerations - The owner must approve `ProtocolManagerDeployment` for raw units of each underlying asset before calling this function. - The target market manager must be registered in `CentralRegistry`. - The manager contract must have market permissions. - Minting will be paused immediately after deployment. ``` -------------------------------- ### Get Adaptor Type Source: https://docs.curvance.com/app/developer-docs/oracles/adaptors.md Retrieves the adaptor type based on the adaptor name. This function is part of the BaseOracleAdaptor contract. ```solidity function adaptorType() external view returns (uint256 result); ``` -------------------------------- ### Get Minimum Deviation Bound Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Returns the minimum allowed deviation bound, specified in Basis Points (BPS). ```solidity function MIN_DEVIATION_BOUND() external view returns (uint256); ``` -------------------------------- ### Get Maximum Deviation Bound Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Returns the maximum allowed deviation bound, specified in Basis Points (BPS). ```solidity function MAX_DEVIATION_BOUND() external view returns (uint256); ``` -------------------------------- ### Get Underlying Aggregator Source: https://docs.curvance.com/app/developer-docs/oracles/adaptors.md Returns the IChainlink interface of the underlying aggregator used by the wrapper. This function is part of the BaseWrappedAggregator contract. ```solidity function underlyingAggregator() public view returns (IChainlink result); ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.curvance.com/app/developer-docs/position-management/leverage.md Use this method to ask questions about the documentation when information is not explicitly present. The response includes a direct answer and relevant excerpts. ```http GET https://docs.curvance.com/app/developer-docs/position-management/leverage.md?ask= ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment/borrow.md Perform an HTTP GET request to query documentation dynamically with the 'ask' query parameter. Use this when the answer is not explicitly present, you need clarification, or want to retrieve related documentation. ```http GET https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment/borrow.md?ask= ``` -------------------------------- ### Get Linked Token Address Source: https://docs.curvance.com/app/developer-docs/lending-protocol/dynamic-interest-rate-model.md Returns the borrowable Curvance token address linked to this interest rate model contract. ```solidity function linkedToken() external view returns (address result); ``` -------------------------------- ### Get Updated Exchange Rate Source: https://docs.curvance.com/app/developer-docs/lending-protocol/ctoken.md Retrieves the current exchange rate after updating interest. This determines the value of cTokens in underlying assets. ```Solidity function exchangeRateUpdated() external returns (uint256) ``` -------------------------------- ### Setup for Repaying Debt with ethers.js Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment/repaying-debt.md Initializes ethers.js provider, wallet, and contract instances for interacting with cUSDC, USDC, and the protocol reader. Ensure you replace placeholder addresses and RPC URLs with actual values. ```javascript import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("YOUR_RPC_URL"); const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const cUSDCAddress = "0x..."; const USDCAddress = "0x..."; const protocolReaderAddress = "0x..."; const cUSDC = new ethers.Contract(cUSDCAddress, BORROWABLE_CTOKEN_ABI, wallet); const USDC = new ethers.Contract(USDCAddress, ERC20_ABI, wallet); const protocolReader = new ethers.Contract( protocolReaderAddress, PROTOCOL_READER_ABI, provider ); const marketManager = new ethers.Contract( await cUSDC.marketManager(), MARKET_MANAGER_ABI, provider ); ``` -------------------------------- ### Mint cTokens Source: https://docs.curvance.com/app/developer-docs/lending-protocol/ctoken.md Deposits underlying assets to mint cTokens. The receiver gets the minted shares. Returns the underlying assets consumed. ```solidity function mint(uint256 shares, address receiver) public nonReentrant returns (uint256 assets) ``` ```solidity // Emitted from cToken and underlying asset. event Transfer(address indexed from, address indexed to, uint256 value); ``` -------------------------------- ### Constructor Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagerdeployment.md Initializes the ProtocolManagerDeployment contract with a central registry and an owner address. It validates the provided central registry and ensures the owner address is not zero. ```APIDOC ## Constructor ### Description Initializes the ProtocolManagerDeployment contract with a central registry and an owner address. It validates the provided central registry and ensures the owner address is not zero. ### Signature ```solidity constructor(ICentralRegistry cr, address _owner) ``` ``` -------------------------------- ### Get Central Registry Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Returns the ICentralRegistry interface address used for permission checks and uptime-oracle lookups within the Oracle Manager. ```solidity function centralRegistry() external view returns (ICentralRegistry); ``` -------------------------------- ### Constructor Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanager.md Deploys the manager, validates the central registry, stores the operational authority, configures the initial managed addresses, and stores immutable capability flags. ```APIDOC ## Constructor ```solidity constructor( ICentralRegistry cr, address pm, ProtocolManager.PermsConfig memory p, address[] memory managedAddresses, ProtocolManager.PeriodLimits[] memory l ); ``` Deploys the manager, validates the central registry, stores the operational authority, configures the initial managed addresses, and stores immutable capability flags. ``` -------------------------------- ### Get Price Guard Configuration Source: https://docs.curvance.com/app/developer-docs/oracles/price-guard.md Retrieves the configured `PriceGuard` for a given asset and denomination. A `basePrice` of 0 indicates that the guard is disabled. ```Solidity function getPriceGuard( address asset, bool inUSD ) external view returns (PriceGuard memory); ``` -------------------------------- ### Build Simple Leverage Action Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/leverage.md Constructs the action object for a simple ERC20-to-ERC20 leverage operation. Asserts preconditions like enabled PositionManager, borrowable debt cToken, and non-paused borrowing. ```javascript const WAD = 10n ** 18n; const ONE_PERCENT = ethers.parseUnits("0.01", 18); async function assertLeveragePreconditions() { const [isPM, debtCap, [, , borrowPaused]] = await Promise.all([ marketManager.isPositionManager(POSITION_MANAGER), marketManager.debtCaps(C_TOKEN_DEBT), marketManager.actionsPaused(C_TOKEN_DEBT) ]); if (!isPM) throw new Error("PositionManager is not enabled for this market"); if (debtCap === 0n) throw new Error("Debt cToken is not borrowable in this market"); if (borrowPaused) throw new Error("Borrowing is paused for the debt cToken"); } async function buildSimpleLeverageAction({ borrowAmount, quotedCollateralOut, swapCalldata }) { await assertLeveragePreconditions(); const netBorrowAmount = await netAfterPositionManagerFee(borrowAmount); const [debtAsset, collateralAsset] = await Promise.all([ debtCToken.asset(), collateralCToken.asset() ]); const expectedShares = await collateralCToken.previewDeposit(quotedCollateralOut); return { borrowableCToken: C_TOKEN_DEBT, borrowAssets: borrowAmount, cToken: C_TOKEN_COLLATERAL, expectedShares, swapAction: { inputToken: debtAsset, inputAmount: netBorrowAmount, outputToken: collateralAsset, target: APPROVED_SWAP_TARGET, slippage: ONE_PERCENT, call: swapCalldata }, auxData: "0x" }; } ``` -------------------------------- ### Get Asset Price Source: https://docs.curvance.com/app/developer-docs/protocol-reader.md Retrieves the price of an asset, either in USD or native token terms. Handles oracle errors with specific codes. ```Solidity function getPrice( address asset, bool inUSD, bool getLower) public view returns( uint256 price, uint256 errorCode ); ``` -------------------------------- ### Simulate Non-Auction Liquidation with `canLiquidate` Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/liquidations/non-auction-liquidations.md Simulate a liquidation to determine the amount of debt to repay and the collateral shares received. Ensure accounts are sorted and unique. This simulation is crucial for pre-calculating liquidation outcomes before submitting a transaction. ```javascript // Accounts MUST be sorted ascending with no duplicates const accounts = [ "0x1111111111111111111111111111111111111111", "0x2222222222222222222222222222222222222222", "0x3333333333333333333333333333333333333333", ]; // Empty debtAmounts means "liquidate the maximum for each account" const debtAmounts = new Array(accounts.length).fill(0n); const liquidatorAddress = await signer.getAddress(); // Simulate to get liquidatedShares[], total debtRepaid, and any badDebt const [result] = await marketManager.canLiquidate.staticCall( debtAmounts, liquidatorAddress, accounts, { collateralToken: COLLATERAL_CTOKEN, debtToken: DEBT_CTOKEN, numAccounts: BigInt(accounts.length), liquidateExact: false, liquidatedShares: 0n, debtRepaid: 0n, badDebt: 0n, } ); console.log(`Will repay: ${result.debtRepaid}`); console.log(`Will receive (cToken shares): ${result.liquidatedShares}`); if (result.badDebt > 0n) { console.warn(`Liquidation will realize ${result.badDebt} of bad debt`); } ``` -------------------------------- ### Configuration Read: Get Current Period Timestamp Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanager.md Returns the current period timestamp, useful for querying period adjustments for the active period. ```solidity function getPeriodTimestamp() public view returns (uint256 x); ``` -------------------------------- ### Deploy Market Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagermasspause.md Deploys a new market, initializing reserves, pausing minting, and recording a pending one-time mint unpause. The owner must approve the ProtocolManagerDeployment contract for underlying asset units before calling this function. ```solidity function deployMarket( address marketManager, address token0, address token1, MarketManagerIsolated.TokenConfig memory config0, MarketManagerIsolated.TokenConfig memory config1 ) external; ``` -------------------------------- ### Check Market Information (Rates, Debt, Utilization) Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment.md Inspect current market state by checking stale and fresh exchange rates, total outstanding debt, and utilization. This helps anticipate borrowing costs. ```javascript async function checkMarketInfo() { const USDCDecimals = await USDC.decimals(); // Exchange-rate reads are WAD-scaled share-to-asset rates. const rateStale = await cUSDC.exchangeRate(); const rateFresh = await cUSDC.exchangeRateUpdated.staticCall(); console.log(`Stale exchange rate: ${ethers.formatUnits(rateStale, 18)}`); console.log(`Fresh exchange rate: ${ethers.formatUnits(rateFresh, 18)}`); // marketOutstandingDebt is a public uint240 storage variable. It reflects // last-accrued debt for this cToken's underlying asset. const totalBorrowsStale = await cUSDC.marketOutstandingDebt(); const totalBorrowsFresh = await cUSDC.marketOutstandingDebtUpdated.staticCall(); console.log( `Total USDC debt (stale): ${ethers.formatUnits(totalBorrowsStale, USDCDecimals)}` ); console.log( `Total USDC debt (fresh): ${ethers.formatUnits(totalBorrowsFresh, USDCDecimals)}` ); // A stale but internally consistent utilization display. const idleAssetsStale = await cUSDC.assetsHeld(); const WAD = 10n ** 18n; const utilizationStale = totalBorrowsStale === 0n ? 0n : (totalBorrowsStale * WAD) / (idleAssetsStale + totalBorrowsStale); console.log(`Utilization (stale): ${ethers.formatUnits(utilizationStale, 18)}`); return { rateFresh, totalBorrowsFresh, utilizationStale }; } ``` -------------------------------- ### Get Adjusted Answer Source: https://docs.curvance.com/app/developer-docs/oracles/adaptors.md Calculates and returns the adjusted answer for a given underlying answer. Child contracts define the specific adjustment logic. ```solidity function getAdjustedAnswer(int256 answer) public view returns (int256 result); ``` -------------------------------- ### Get Underlying Asset for cToken Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Retrieves the underlying asset address for a given Curvance cToken. Returns address(0) if the cToken is not registered. ```solidity function cTokens(address cToken) external view returns (address); ``` -------------------------------- ### PriceGuard Struct Definition Source: https://docs.curvance.com/app/developer-docs/oracles/price-guard.md Defines the fields for a price guard, including start time, growth rate, base price, and minimum price. ```solidity struct PriceGuard { uint40 timestampStart; uint40 ips; uint88 basePrice; uint88 minPrice; } ``` -------------------------------- ### previewMint Source: https://docs.curvance.com/app/developer-docs/lending-protocol/ctoken.md Simulates the amount of underlying assets required to mint a specified number of cToken shares without actually performing the mint operation. ```APIDOC ## previewMint() ### Description Simulates the amount of underlying assets required to mint a specified number of cToken shares without actually performing the mint operation. ### Function Signature ```solidity function previewMint(uint256 shares) public view override returns (uint256) ``` ### Parameters #### Path Parameters - **shares** (uint256) - Required - The number of assets, quoted as shares to preview a mint call. ### Return Data #### Success Response - **uint256** - The assets required to mint `shares`. ``` -------------------------------- ### DeployProtocolManager Script Source: https://docs.curvance.com/app/developer-docs/protocol-managers/protocolmanagerdeployment.md This script deploys the ProtocolManagerDeployment contract. It requires the address of the central registry and the owner address for the deployment. After deployment, market permissions must be granted to the new contract. ```solidity function run( address registry, address ownerAddress ) external; ``` -------------------------------- ### Redeem Shares for Assets Source: https://docs.curvance.com/app/developer-docs/lending-protocol/ctoken.md Burns shares to receive underlying assets. The receiver gets the assets. Returns the amount of underlying assets sent to the receiver. ```solidity function redeem( uint256 shares, address receiver, address owner) external returns (uint256 assets) ``` ```solidity // From cToken event Withdraw(address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares); event Transfer(address indexed from, address indexed to, uint256 value); ``` ```solidity // From MarketManager event PositionUpdated(address cToken, address account, bool open); ``` -------------------------------- ### previewDeposit Source: https://docs.curvance.com/app/developer-docs/lending-protocol/ctoken.md Simulates the number of cToken shares that would be received for a given deposit amount without actually performing the deposit. ```APIDOC ## previewDeposit() ### Description Simulates the number of cToken shares that would be received for a given deposit amount without actually performing the deposit. ### Function Signature ```solidity function previewDeposit(uint256 assets) public view override returns (uint256) ``` ### Parameters #### Path Parameters - **assets** (uint256) - Required - The number of assets to preview a deposit call. ### Return Data #### Success Response - **uint256** - The shares received for depositing `assets`. ``` -------------------------------- ### Get Fresh Debt Balance via StaticCall Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment.md Call `cUSDC.debtBalanceUpdated` with `staticCall` for a wei-accurate read at the current block. This function accrues interest before returning. ```javascript const freshDebt = await cUSDC.debtBalanceUpdated.staticCall(wallet.address); ``` -------------------------------- ### Get Minimum Caution to Bad Source Delta Source: https://docs.curvance.com/app/developer-docs/oracles/oracle-manager.md Returns the minimum required gap between caution and bad-source bounds, specified in Basis Points (BPS). ```solidity function MIN_CAUTION_TO_BAD_SOURCE_DELTA() external view returns (uint256); ``` -------------------------------- ### mint() Source: https://docs.curvance.com/app/developer-docs/earn-vaults.md Mints an exact amount of optimizer shares by depositing the required amount of underlying assets. The caller must approve the optimizer to spend the required underlying assets. ```APIDOC ## mint() ### Description Mints an exact amount of optimizer shares by depositing the required amount of underlying assets. ### Method Public ### Contract `LendingOptimizer.sol` ### Function Signature ```solidity function mint(uint256 shares, address receiver) public returns (uint256 assets) ``` ### Parameters #### Inputs - **shares** (uint256) - Required - Exact optimizer shares to mint. - **receiver** (address) - Required - Account that receives optimizer shares. ### Return Data #### Assets - **assets** (uint256) - Underlying assets pulled from the caller. ### Events - `Deposit(address indexed by, address indexed owner, uint256 assets, uint256 shares)` - `PerformanceFeeAccrued(uint256 feeShares, address indexed recipient)` (if accrual charges a performance fee) ### Notes Caller must approve the optimizer to spend the required underlying assets. Reverts if `shares == 0`, the optimizer is uninitialized, deposits are paused, any approved market has minting paused, or cToken rounding makes the tracked assets insufficient for the requested shares. ``` -------------------------------- ### Initialize Curvance Contracts with Ethers.js Source: https://docs.curvance.com/app/developer-docs/quick-start-guides/borrowing-and-repayment.md Set up your development environment by initializing contract instances for cUSDC, USDC, and the ProtocolReader using ethers v6. Ensure you source the correct contract addresses and ABIs for your target chain. ```javascript const { ethers } = require('ethers'); const provider = new ethers.JsonRpcProvider('YOUR_RPC_URL'); const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider); // Placeholder addresses. Source the real values from the deployment registry // for the chain you're targeting. const cUSDCAddress = '0x...'; // cUSDC contract for your target market const USDCAddress = '0x...'; // underlying USDC token on your target chain const protocolReaderAddr = '0x...'; // Curvance ProtocolReader // Initialize contract instances with the appropriate ABIs const cUSDC = new ethers.Contract(cUSDCAddress, BORROWABLE_CTOKEN_ABI, wallet); const USDC = new ethers.Contract(USDCAddress, ERC20_ABI, wallet); const protocolReader = new ethers.Contract(protocolReaderAddr, PROTOCOL_READER_ABI, provider); ```