Skip to content

Instantly share code, notes, and snippets.

@korrio
Created August 7, 2024 08:35
Show Gist options
  • Save korrio/73e0ae4ba1b45b863475d29ac429220b to your computer and use it in GitHub Desktop.
Save korrio/73e0ae4ba1b45b863475d29ac429220b to your computer and use it in GitHub Desktop.
fetchPrice on-chain from pair
const fetchTokenPrice = async () => {
const tokenAddress = '0xB96D0f29a0aC9AF4a32835e90EC6531389765089';
const tokenAddress2 = '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c';
const data1 = await publicClient.readContract({
address: '0x93accdaf2a9bb95d83d28cd19bc00d08be8741f9',
abi: pancakePairAbi,
functionName: 'getReserves',
});
const data2 = await publicClient.readContract({
address: '0x58f876857a02d6762e0101bb5c46a8c1ed44dc16',
abi: pancakePairAbi,
functionName: 'getReserves',
});
const data3 = await publicClient.readContract({
address: '0x93accdaf2a9bb95d83d28cd19bc00d08be8741f9',
abi: pancakePairAbi,
functionName: 'token0',
});
const data4 = await publicClient.readContract({
address: '0x58f876857a02d6762e0101bb5c46a8c1ed44dc16',
abi: pancakePairAbi,
functionName: 'token0',
});
const [reserve0, reserve1]: any = data1;
const [reserve2, reserve3]: any = data2;
const token0DataVPR: any = data3;
const token0DataBNB: any = data4;
// console.log("data1",data1)
// console.log("data2",data2)
// console.log("data3",data3)
// console.log("data4",data4)
const token0Address = token0DataVPR.toLowerCase();
const [tokenIndex, busdIndex] = token0Address === tokenAddress?.toLowerCase() ? [0, 1] : [1, 0];
const tokenAmount = tokenIndex === 0 ? (reserve0 as any) : reserve1;
const busdAmount = busdIndex === 0 ? reserve0 : reserve1;
const tokenBaseAmount = formatUnits(tokenAmount, 2);
const busdBaseAmount = formatUnits(busdAmount, 2);
const vprPriceInBnb = parseFloat(busdBaseAmount) / parseFloat(tokenBaseAmount);
// console.log('vprPriceInBnbvprPriceInBnb', vprPriceInBnb);
const token0Address2 = token0DataBNB.toLowerCase();
const [tokenIndex2, busdIndex2] = token0Address2 === tokenAddress2?.toLowerCase() ? [0, 1] : [1, 0];
const tokenAmount2 = tokenIndex2 === 0 ? (reserve2 as any) : reserve3;
const busdAmount2 = busdIndex2 === 0 ? reserve2 : reserve3;
const tokenBaseAmount2 = formatUnits(tokenAmount2, 2);
const busdBaseAmount2 = formatUnits(busdAmount2, 2);
const bnbPriceInUsd = parseFloat(busdBaseAmount2) / parseFloat(tokenBaseAmount2);
const vprPriceInUsd = vprPriceInBnb * bnbPriceInUsd;
return vprPriceInUsd;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment