Last active
February 26, 2024 17:35
-
-
Save SpiralOutDotEu/68e19cb0e339133302233bb84cf68fc8 to your computer and use it in GitHub Desktop.
Ethers calculate transaction fee
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ethers } from "ethers"; | |
// Using this if cannot serialize bigint | |
BigInt.prototype.toJSON = function () { | |
const int = Number.parseInt(this.toString()); | |
return int ?? this.toString(); | |
}; | |
// Define provider | |
const provider = new ethers.JsonRpcProvider(RPC_URL) | |
// Define signer | |
const signer = new ethers.Wallet( | |
private_key, | |
provider | |
); | |
// Define Contract | |
const myContract = new ethers.Contract( | |
address, | |
contractAbi, | |
signer | |
); | |
// *Optional: Test tx if can pass. It returns true or error | |
const testTx = | |
await myContract.oneMethod.staticCall( | |
oneParameter, | |
anotherParameter | |
); | |
// Estimate Gas | |
const gasAmount = | |
await myContract.oneMethod.estimateGas( | |
oneParameter, | |
anotherParameter | |
); | |
// Get the current gas price | |
const gasPrice = (await provider.getFeeData()).gasPrice; | |
// Calculate the gas fee | |
const gasFeeInWei = (gasPrice as bigint) * gasAmount; | |
const gasFeeInETH = ethers.formatEther(gasFeeInWei); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment