I'm optimizing the gasLimit
for transactions to ensure the maximum possible gas refund without leaving any unused gas. Given most web3 network's have a maximum gas refund policy where a portion of the unused gas is refundable(on Ethereum this is currently set to a maximum refund of 50% of the gasLimit IIRC), and considering a known gas estimate for a transaction, denoted as Goriginal
, and a desired maximum refund rate P
, how can the exact gas limit be calculated?
1 Answer
To find the optimal gasLimit
ensuring maximum refund without surplus, we can derive a formula reflecting these refund mechanics.
Given:
Goriginal
represents the original gas estimate for the transaction.P
denotes the desired refund rate (e.g., 0.25 for a 25% refund rate).
The key insight here is understanding the relationship between the refundable and non-refundable portions of gas. The fraction ( P / (1 - P) ) intuitively represents the ratio of the refundable amount to the non-refundable amount. By directly multiplying this ratio with Goriginal
, we can determine the additional gas, X
, required to achieve a full refund.
Consequently, the total over-estimated gasLimit
becomes the summation of Goriginal
and X
.
Below is a JavaScript function that computes the necessary gas limit:
function calculateGasLimit(Goriginal, P) {
const X = Goriginal * (P / (1 - P));
return Goriginal + X;
}
For instance, given a gas estimate of 100,000 and a desired refund rate of 0.25:
calculateGasLimit(100_000, 0.25)
This outputs a gas limit of roughly 133,333. By setting this gas limit, if your transaction precisely utilizes 100,000 gas, the net expenditure post-refund will resonate with the 25% maximum refundable policy, thereby optimizing the gas refund without leaving any residue. Your transaction now has leeway to use an additional 33,333 gas(if for example transactions occurred after the gas estimation and before the execution of your transaction affecting the actual gas required). However, if your transaction actually used less than the original estimate of 100,000 gas say 90,000 then since the max refund is 33,333 gas you won't be refunded for 10,000 gas.