我可以获取 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)
我可以给它一些任意的数字,但这不是真正的解决方案。在我在网上看到的每个示例中,都添加了一些任意的 Gas 量,但没有解释他们如何获得它。
您可以在未签名的交易上使用
web3.eth.estimate_gas
,然后使用适当的 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(tx) tx.update({'gas': gas})
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})
来自 web3py 文档:
Gas 价格策略仅支持旧交易。伦敦分叉引入了
和maxFeePerGas
交易参数,应尽可能在 GasPrice 上使用。maxPriorityFeePerGas
尝试像这样构建您的交易,仅设置这些字段。 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
})