Skip to content

Instantly share code, notes, and snippets.

@gregorynicholas
Created November 8, 2020 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gregorynicholas/e1afa094c8013b57e61f92d261c99bb0 to your computer and use it in GitHub Desktop.
Save gregorynicholas/e1afa094c8013b57e61f92d261c99bb0 to your computer and use it in GitHub Desktop.
Get COMP APY for USDT. Uses Node.js with Compound.js. Be sure to fill in your Infura project ID at the top. See comments for run instructions.
const Compound = require('@compound-finance/compound-js');
const provider = 'https://mainnet.infura.io/v3/<YOUR INFURA API KEY HERE>';
const cTokenToGetCompApy = Compound.cUSDT;
const underlying = cTokenToGetCompApy.slice(1, 10);
const underlyingDecimals = Compound.decimals[underlying];
const cTokenDecimals = 8; // always 8
const comptroller = Compound.util.getAddress(Compound.Comptroller);
const opf = Compound.util.getAddress(Compound.PriceFeed);
const cTokenAddr = Compound.util.getAddress(cTokenToGetCompApy);
const apxBlockSpeedInSeconds = 13.15;
const compound = new Compound(provider);
(async function() {
let compSpeed = await Compound.eth.read(
comptroller,
'function compSpeeds(address cToken) public returns (uint)',
[ cTokenAddr ],
{ provider }
);
let compPrice = await compound.getPrice(Compound.COMP, underlying);
let totalBorrows = await Compound.eth.read(
cTokenAddr,
'function totalBorrowsCurrent() returns (uint)',
[],
{ provider }
);
let totalSupply = await Compound.eth.read(
cTokenAddr,
'function totalSupply() returns (uint)',
[],
{ provider }
);
let exchangeRate = await Compound.eth.read(
cTokenAddr,
'function exchangeRateCurrent() returns (uint)',
[],
{ provider }
);
// Total supply needs to be converted from cTokens
exchangeRate = +exchangeRate.toString() / Math.pow(10, 18);
compSpeed = compSpeed / 1e18; // COMP has 18 decimal places
compPrice = compPrice; // price feed is USD price with 6 decimal places
totalBorrows = +totalBorrows.toString() / (Math.pow(10, underlyingDecimals));
totalSupply = (+totalSupply.toString() * exchangeRate) / (Math.pow(10, underlyingDecimals));
console.log('compSpeed:', compSpeed);
console.log('compPrice:', compPrice);
console.log('totalBorrows:', totalBorrows);
console.log('totalSupply:', totalSupply);
console.log('exchangeRate:', exchangeRate);
const compPerDay = compSpeed * parseInt((60 * 60 * 24) / apxBlockSpeedInSeconds);
const compBorrowApy = +(100 * (Math.pow((1 + (compPrice * compPerDay / totalBorrows)), 365) - 1)).toFixed(2);
const compSupplyApy = +(100 * (Math.pow((1 + (compPrice * compPerDay / totalSupply)), 365) - 1)).toFixed(2);
console.log('compBorrowApy', compBorrowApy, '%');
console.log('compSupplyApy:', compSupplyApy, '%');
})().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment