[英]How to get gas amount web3py?
我可以得到 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)
我可以給它一些任意數字,但這不是一個真正的解決方案。 在我在網上看到的每個示例中,都輸入了一些任意的氣體量,但沒有解釋他們是如何得到它的。
您可以在未簽名的交易上使用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})
你可以省略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
和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
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.