如何从链上获取 lending protocal 的 APY
要从链上获取借贷协议的年化收益率(APY,Annual Percentage Yield),可以按照以下步骤进行:
确定你要查询的借贷协议(如Aave、Compound等)以及它们运行的区块链(如以太坊、Polygon等)。
借贷协议的APY数据通常保存在其智能合约中。找到这些智能合约的地址,你可以在协议的官方文档或区块浏览器(如Etherscan、Polygonscan)上找到。
使用Web3库(如Web3.js或Ethers.js)连接到相应的区块链网络。这些库允许你与智能合约进行交互。
const Web3 = require('web3');
const web3 = new Web3('https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID');
ABI(Application Binary Interface)是与智能合约交互所需的接口描述。你可以在协议的GitHub仓库或区块浏览器上找到智能合约的ABI。
使用智能合约地址和ABI初始化智能合约实例。
const contractAddress = '0x...'; // 替换为协议的智能合约地址
const contractABI = [ /* ABI数组 */ ];
const contract = new web3.eth.Contract(contractABI, contractAddress);
借贷协议通常有专门的方法来获取当前的APY。你需要查找这些方法并调用它们。
例如,在Compound协议中,你可以通过以下方法获取当前利率:
async function getCompoundAPY() {
const supplyRatePerBlock = await contract.methods.supplyRatePerBlock().call();
const blocksPerDay = 4 * 60 * 24; // 以太坊每15秒一个区块
const daysPerYear = 365;
const apy = (Math.pow((supplyRatePerBlock / 1e18 * blocksPerDay) + 1, daysPerYear) - 1) * 100;
return apy;
}
调用函数并输出APY结果。
getCompoundAPY().then(apy => {
console.log('Current APY:', apy);
}).catch(err => {
console.error('Error fetching APY:', err);
});
通过这些步骤,你可以从链上获取借贷协议的APY。如果你对特定的协议有疑问,可以查阅其文档或社区资源。
使用 Ethers.js
使用Ethers.js从链上获取借贷协议的APY(Annual Percentage Yield)可以按照以下步骤进行。以下是一个简单的示例,展示如何从Compound协议中获取APY:
如果你还没有安装Ethers.js,可以通过npm或yarn进行安装:
npm install ethers
# 或者
yarn add ethers
导入Ethers.js库,并设置一个Provider来连接到区块链网络。
const { ethers } = require('ethers');
// 使用Infura提供的以太坊主网接口
const provider = new ethers.providers.InfuraProvider('homestead', 'YOUR_INFURA_PROJECT_ID');
你需要Compound协议的cToken智能合约地址和ABI。以cDAI为例,你可以在Compound的官方文档或Etherscan上找到这些信息。
const cDaiAddress = '0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643';
const cDaiABI = [
// 只包含和APY相关的方法
"function supplyRatePerBlock() external view returns (uint)",
];
使用Ethers.js的Contract类初始化智能合约实例。
const cDaiContract = new ethers.Contract(cDaiAddress, cDaiABI, provider);
使用智能合约的方法获取每个区块的供应利率,并计算年化利率。
async function getCompoundAPY() {
const supplyRatePerBlock = await cDaiContract.supplyRatePerBlock();
const blocksPerDay = 4 * 60 * 24; // 以太坊每15秒一个区块
const daysPerYear = 365;
// 计算APY
const apy = (Math.pow((supplyRatePerBlock / 1e18 * blocksPerDay) + 1, daysPerYear) - 1) * 100;
return apy;
}
getCompoundAPY().then(apy => {
console.log('Current APY:', apy);
}).catch(err => {
console.error('Error fetching APY:', err);
});
确保你在合适的JavaScript环境(如Node.js)中运行这段代码,替换YOUR_INFURA_PROJECT_ID为你的Infura项目ID。
通过这些步骤,你可以使用Ethers.js从链上获取Compound协议的APY。同样的方法可以应用于其他借贷协议,只需调整智能合约地址和ABI以及调用适当的方法。