[英]How to get gas amount web3py?
I can get the gas price, but how do I even get the gas amount?我可以得到 gas 价格,但我怎么才能得到 gas 数量呢? I feel like this is something that is not covered properly in the docs.
我觉得这是文档中没有正确涵盖的内容。 In order for me to send a transaction(contract call), I need to build it but when I build it I need to give it the gas price and the amount of gas.
为了让我发送交易(合约调用),我需要构建它,但是当我构建它时,我需要给它 gas 价格和 gas 数量。 How can I give it the amount of gas if I have no idea how to estimate the amount of gas?
如果我不知道如何估算气体量,我该如何给它提供气体量?
For example this is my code of an approve contract call.例如,这是我批准合同调用的代码。
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)
I can give it some arbitrary number, but this is not a real solution.我可以给它一些任意数字,但这不是一个真正的解决方案。 In every example I see online, some arbitrary gas amount is thrown in, with no explanation of how they got it.
在我在网上看到的每个示例中,都输入了一些任意的气体量,但没有解释他们是如何得到它的。
You can use web3.eth.estimate_gas
on the unsigned transaction and then update the transaction with appropriate gas amount and sign您可以在未签名的交易上使用
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})
You can omit the gas and just set the gas price.你可以省略gas,只设置gas价格。
w3.eth.gas_price
w3.eth.gas_price
transaction = SimpleStorage.constructor().buildTransaction(
{
"chainId": chain_id,
"gasPrice": w3.eth.gas_price,
"from": my_address,
"nonce": nonce,
}
)
get the estimate gas获得估计气体
estimate = web3.eth.estimateGas({ 'to': 'to_ddress_here', 'from': 'from_address_here', 'value': 145})
From the web3py docs :来自web3py 文档:
Gas price strategy is only supported for legacy transactions.
Gas 价格策略仅支持遗留交易。 The London fork introduced
maxFeePerGas
andmaxPriorityFeePerGas
transaction parameters which should be used over gasPrice whenever possible.伦敦分叉引入了
maxFeePerGas
和maxPriorityFeePerGas
交易参数,应尽可能在 gasPrice 上使用。
Try building your transaction like this, setting only those fields.尝试像这样构建您的事务,仅设置这些字段。 Web3 will calculate the best gas price using those constraints.
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
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.