0

我可以得到 gas 价格,但我怎么才能得到 gas 数量呢?我觉得这是文档中没有正确涵盖的内容。为了让我发送交易(合约调用),我需要构建它,但是当我构建它时,我需要给它 gas 价格和 gas 数量。如果我不知道如何估算气体量,我该如何给它提供气体量?

例如,这是我批准合同调用的代码。

    tx = contract.functions.approve(spender,max_amount).buildTransaction({
        'nonce': nonce,
        'from':self.account,
        'gasPrice': web3.toWei('20', 'gwei'),
        'gas': ?
        })
    signed_tx = web3.eth.account.signTransaction(tx, self.pkey)

我可以给它一些任意数字,但这不是一个真正的解决方案。在我在网上看到的每个示例中,都输入了一些任意的气体量,但没有解释他们是如何得到它的。

4

3 回答 3

0

您可以web3.eth.estimate_gas在未签名的交易上使用,然后用适当的气体量更新交易并签名

tx = contract.functions.approve(spender,max_amount).buildTransaction({
   'nonce': nonce,
   'from':self.account,
   'gasPrice': web3.toWei('20', 'gwei'),
   'gas': '0'
   })

gas = web3.eth.estimate_gas(temp)
tx.update({'gas': gas})
于 2021-12-12T14:48:44.350 回答
0

来自web3py 文档

Gas 价格策略仅支持遗留交易。伦敦分叉引入了maxFeePerGas交易maxPriorityFeePerGas参数,应尽可能在 gasPrice 上使用。

尝试像这样构建您的事务,仅设置这些字段。Web3 将使用这些约束计算最佳 gas 价格。

tx = contract.functions.approve(spender, max_amount).buildTransaction({
    'from': self.account,
    'maxFeePerGas': web3.toWei('2', 'gwei'),
    'maxPriorityFeePerGas': web3.toWei('1', 'gwei'),
    'nonce': nonce
})
于 2022-01-04T04:44:26.440 回答
0
  • 获取汽油价格:w3.eth.gas_price
transaction = SimpleStorage.constructor().buildTransaction(
    {
        "chainId": chain_id,
        "gasPrice": w3.eth.gas_price,
        "from": my_address,
        "nonce": nonce,
    }
)
  • 获得估计气体

    estimate = web3.eth.estimateGas({
      'to':   'to_ddress_here', 
      'from': 'from_address_here', 
      'value': 145})
    
于 2022-01-03T22:50:04.937 回答