15

I am trying to figure out the best way to deploy a contract using ethers.js

with web3 I can just do:

     const contractInstance = new this.web3.eth.Contract(contractObject.abi)
        var deployTx
        debug(contractInstance)
        if (params === undefined || params.length === 0) {
          deployTx = contractInstance.deploy({
            data: contractObject.bytecode
          })
        } else {
          deployTx = contractInstance.deploy({
            data: contractObject.bytecode,
            arguments: params
          })
        }
        const data = await deployTx.encodeABI()

However with Web 3 I also seem to need an address? and to get that address I have to first manually deploy it. Some clarity around the topic would really help.

I've tried to find resources specifying this but they are not what what im looking for I think?

Thanks in advance

1
  • could you please elaborate or point me in the right direction? What I have gathered is this: The documentation doesnt seem to go in too deep into the deployment itself? Jun 29, 2020 at 19:47

2 Answers 2

14

You can deploy a contract using Ethers.js' ContractFactory.

import { ContractFactory } from 'ethers';

const factory = new ContractFactory(contractAbi, contractByteCode);

// If your contract requires constructor args, you can specify them here
const contract = await factory.deploy(deployArgs);

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

More information can be found in the documentation, found here: https://docs.ethers.io/v5/api/contract/contract-factory/

3
  • 5
    this returns an error Cannot read property 'sendTransaction' of null Jun 30, 2020 at 3:23
  • @LucasRodriguezBenitez Make sure that you have provided your mnemonic or array of private key to the Ethereum development framework you're using. For example, these are the docs for Hardhat. Jan 11, 2021 at 9:31
  • Would like to know how to set the provider as well; i came here with no prior usage of ethers.
    – Stevers
    Dec 1, 2021 at 3:54
6

To further elaborate Marten's answer, I will try to give a complete script. 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

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'.

nodejs script for contract deployment goes here:

//load 'ethers' and 'fs'
const ethers = require('ethers');
const 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);
  
//Ussing async-await for deploy method
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();

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

ethers.ContractFactory( interface , bytecode [ , signer ] )

Please ask if still having problem.

4
  • Is there a method without the seed phrase because i want to launch contracts for people using their wallet without touching their seed or private keys.
    – CodeGuru
    Sep 1, 2022 at 6:51
  • No. The seed created by Metamask is just a proxy for the private keys. Consider it as a mapping. Essentially, all interactions with blockchain is an RPC call, but gas consuming interactions, such as contract deployment, require private key of the user address.
    – Rahuldev
    Sep 2, 2022 at 7:41
  • 1
    Yes, of course there is. Just use a MetaMask signer. You can initialize the provider with const provider = new ethers.providers.Web3Provider(window.ethereum), and then you can pass the provider.getSigner() into the contract factory. But this needs to happen on the client side of course.
    – CherryDT
    Oct 31, 2022 at 20:49
  • the problem is that we cant use fs (to ready the contract) in client side
    – Adri HM
    Apr 12, 2023 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.