Skip to content

Instantly share code, notes, and snippets.

@alephao
Last active April 28, 2022 12:59
Show Gist options
  • Save alephao/1a713154c7a4879ff0b8875a215bb3fd to your computer and use it in GitHub Desktop.
Save alephao/1a713154c7a4879ff0b8875a215bb3fd to your computer and use it in GitHub Desktop.
Deploy with low gas cost
WS_URL=wss://eth-mainnet.alchemyapi.io/v2/<key>
import { execSync } from "child_process";
import { BigNumber, ethers } from "ethers";
import { formatUnits } from "ethers/lib/utils";
import { exit } from "process";
require("dotenv").config();
// eth rpc web socket url
const WS_URL = process.env.WS_URL!;
const gwei = (val: string | number) => {
return ethers.utils.parseUnits(`${val}`, "gwei");
};
const deploy = () => {
// ... deployment code
exit(0);
}
const main = async () => {
execSync("forge build --force --optimize");
const wsProvider = new ethers.providers.WebSocketProvider(WS_URL);
const target = gwei("28");
let done = false;
// subscribe to every new head and check the baseFeePerGas
wsProvider._subscribe("block", ["newHeads"], (result: any) => {
if (done) {
return;
}
const baseFeePerGas = BigNumber.from(result.baseFeePerGas);
const humanReadableBaseFeePerGas = formatUnits(
baseFeePerGas.toString(),
"gwei"
);
if (baseFeePerGas.lte(target)) {
console.log(humanReadableBaseFeePerGas, "✅");
done = true;
deploy();
} else {
console.log(humanReadableBaseFeePerGas, "❌");
}
});
};
main();
{
"scripts": {
"deploy": "ts-node scripts/deploy.ts"
},
"devDependencies": {
"@types/node": "^17.0.24",
"ts-node": "^10.7.0",
"typescript": "^4.6.3"
},
"dependencies": {
"dotenv": "^16.0.0",
"ethers": "^5.6.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment