gpt4 book ai didi

python - 使用 Web3 和 Python 计算 BSC 代币的价格

转载 作者:行者123 更新时间:2023-12-05 01:57:31 27 4
gpt4 key购买 nike

我正在使用 web3 和 python 构建一个工具,需要通过 PancakeSwap 快速准确地获取币安智能链上的代币价格。

该工具收集有关 BSC 代币、价格、流动性等的信息,以便我可以进一步分析 rugpulls。

在下面的代码中,它提供了一个合约地址,它需要提供 BNB 中每个代币的当前价格。然而,它出现了很多故障并且没有给我正确的价格,我无法弄清楚出了什么问题。代码如下。

from web3 import Web3

web3 = Web3(Web3.WebsocketProvider('wss://speedy-nodes-nyc.moralis.io/b51e035eb24e1e81cc144788/bsc/mainnet/ws'))

tokenPriceABI = 'Token Price ABI'

def getTokenPrice(tokenAddress):
BNBTokenAddress = Web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c") # BNB
amountOut = None#
#tokenAddress = Web3.toChecksumAddress(tokenAddress)

tokenRouter = web3_sell.eth.contract(address=tokenAddress, abi=tokenPriceABI)

router = web3_sell.eth.contract(address=Web3.toChecksumAddress("0x10ed43c718714eb63d5aa57b78b54704e256024e"), abi=pancakeABI)
amountIn = web3_sell.toWei(1, 'ether')
amountOut = router.functions.getAmountsOut(amountIn, [tokenAddress, BNBTokenAddress]).call()
amountOut = web3_sell.fromWei(amountOut[1], 'ether')

return amountOut


tokenAddress = input("Enter token address: ")
tokenAddress = Web3.toChecksumAddress(tokenAddress)

priceInBnb = getTokenPrice(tokenAddress)

print(priceInBnb)

有人能帮忙吗?谢谢。

最佳答案

所以你正在做的是你试图获得错误的值(value)。

getamountsout 不会给你价格。您需要使用您的两个 token 作为参数从 pancakeswap 工厂地址调用 getpair。( 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73 ) docs for the getpair function

然后你会得到一个合约地址,你可以从中调用 getreserves 函数(docs for this contract),你可以从中得到 3 个值(_reserve0、_reserve1、_blockTimestampLast),你可以将第一个除以第二个或将第二个除以第一个取决于你想要哪种方式的价格

关于python - 使用 Web3 和 Python 计算 BSC 代币的价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69238258/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com