我注意到所使用的气体量之间存在差异
通过交易几乎是相同的:
我正在调用智能合约,
连续两次使用相同的参数,
两者之间的唯一区别
是我正在设置gasLimit
到精确值
由返回eth_estimateGas
在第一个中,
我正在设置gasLimit
to eth_estimateGas * 1.1
在第二个中。
// with exact estimated amount of gas
const estimatedGas2 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();
console.log('estimatedGas2', estimatedGas2);
const gasLimit2 = estimatedGas2 * 1n;
console.log('gasLimit2', gasLimit2);
const txResponse2 = await (await expendGasSc
.updateState(
1_000_000_123n,
{ gasLimit: gasLimit2 },
))
.wait();
const gasUsed2 = txResponse2.gasUsed.toBigInt();
console.log('gasUsed2', gasUsed2);
// with 110% of estimated amount of gas
const estimatedGas3 = (await expendGasSc.estimateGas.updateState(1_000_000_123n)).toBigInt();
console.log('estimatedGas3', estimatedGas3);
const gasLimit3 = estimatedGas3 * 11n / 10n;
console.log('gasLimit3', gasLimit3);
const txResponse3 = await (await expendGasSc
.updateState(
1_000_000_123n,
{ gasLimit: gasLimit3 },
))
.wait();
const gasUsed3 = txResponse3.gasUsed.toBigInt();
console.log('gasUsed3', gasUsed3);
这是输出,显示:
- when
gasLimit
设置为 400,000,gasUsed
是 320,000
- when
gasLimit
设置为 440,000,gasUsed
是 352,000
estimatedGas2 400000n
gasLimit2 400000n
gasUsed2 320000n
estimatedGas3 400000n
gasLimit3 440000n
gasUsed3 352000n
为什么第二次调用会额外消耗 32,000 的 Gas?
(我预计gasUsed
两种情况下的值相同。)
这是智能合约:
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.18;
contract ExpendSomeGasDemo {
uint256 public state;
function updateState(
uint256 newState
)
public
returns (uint256 updatedState)
{
state = newState;
updatedState = newState;
}
}
请注意,该合约部署在 Hedera 测试网上:0x9C58D0159495F7a8853A24574f2B8F348a72424c https://hashscan.io/testnet/contract/0.0.4616849
请注意,上面的 Javascript 示例使用 ethers.js。