DEV Community

yosi
yosi

Posted on β€’ Edited on

Deploy a Smart Contract with Ethers.js

In order to create a new contract we need to send a transaction to the Ethereum blockchain with a payload that contains the compiled contract code. The transaction recipient must be set to null.

The following JS code implements such a transaction using Ethers.js

const ethers = require('ethers');
const fs = require('fs');
(async () => {
  // Deploy the contract to Ethereum test network - Ropsten
  const provider = ethers.providers.getDefaultProvider('ropsten')

  // Use your wallet's private key to deploy the contract
  const privateKey = 'YOUT_PRIVATE_KEY'
  const wallet = new ethers.Wallet(privateKey, provider)

  // Read the contract artifact, which was generated by Remix
  const metadata = JSON.parse(fs.readFileSync('contract.json').toString())

  // Set gas limit and gas price, using the default Ropsten provider
  const price = ethers.utils.formatUnits(await provider.getGasPrice(), 'gwei')
  const options = {gasLimit: 100000, gasPrice: ethers.utils.parseUnits(price, 'gwei')}

  // Deploy the contract
  const factory = new ethers.ContractFactory(metadata.abi, metadata.data.bytecode.object, wallet)
  const contract = await factory.deploy(options)
  await contract.deployed()
  console.log(`Deployment successful! Contract Address: ${contract.address}`)
})()
Enter fullscreen mode Exit fullscreen mode

If the transaction is successful, you’ll get the following message –

Deployment successful! Contract Address: YOUR_CONTRACT_ADDRESS
Enter fullscreen mode Exit fullscreen mode

Congrats for deploying your first contract! πŸš€πŸš€πŸš€

Top comments (1)

Collapse
Β 
emasacco profile image
Emanuele Sacco β€’

Hi yosi, thanks for your tutorial, may you clarify to me how to add custom constructor parameters for the smart contract in the deploy function.
thanks in advance :)