Skip to main content

Deploying a Smart Contract with ethers.js

This guide explains how to deploy a smart contract using ethers.js. Follow these steps to set up your environment, write a smart contract, and deploy it.

Prerequisites

  • Node.js installed on your machine (Download Node.js)
  • An Ethereum wallet with test Ether (e.g., MetaMask)
  • Basic knowledge of Solidity and JavaScript

Step 1: Set Up the Project

  1. Initialize a Node.js Project

    mkdir my-smart-contract
    cd my-smart-contract
    npm init -y
  2. Install Dependencies

    npm install ethers solc

Step 2: Write Your Smart Contract

Create MyContract.sol:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract MyContract {
string public message;

constructor(string memory _message) {
message = _message;
}

function setMessage(string memory _message) public {
message = _message;
}
}

Step 3: Compile Your Smart Contract

Create compile.js:

const fs = require('fs');
const solc = require('solc');

const source = fs.readFileSync('MyContract.sol', 'utf8');
const input = {
language: 'Solidity',
sources: { 'MyContract.sol': { content: source } },
settings: { outputSelection: { '*': { '*': ['abi', 'evm.bytecode'] } } },
};

const output = JSON.parse(solc.compile(JSON.stringify(input)));
const contract = output.contracts['MyContract.sol'].MyContract;

fs.writeFileSync('MyContractABI.json', JSON.stringify(contract.abi, null, 2));
fs.writeFileSync('MyContractBytecode.txt', contract.evm.bytecode.object);

Run the script:

node compile.js

Step 4: Deploy Your Smart Contract

Create deploy.js:

const { ethers } = require('ethers');
const fs = require('fs');

const abi = JSON.parse(fs.readFileSync('MyContractABI.json'));
const bytecode = fs.readFileSync('MyContractBytecode.txt', 'utf8');
const provider = new ethers.providers.InfuraProvider('rinkeby', 'YOUR_INFURA_PROJECT_ID');
const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider);

async function main() {
const factory = new ethers.ContractFactory(abi, bytecode, wallet);
const contract = await factory.deploy('Hello, World!');

console.log('Contract address:', contract.address);
console.log('Transaction hash:', contract.deployTransaction.hash);

await contract.deployed();

console.log('Contract deployed successfully');
}

main().catch(console.error);

Replace YOUR_INFURA_PROJECT_ID and YOUR_PRIVATE_KEY with your Infura project ID and wallet private key.

Step 5: Deploy the Contract

Run the deployment script:

node deploy.js

You should see the contract address and transaction hash in the console output.

Conclusion

You've successfully deployed a smart contract using ethers.js. For more information, refer to the ethers.js documentation.