Skip to content

Instantly share code, notes, and snippets.

@w1nt3r-eth
Created December 16, 2021 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save w1nt3r-eth/39a1d475ba962e2431c31d3c2ab98397 to your computer and use it in GitHub Desktop.
Save w1nt3r-eth/39a1d475ba962e2431c31d3c2ab98397 to your computer and use it in GitHub Desktop.
Deploy a contract when gas is cheap
// $ 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