How to calculate maxFeePerGas/maxPriorityFeePerGas #239
-
We're working on migrating from ethers to viem (going good so far) but I can't figure this one out. With ethers we could use const get1559GasFees = async ({ provider }: { provider: Provider }) => {
try {
return await provider.getFeeData();
} catch {
return {
maxFeePerGas: null,
maxPriorityFeePerGas: null,
};
}
};
let maxFeePerGas: BigNumber = null;
let maxPriorityFeePerGas: BigNumber = null;
let gasEstimate: BigNumber = null;
try {
const fees = await get1559GasFees({
provider: contract.provider as Provider,
});
maxFeePerGas = fees.maxFeePerGas;
maxPriorityFeePerGas = fees.maxPriorityFeePerGas;
// Estimate EIP-1559 gas
gasEstimate = await contract.estimateGas[method](...args, {
maxFeePerGas,
maxPriorityFeePerGas,
});
} catch {
// EIP-1559 not supported/failed
try {
maxFeePerGas = null;
maxPriorityFeePerGas = null;
gasEstimate = await contract.estimateGas[method](...args);
} catch {
// Failed to estimate gas
}
return { gasEstimate, maxFeePerGas, maxPriorityFeePerGas }; Then we'd subsequently call the contract method with the resulting values: await contract[method](...args, {
maxFeePerGas, // may be null
maxPriorityFeePerGas, // may be null
gasLimit: bumpBy5Percent(gasEstimate), // the gas estimate for either a 1559 or a legacy txn
}); With Viem I can see that we can pass in const gasEstimate = await client.estimateContractGas({
address,
abi,
functionName,
args,
account,
maxFeePerGas, // ?
maxPriorityFeePerGas, // ?
});
return bumpBy5Percent(gas) // is this still the gasLimit arg for a 1559 txn? I'm really just hoping for some clarification on all this 😊 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Are you using a JSON-RPC Account or a Local Account (private key, mnemonic, etc)? For a JSON-RPC Account, it is recommended to defer fee calculation to the wallet (as they have better mechanisms to determine best fee data), meaning you don't need to pass through fee data at all. |
Beta Was this translation helpful? Give feedback.
Are you using a JSON-RPC Account or a Local Account (private key, mnemonic, etc)?
For a JSON-RPC Account, it is recommended to defer fee calculation to the wallet (as they have better mechanisms to determine best fee data), meaning you don't need to pass through fee data at all.
For a Local Account, we do fee calculations automatically in the internal
prepareRequest
util – however, if you want to do something more custom, we can extract this out into a utility quite easily. Would you rather do this manually and we extract it out into a util?