Deploy a Smart Contract with Ethers.js
yosi
Posted on November 3, 2021
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}`)
})()
If the transaction is successful, you’ll get the following message –
Deployment successful! Contract Address: YOUR_CONTRACT_ADDRESS
Congrats for deploying your first contract! 🚀🚀🚀
💖 💪 🙅 🚩
yosi
Posted on November 3, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.