我有一个从Uniswap V2获取价格的简单代码
const getTokenExchangeRate = async (tokenA, tokenB) => {
return (
await dexRouter.methods.getAmountsOut(toWei("1"), [tokenA, tokenB]).call()
)[1];
};
// usage
const price = await getTokenExchangeRate(LINK, DAI)
priceNormal = web3.utils.fromWei(price)
console.log(priceNormal)如果这两种硬币的小数相等,正常工作,但如果小数有差异,我得到一个巨大的数字。例如
const price = await getTokenExchangeRate(LINK, USDC)
priceNormal = web3.utils.fromWei(price)
console.log(priceNormal)
PS C:\Users\Viktor\Desktop\Uniswap3JS> node test.js
0.000000000009015961我应该添加什么来获得所有可能的对的人类可读的数字?谢谢。
发布于 2022-08-14 17:06:23
decimals()。if(tokenDecimals < 18){
const amountOut = await pair.methods.getReserves().call()
const parsedAmount = Number(amountOut.tokenB._hex).toFixed(18)
await dexRouter.methods.getAmountsOut(parsedAmount, [tokenA,tokenB]).call()
}无法测试这段代码是否会编译,但下面是北部代码。
发布于 2022-08-14 17:53:38
嗯,我找到了答案,尽管我不喜欢。现在我不明白为什么getAmountsOut (WETH,USDC)给出了一个真实的价格,而getAmountsOut (USDC,WETH)给出了一些奇怪的数字。但那是另一个故事。
const getTokenExchangeRate = async (tokenA, tokenB) => {
return (
await dexRouter.methods.getAmountsOut(toWei("1"), [tokenA, tokenB]).call()
)[1];
};
const price = await getTokenExchangeRate(USDC, WETH9)
// DECIMALS
const abi2 = [
{
"constant": true,
"inputs": [],
"name": "decimals",
"outputs": [
{
"name": "",
"type": "uint8"
}
],
"payable": false,
"type": "function"
},
];
const check = new web3.eth.Contract(
abi2,
WETH9 //TokenB
);
const result = await check.methods.decimals().call()
let humanPrice = price/(10**result)发布于 2022-08-14 16:58:28
我建议将所有数字转换为公分母(即小数点18位精度),并对这些小数位进行分析。
Aave V2回购有一些不错的效用函数为此目的。
https://ethereum.stackexchange.com/questions/133589
复制相似问题