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

Jam*_*mes 3 python cryptocurrency binance web3py binance-smart-chain

我正在使用 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)

Run Code Online (Sandbox Code Playgroud)

有人能帮忙吗?谢谢。

小智 5

所以你所做的就是试图获得错误的值。

getamountsout 不会给你价格。您需要使用两个代币作为参数从 pancakeswap 工厂地址调用 getpair。( 0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73 ) getpair 函数的文档

然后你会得到一个合约地址,你可以从中调用 getreserves 函数(此合约的文档),从中你可以得到 3 个值(_reserve0、_reserve1、_blockTimestampLast),你可以将第一个值除以第二个值,或者将第二个值除以第一个值,具体取决于您想要哪个价格