function keepTrackOfGas(string memory message, uint256 number) public {
...
uint gasUsed = msg.gasLimit - gasleft();
}
这是一个非常常见的用例,并且多个实现都受到未考虑不可访问费用的影响。 gasUsed 问题的最先进解决方案是在您的智能合约的第一行访问 ‘gasleft()’。
请注意,可变交易输入大小意味着交易使用的 gas 取决于输入的零和非零字节数,以及 GTXDATANONZERO。另一个问题是 Solidity 通过将整个输入从 calldata 加载到 memory 来处理 public 方法,从而花费不可预测数量的 gas。
另一个应用是让一个方法对给定的 gas 限制有要求。这种情况在元交易的上下文中非常常见,其中 msg.sender 的帐户持有人可能对内部交易的成功不太感兴趣。夸张的伪代码:
function verifyGasLimit(uint256 desiredGasLimit, bytes memory signature, address signer, bytes memory someOtherData) public {
require(ecrecover(abi.encodePacked(desiredGasLimit, someOtherData), signature) == signer, "Signature does not match");
require(tx.gasLimit == desiredGasLimit, "Transaction limit does not match the signed value. The signer did not authorize that.");
...
}