Created
December 16, 2021 18:29
-
-
Save w1nt3r-eth/39a1d475ba962e2431c31d3c2ab98397 to your computer and use it in GitHub Desktop.
Deploy a contract when gas is cheap
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
// $ yarn hardhat run --network mainnet scripts/deploy.ts | |
import {BigNumber} from '@ethersproject/bignumber'; | |
import {formatUnits, parseUnits} from '@ethersproject/units'; | |
import {ethers} from 'hardhat'; | |
async function main() { | |
const gasPrice = await waitForGasPriceBelow(parseUnits('40', 'gwei')); | |
const Greeter = await ethers.getContractFactory('Greeter'); | |
const greeter = await Greeter.deploy({gasPrice}); | |
console.log('Greeter address:', greeter.address); | |
await greeter.deployed(); | |
console.log('Deployed!'); | |
} | |
async function waitForGasPriceBelow(max: BigNumber): Promise<BigNumber> { | |
console.log('Waiting for gas price below', formatUnits(max, 'gwei'), 'gwei'); | |
while (true) { | |
const price = await ethers.provider.getGasPrice(); | |
console.log(new Date().toLocaleString(), 'Gas Price:', formatUnits(price, 'gwei'), 'gwei'); | |
if (price.lte(max)) { | |
console.log('Good enough!'); | |
return price; | |
} | |
await new Promise((resolve) => setTimeout(resolve, 30_000)); | |
} | |
} | |
main() | |
.then(() => process.exit(0)) | |
.catch((error) => { | |
console.error(error); | |
process.exit(1); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment