DEV Community

yosi
yosi

Posted on • Edited on

6 2

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! 🚀🚀🚀

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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 :)

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay