微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 BSC 上使用 Web3.py 获取令牌的确切值?函数 getAmountsOut() 返回错误值

如何解决如何在 BSC 上使用 Web3.py 获取令牌的确切值?函数 getAmountsOut() 返回错误值

大家好,我会尽量说清楚。 我试图使用 web3.py 获取 s**tcoins 的价格,在解决了许多问题后,我被我问的问题困住了。

tokenAddres = '0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82' #Cake
tokenAddres = Web3.tochecksumAddress(tokenAddres)
bnbPrice = calcBNBPrice()
print(f'current BNB price: {bnbPrice}')
priceInBnb = calcSell(1,tokenAddres)
print(f'SHIT_TOKEN VALUE IN BNB : {priceInBnb} | Just convert it to USD ')
print(f'SHIT_TOKEN VALUE IN USD: {priceInBnb * bnbPrice}')

calcsell 函数应该是返回 BNB 中代币值的函数

def calcSell(tokenToSell,tokenAddress):
    BNBTokenAddress = Web3.tochecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")  # BNB
    amountOut = None

    tokenRouter = web3.eth.contract(address=Web3.tochecksumAddress(tokenAddress),abi=tokenAbi)
    tokenDecimals = tokenRouter.functions.decimals().call()
    tokenToSell = setDecimals(tokenToSell,tokenDecimals) # Set token a correct number of 0s
    
    router = web3.eth.contract(address=Web3.tochecksumAddress(pancakeSwapContract),abi=pancakeSwapAbi)
    amountIn = web3.toWei(tokenToSell,'ether')
    amountOut = router.functions.getAmountsOut(amountIn,[tokenAddress,BNBTokenAddress]).call()
    amountOut = web3.fromWei(amountOut[1],'ether')

    return amountOut

我得到的值是:
BNB 中的 SHIT_TOKEN 值:974136.205251839691973598 |只需将其转换为美元
SHIT_TOKEN 美元价值:340708627.4489159379891912819

而正确的是:
BNB 中的 SHIT_TOKEN 值:0.048846069961106416 |只需将其转换为美元
SHIT_TOKEN VALUE IN USD:16.98585439310707

有什么猜想吗?在此先感谢您,如有任何问题,请随时提问!

解决方法

我觉得这条线

tokenToSell = setDecimals(tokenToSell,tokenDecimals) # Set token a correct number of 0s

与此行完全相同

amountIn = web3.toWei(tokenToSell,'ether')

这使得 amountIn 成为 1*(10**18)*(10**18) 假设十进制是 18,去掉 amountIn = web3.toWei(tokenToSell,'ether'),因为 tokenToSell 已经是 wei 格式了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。