DEV Community

rahuldev-17
rahuldev-17

Posted on

3 1

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 https://getblock.io/docs/get-started/auth-with-api-key/). 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://bsc.getblock.io/testnet/?api_key=<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();

console.log(contract.address);
console.log(contract.deployTransaction);
}

main();
Enter fullscreen mode Exit fullscreen mode

In the above code, 'account' is the 'signer' of the ethers docs
https://docs.ethers.io/v5/api/contract/contract-factory/#ContractFactory--creating

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more