### Get Asset Price Feeds Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to get the price feed addresses for assets supported by a Compound III instance. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const assetAddress = "YOUR_ASSET_ADDRESS"; // The asset for which you want the price feed address const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAssetInfo(address asset) external view returns (uint80, uint8, uint24, uint128, uint128, uint64)" ]; async function getAssetPriceFeed() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); // The getAssetInfo function returns several values. The price feed address is not directly returned here. // In Compound III, price feeds are typically managed by a Price Oracle contract. // You would need to get the address of the Price Oracle contract first. // Placeholder: Get the Price Oracle contract address (this varies by deployment) // const priceOracleAddress = await comptrollerContract.getPriceOracle(); // Example method const priceOracleAddress = "YOUR_PRICE_ORACLE_ADDRESS"; // Replace with actual address if known if (!priceOracleAddress || priceOracleAddress === ethers.constants.AddressZero) { console.log("Price Oracle address not found or is zero address."); return; } console.log(`Price Oracle Address: ${priceOracleAddress}`); // To get the specific price feed for an asset, you would interact with the Price Oracle contract. // The exact method depends on the oracle implementation. // Example: If the oracle has a 'getFeed(address asset)' method: // const priceOracleContract = new ethers.Contract(priceOracleAddress, priceOracleAbi, provider); // const priceFeedAddress = await priceOracleContract.getFeed(assetAddress); // console.log(`Price feed for asset ${assetAddress}: ${priceFeedAddress}`); console.log("Note: The exact method to get the price feed address depends on the Price Oracle implementation."); } getAssetPriceFeed().catch(console.error); ``` -------------------------------- ### Get Supported Asset Addresses Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve a list of supported asset addresses from Compound III. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAllMarkets() external view returns (address[] memory)" ]; async function getSupportedAssets() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const supportedAssets = await comptrollerContract.getAllMarkets(); console.log("Supported Assets:"); supportedAssets.forEach(assetAddress => { console.log(assetAddress); }); } getSupportedAssets().catch(console.error); ``` -------------------------------- ### Install Dependencies Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Run this command to install all project dependencies. ```bash npm install ``` -------------------------------- ### Get Asset Price from Compound III Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve an asset's price from the Compound III protocol's perspective. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const assetAddress = "YOUR_ASSET_ADDRESS"; // Address of the asset you want the price for const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAssetInfo(address asset) external view returns (uint80, uint8, uint24, uint128, uint128, uint64)" ]; async function getAssetPrice() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const [errorCode, asset dạ, supplyPerBlock, borrowPerBlock, collateralFactor, flashLoanCollateralFactor] = await comptrollerContract.getAssetInfo(assetAddress); // The price is typically represented as a scaled integer. You'll need to know the price feed's decimals. // For simplicity, let's assume the price feed has 8 decimals and the asset has 18 decimals. // You would typically get the price feed decimals from another source or contract. const priceFeedDecimals = 8; const assetDecimals = 18; // To get the actual price, you'd usually query a price oracle or feed. // This example assumes 'asset dạ' is related to the price, but in a real scenario, // you'd use a method like 'getPrice(assetAddress)' on a price oracle contract. // For demonstration, let's simulate getting a price. // Placeholder for actual price retrieval logic: // const priceOracleAddress = "YOUR_PRICE_ORACLE_ADDRESS"; // const priceOracleAbi = ["function getPrice(address _asset) external view returns (uint256)"]; // const priceOracleContract = new ethers.Contract(priceOracleAddress, priceOracleAbi, provider); // const price = await priceOracleContract.getPrice(assetAddress); // Simulating a price for demonstration: const simulatedPrice = ethers.utils.parseUnits("1500", priceFeedDecimals); // e.g., $1500 console.log(`Simulated price for asset ${assetAddress}: ${ethers.utils.formatUnits(simulatedPrice, priceFeedDecimals)}`); // Note: The actual price retrieval depends on the specific Compound III deployment and its oracles. } getAssetPrice().catch(console.error); ``` -------------------------------- ### Supply Collateral to Compound III Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to supply collateral to Compound III. Refer to the JavaScript file for implementation details. ```Solidity pragma solidity ^0.8.19; import { ComptrollerInterface, CometInterface, ERC20Interface } from "./interfaces.sol"; contract MyContract { ComptrollerInterface public immutable comptroller; CometInterface public immutable comet; ERC20Interface public immutable asset; constructor(address _comptroller, address _comet, address _asset) { comptroller = ComptrollerInterface(_comptroller); comet = CometInterface(_comptroller); asset = ERC20Interface(_asset); } function supplyCollateral() public { // Approve the Comet contract to spend your asset tokens asset.approve(address(comet), type(uint256).max); // Supply the asset to the Comet contract comet.supply(asset, 1000000000000000000); // Example amount } } ``` -------------------------------- ### Solidity Contract Import Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of importing the CometInterface in a Solidity contract. ```solidity pragma solidity 0.8.13; import "./CometInterface.sol"; contract MyContract { //... ``` -------------------------------- ### Get Borrow Capacity for an Account Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to determine the borrow capacity for a Compound III account. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const accountAddress = "YOUR_ACCOUNT_ADDRESS"; // The address of the account to check const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAccountLimits(address account) external view returns (uint borrowCap, uint supplyCap)" ]; async function getBorrowCapacity() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const [borrowCap, supplyCap] = await comptrollerContract.getAccountLimits(accountAddress); // The borrow capacity is typically represented as a scaled integer. // You'll need to know the decimals of the base asset to format this correctly. const baseAssetDecimals = 18; // Assuming base asset has 18 decimals console.log(`Borrow Capacity for ${accountAddress}: ${ethers.utils.formatUnits(borrowCap, baseAssetDecimals)}`); console.log(`Supply Capacity for ${accountAddress}: ${ethers.utils.formatUnits(supplyCap, baseAssetDecimals)}`); } getBorrowCapacity().catch(console.error); ``` -------------------------------- ### Get Borrow and Liquidate Collateral Factors Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve the borrow and liquidate collateral factors for a Compound III asset. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const assetAddress = "YOUR_ASSET_ADDRESS"; // The asset for which to get collateral factors const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAssetInfo(address asset) external view returns (uint80, uint8, uint24, uint128, uint128, uint64)" ]; async function getCollateralFactors() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); // The getAssetInfo function returns: error code, asset dạ, supply per block, borrow per block, collateral factor, flash loan collateral factor const [errorCode, asset dạ, supplyPerBlock, borrowPerBlock, collateralFactor, flashLoanCollateralFactor] = await comptrollerContract.getAssetInfo(assetAddress); // Collateral factor is typically represented as a percentage (e.g., 8000 for 80%). const collateralFactorPercentage = (collateralFactor / 10000) * 100; const flashLoanCollateralFactorPercentage = (flashLoanCollateralFactor / 10000) * 100; console.log(`Collateral Factor for ${assetAddress}: ${collateralFactorPercentage.toFixed(2)}%`); console.log(`Flash Loan Collateral Factor for ${assetAddress}: ${flashLoanCollateralFactorPercentage.toFixed(2)}%`); } getCollateralFactors().catch(console.error); ``` -------------------------------- ### Get Principal Amount of Asset Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve the principal amount of an asset for a Compound III account. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const accountAddress = "YOUR_ACCOUNT_ADDRESS"; // The account to check const cometAddress = "YOUR_COMET_ADDRESS"; // The Comet contract for the specific asset const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAccountLiquidity(address account) external view returns (uint, uint, uint)" ]; const cometAbi = [ // ... Comet ABI snippets ... "function borrowBalanceStored() external view returns (uint)", "function asset() external view returns (address)" ]; async function getPrincipalAmount() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const cometContract = new ethers.Contract(cometAddress, cometAbi, provider); // The borrowBalanceStored() function on the Comet contract gives the principal borrow amount. const principal = await cometContract.borrowBalanceStored(); // You need to know the decimals of the base asset to format this correctly. const baseAssetDecimals = 18; // Assuming base asset has 18 decimals console.log(`Principal borrow amount for account ${accountAddress} in ${cometAddress}: ${ethers.utils.formatUnits(principal, baseAssetDecimals)}`); // Note: getAccountLiquidity() on Comptroller provides overall account health, not specific asset principal. } getPrincipalAmount().catch(console.error); ``` -------------------------------- ### Deploy Compound III Locally Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Deploy Compound III to a local Ethereum node. This involves cloning the repository, installing dependencies, starting a local node, and then deploying the contracts. ```bash ## In one command line window: git clone https://github.com/compound-finance/comet.git cd comet/ yarn install ## This runs the ethereum node locally ## The development mnemonic or private keys can be configured in hardhat.config.ts npx hardhat node ## In another command line window: cd comet/ ## This deploys to the running local ethereum node ## It also writes deployment information to ./deployments/localhost/ yarn deploy --network localhost ``` -------------------------------- ### Get Supply or Borrow APR Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve the Supply or Borrow Annual Percentage Rate (APR) from the Compound III protocol. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const cometAddress = "YOUR_COMET_ADDRESS"; // Address of the specific asset's Comet contract const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getSupplyRate(address market) external view returns (uint)", "function getBorrowRate(address market) external view returns (uint)" ]; async function getAPR() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); // Get Supply APR const supplyRate = await comptrollerContract.getSupplyRate(cometAddress); // The rate is typically a scaled integer (e.g., representing basis points per second). // To convert to APR, you need to multiply by seconds in a year and divide by the scaling factor. const secondsInYear = 365 * 24 * 60 * 60; // Assuming the rate is scaled by 1e18 (common for rates) const supplyAPR = (supplyRate / 1e18) * secondsInYear * 100; // Convert to percentage console.log(`Supply APR for ${cometAddress}: ${supplyAPR.toFixed(4)}%`); // Get Borrow APR const borrowRate = await comptrollerContract.getBorrowRate(cometAddress); // Similar conversion for borrow rate const borrowAPR = (borrowRate / 1e18) * secondsInYear * 100; // Convert to percentage console.log(`Borrow APR for ${cometAddress}: ${borrowAPR.toFixed(4)}%`); } getAPR().catch(console.error); ``` -------------------------------- ### Borrow Base Asset from Compound III Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to borrow the base asset from Compound III. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const signer = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const cometAddress = "YOUR_COMET_ADDRESS"; // Address of the specific asset's Comet contract const baseAssetAddress = "YOUR_BASE_ASSET_ADDRESS"; // Address of the base asset (e.g., WETH) const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function enterMarkets(address[] memory markets) external returns (uint[] memory errors)", "function getAccountLimits(address account) external view returns (uint borrowCap, uint supplyCap)" ]; const cometAbi = [ // ... Comet ABI snippets ... "function borrow(uint amount) external returns (uint)", "function borrowBalanceStored() external view returns (uint)" ]; const assetAbi = [ // ... ERC20 ABI snippets ... "function approve(address spender, uint256 amount) external returns (bool)", "function balanceOf(address account) external view returns (uint256)" ]; async function borrowBaseAsset() { const cometContract = new ethers.Contract(cometAddress, cometAbi, signer); const assetContract = new ethers.Contract(baseAssetAddress, assetAbi, signer); // Ensure you have entered the market (if necessary for your setup) // const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, signer); // await comptrollerContract.enterMarkets([cometAddress]); // Borrow a specific amount of the base asset const borrowAmount = ethers.utils.parseUnits("10", 18); // Example: Borrow 10 units of the base asset await cometContract.borrow(borrowAmount); console.log(`Successfully borrowed ${ethers.utils.formatUnits(borrowAmount, 18)} of the base asset.`); // You can also check your current borrow balance const currentBorrowBalance = await cometContract.borrowBalanceStored(); console.log(`Current borrow balance: ${ethers.utils.formatUnits(currentBorrowBalance, 18)}`); } borrowBaseAsset().catch(console.error); ``` -------------------------------- ### Get Total Value Locked (TVL) Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to retrieve the Total Value Locked (TVL) in the Compound III protocol. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getAssetsInMarkets() external view returns (address[] memory)", "function getAssetInfo(address asset) external view returns (uint80, uint8, uint24, uint128, uint128, uint64)" ]; // Placeholder for a price oracle contract to get asset prices const priceOracleAbi = [ "function getPrice(address asset) external view returns (uint256)" ]; const priceOracleAddress = "YOUR_PRICE_ORACLE_ADDRESS"; async function getTotalValueLocked() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const priceOracleContract = new ethers.Contract(priceOracleAddress, priceOracleAbi, provider); const markets = await comptrollerContract.getAssetsInMarkets(); let totalValueLocked = ethers.constants.Zero; for (const marketAddress of markets) { // Get asset info to find total supply (usually stored in the Comet contract) // This example assumes you can get total supply directly or via another method. // In a real scenario, you'd query the specific Comet contract for total supply. // Placeholder for getting total supply of the asset in the market // const cometContract = new ethers.Contract(marketAddress, cometAbi, provider); // const totalSupply = await cometContract.totalSupply(); const totalSupply = ethers.utils.parseUnits("1000000", 18); // Example: 1 Million units // Get the price of the asset const price = await priceOracleContract.getPrice(marketAddress); // Get asset decimals (needed for accurate formatting) // This requires an ERC20 ABI or similar interface. // const assetContract = new ethers.Contract(marketAddress, erc20Abi, provider); // const decimals = await assetContract.decimals(); const decimals = 18; // Assuming 18 decimals for the asset // Calculate the value of the asset supplied const assetValue = totalSupply * price; // Adjust for decimals: (totalSupply * (10^decimals)) * price / (10^price_decimals) // Assuming price is scaled appropriately (e.g., 1e8 or 1e18) const scaledAssetValue = assetValue.div(ethers.BigNumber.from(10).pow(decimals)); totalValueLocked = totalValueLocked.add(scaledAssetValue); } console.log(`Total Value Locked (TVL): ${ethers.utils.formatUnits(totalValueLocked, 18)}`); // Assuming TVL is in base asset decimals } getTotalValueLocked().catch(console.error); ``` -------------------------------- ### Repay Full Borrow Precisely Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to repay the entire borrow amount precisely in Compound III. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const signer = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const cometAddress = "YOUR_COMET_ADDRESS"; // Address of the specific asset's Comet contract const baseAssetAddress = "YOUR_BASE_ASSET_ADDRESS"; // Address of the base asset (e.g., WETH) const cometAbi = [ // ... Comet ABI snippets ... "function borrowBalanceStored() external view returns (uint)", "function repay(uint amount) external returns (uint)", "function asset() external view returns (address)" ]; const assetAbi = [ // ... ERC20 ABI snippets ... "function approve(address spender, uint256 amount) external returns (bool)", "function balanceOf(address account) external view returns (uint256)" ]; async function repayFullBorrow() { const cometContract = new ethers.Contract(cometAddress, cometAbi, signer); const assetContract = new ethers.Contract(baseAssetAddress, assetAbi, signer); // Get the current borrow balance const currentBorrowBalance = await cometContract.borrowBalanceStored(); if (currentBorrowBalance === 0) { console.log("No outstanding borrow to repay."); return; } // Approve the Comet contract to spend the base asset from your wallet await assetContract.approve(cometAddress, currentBorrowBalance); // Repay the exact borrow amount await cometContract.repay(currentBorrowBalance); console.log(`Successfully repaid ${ethers.utils.formatUnits(currentBorrowBalance, 18)} of the base asset.`); const newBorrowBalance = await cometContract.borrowBalanceStored(); console.log(`New borrow balance: ${ethers.utils.formatUnits(newBorrowBalance, 18)}`); } repayFullBorrow().catch(console.error); ``` -------------------------------- ### Claim COMP Rewards Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to claim accrued COMP rewards for an account. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const signer = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); // Assuming there's a specific contract or method to claim COMP rewards. // This might involve a RewardsController or similar contract in Compound III. // The exact ABI and method names will depend on the specific deployment. const rewardsControllerAbi = [ // Example ABI for a hypothetical RewardsController contract "function claimComp(address user) external returns (uint)", "function getCompAccrued(address user) external view returns (uint)" ]; // Placeholder for the actual Rewards Controller contract address const rewardsControllerAddress = "YOUR_REWARDS_CONTROLLER_ADDRESS"; async function claimCompRewards() { const rewardsControllerContract = new ethers.Contract(rewardsControllerAddress, rewardsControllerAbi, signer); const accountAddress = await signer.getAddress(); // Check accrued rewards before claiming (optional) const accruedRewards = await rewardsControllerContract.getCompAccrued(accountAddress); console.log(`Accrued COMP rewards: ${ethers.utils.formatUnits(accruedRewards, 18)}`); if (accruedRewards > 0) { // Claim the COMP rewards const claimedAmount = await rewardsControllerContract.claimComp(accountAddress); console.log(`Successfully claimed ${ethers.utils.formatUnits(claimedAmount, 18)} COMP rewards.`); } else { console.log("No COMP rewards to claim."); } } claimCompRewards().catch(console.error); ``` -------------------------------- ### Calculate APR of COMP Rewards Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to calculate the Annual Percentage Rate (APR) of COMP rewards. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; // Assuming there's a specific contract or method to get COMP reward rates. // This might involve a RewardsController or similar contract in Compound III. // The exact ABI and method names will depend on the specific deployment. const rewardsControllerAbi = [ // Example ABI for a hypothetical RewardsController contract "function getCompRewardInfo(address user) external view returns (uint rewardPerSecond, uint borrowIndex)", "function getCompAccrued(address user) external view returns (uint)" ]; // Placeholder for the actual Rewards Controller contract address const rewardsControllerAddress = "YOUR_REWARDS_CONTROLLER_ADDRESS"; async function calculateCompRewardAPR() { const rewardsControllerContract = new ethers.Contract(rewardsControllerAddress, rewardsControllerAbi, provider); const accountAddress = "YOUR_ACCOUNT_ADDRESS"; // Get reward information for the user const [rewardPerSecond, borrowIndex] = await rewardsControllerContract.getCompRewardInfo(accountAddress); // To calculate APR, you need: // 1. The total value supplied/borrowed by the user (in USD or base asset equivalent). // 2. The current COMP price. // 3. The reward rate (e.g., COMP per second). // Placeholder for getting total supplied/borrowed value (requires querying asset prices and balances) // const totalSuppliedValue = await getTotalSuppliedValue(accountAddress, provider, comptrollerAddress); // const totalBorrowedValue = await getTotalBorrowedValue(accountAddress, provider, comptrollerAddress); // const accountValue = totalSuppliedValue - totalBorrowedValue; // Simplified net value // Placeholder for getting COMP price // const compPrice = await getCompPrice(provider); // Placeholder values for demonstration: const accountValue = ethers.utils.parseUnits("10000", 18); // Example: $10,000 const compPrice = ethers.utils.parseUnits("5", 18); // Example: $5 per COMP // Calculate COMP earned per year const secondsInYear = 365 * 24 * 60 * 60; const compEarnedPerYear = rewardPerSecond * secondsInYear; // Calculate the value of COMP earned per year const compValueEarnedPerYear = compEarnedPerYear * compPrice; // Calculate APR // APR = (Value Earned Per Year / Total Account Value) * 100 const compRewardAPR = (compValueEarnedPerYear / accountValue) * 100; console.log(`COMP Reward APR for ${accountAddress}: ${compRewardAPR.toFixed(4)}%`); console.log("(Note: This calculation requires accurate COMP price and account value data, which are placeholders here.)"); } // Helper functions (placeholders) - you would need to implement these // async function getTotalSuppliedValue(account, provider, comptroller) { ... } // async function getTotalBorrowedValue(account, provider, comptroller) { ... } // async function getCompPrice(provider) { ... } calculateCompRewardAPR().catch(console.error); ``` -------------------------------- ### Calculate Interest Earned Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Example of how to calculate the interest earned by a Compound III account. Refer to the JavaScript file for implementation details. ```JavaScript const { ethers } = require("ethers"); const provider = new ethers.providers.JsonRpcProvider("YOUR_RPC_URL"); const comptrollerAddress = "YOUR_COMPTROLLER_ADDRESS"; const cometAddress = "YOUR_COMET_ADDRESS"; // Comet contract for the asset const comptrollerAbi = [ // ... Comptroller ABI snippets ... "function getSupplyRate(address market) external view returns (uint)" ]; const cometAbi = [ // ... Comet ABI snippets ... "function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint)" ]; async function calculateInterestEarned() { const comptrollerContract = new ethers.Contract(comptrollerAddress, comptrollerAbi, provider); const cometContract = new ethers.Contract(cometAddress, cometAbi, provider); const accountAddress = "YOUR_ACCOUNT_ADDRESS"; // The account to check // Get the current supply rate const supplyRate = await comptrollerContract.getSupplyRate(cometAddress); // Get the account snapshot (block number, supply balance, borrow balance, yield start timestamp) const [blockNumber, supplyBalance, borrowBalance, yieldStartTimestamp] = await cometContract.getAccountSnapshot(accountAddress); // Calculate interest earned since the last snapshot // This requires knowing the current block timestamp and the yieldStartTimestamp from the snapshot. // The exact calculation depends on how the protocol accrues interest (e.g., per second, per block). // Simplified example assuming interest accrues per second and we have the current time: const currentTimestamp = Math.floor(Date.now() / 1000); const timeElapsed = currentTimestamp - yieldStartTimestamp; // Assuming supplyRate is scaled (e.g., by 1e18) and represents rate per second. // Interest = Principal * (Rate per second * Time elapsed) const interestEarned = supplyBalance * (supplyRate / 1e18) * timeElapsed; // You need to know the decimals of the asset to format correctly. const assetDecimals = 18; // Assuming asset has 18 decimals console.log(`Interest earned for account ${accountAddress} in ${cometAddress}: ${ethers.utils.formatUnits(interestEarned, assetDecimals)}`); console.log(`(Note: This is a simplified calculation. Actual interest accrual may vary.)`); } calculateInterestEarned().catch(console.error); ``` -------------------------------- ### Get Latest Contract Addresses Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Clone the Compound III repository and use the hardhat spider command to fetch the latest contract addresses for a specified network. ```bash git clone https://github.com/compound-finance/comet.git cd comet/ yarn npx hardhat spider --deployment mainnet ``` -------------------------------- ### Configure JSON RPC Provider and Comet Instance Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Set your JSON RPC provider URL and select the Comet instance for local testing in `hardhat.config.js`. ```javascript const providerUrl = 'https://eth-mainnet.alchemyapi.io/v2/__YOUR_API_KEY_HERE__'; const cometInstance = 'usdc-mainnet'; ``` -------------------------------- ### Clone Compound III Repository and Build Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Clone the Compound III repository and run the build command to obtain contract artifacts. ```bash ## First, run the build command in the Compound III project repository git clone https://github.com/compound-finance/comet.git cd comet/ yarn run build ``` -------------------------------- ### Reference Comet ABI in Hardhat Artifacts Source: https://github.com/compound-developers/compound-3-developer-faq/blob/master/README.md Reference the Hardhat artifact for Comet's ABI to interact with the contract. ```javascript // Reference the Hardhat artifact in the Compound III project build files const abi = require('./artifacts/contracts/CometInterface.sol/CometInterface.json').abi; const comet = new ethers.Contract(cometAddress, abi, provider); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.