DEV Community


Posted on

How to deploy a solidity contract with etherjs

Assuming you have installed metamask, and know the seed phrase, here are steps to deploy contract using 'ethers' and 'fs':

  1. compile the contract to .bin and .abi files
  2. load 'ethers' and 'fs'
  3. create a 'signer' object using 'provider', 'Wallet', and 'connect' methods from 'ethers'
  4. create a contract instance from 'ContractFactory' method
  5. use deploy method as promise
  6. Here I have used 'getblock' as web3 provider for example (see Other alternatives are 'quicknode', 'alchemy' and 'infura'.

We will deploy the code to the BSC testnet, but same procedure will apply for other Ethereum Virtual Machine(EVM) compatible chains, such as : Avalanche Contract Chain (C-Chain), Binance Smart Chain (BSC) mainnet, Fantom Opera and Polygon etc.

nodejs script for contract deployment goes here:

//load 'ethers' and 'fs'

ethers = require('ethers');
fs = require('fs');

//Read bin and abi file to object; names of the solcjs-generated files renamed
bytecode = fs.readFileSync('storage.bin').toString();
abi = JSON.parse(fs.readFileSync('storage.abi').toString());

//to create 'signer' object;here 'account'
const mnemonic = "<see-phrase>" // seed phrase for your Metamask account
const provider = new ethers.providers.WebSocketProvider("wss://<your-api-key>");
const wallet = ethers.Wallet.fromMnemonic(mnemonic);
const account = wallet.connect(provider);

const myContract = new ethers.ContractFactory(abi, bytecode, account);

//Using 'deploy method 'in 'async-await' 
async function main() {
// If your contract requires constructor args, you can specify them here
const contract = await myContract.deploy();


Enter fullscreen mode Exit fullscreen mode

In the above code, 'account' is the 'signer' of the ethers docs

ethers.ContractFactory( interface , bytecode [ , signer ] )
Enter fullscreen mode Exit fullscreen mode

Do not hesitate to ask in discussion if you face any problem in deploying your contract.

Top comments (0)