Created
October 28, 2024 19:08
-
-
Save claytantor/578788fa560c3401fcac2b07fbeaab90 to your computer and use it in GitHub Desktop.
Estimate gas on a swap
This file contains hidden or 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
| async function estimateTransactionCost(provider, contract) { | |
| // Set up provider and contract | |
| // const provider = new ethers.providers.InfuraProvider("sepolia", "YOUR_INFURA_PROJECT_ID"); | |
| // const wallet = new ethers.Wallet("YOUR_PRIVATE_KEY", provider); | |
| // const contract = new ethers.Contract("CONTRACT_ADDRESS", contractAbi, wallet); | |
| try { | |
| // Estimate gas for the function | |
| //const gasLimitMax = ethers.utils.parseUnits("10", "gwei"); | |
| const gasLimitMax = 500000; | |
| const estimatedGas = await contract.estimateGas.swapExactInputSingle(ethers.utils.parseUnits("3.0", 6), { | |
| gasLimit: gasLimitMax // Adjust the value as needed | |
| }); | |
| console.log("Estimated Gas:", estimatedGas.toString()); | |
| // Get the current gas price | |
| const gasPrice = await provider.getGasPrice(); | |
| console.log("Current Gas Price:", ethers.utils.formatUnits(gasPrice, "gwei"), "Gwei"); | |
| // Calculate the total cost in wei | |
| const transactionCost = estimatedGas.mul(gasPrice); | |
| console.log("Transaction Cost in Wei:", transactionCost.toString()); | |
| // Convert to ETH for readability | |
| const transactionCostInEth = ethers.utils.formatEther(transactionCost); | |
| console.log("Transaction Cost in ETH:", transactionCostInEth); | |
| return transactionCostInEth; | |
| } catch (error) { | |
| console.error("Error estimating transaction cost:", error); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment