Open In App

How to deploy Smart Contracts using Ethers.js and Node.js on Goerli Testnet Blockchain from Back-end ?

In this article, we will be deploying smart contracts on blockchain from back-end, so that we do not have to require hardhat or truffle frameworks and their commands to deploy a smart contract or if somebody doesn’t want to use these frameworks. Since we have to run manual commands of these frameworks in the terminal to deploy Smart Contracts.  We can directly deploy smart contracts by simply running the function in the node i.e. if somebody wants to deploy a smart contract on click from the front-end, we can easily connect the contract deploying function to the front-end through node REST API. 

The ethers.js library can be used to deploy Smart Contracts on Blockchain and can also be used to interact with the deployed Contract. It is a very simple library that can be used for developing decentralized applications like NFT marketplace, Defi, Token Exchange, and many more. It is comparatively simpler than the web3.js library.



Deploying smart contracts or interacting with a smart contract on the blockchain requires a gas fee. The amount of gas fee required depends upon the length and complexity of our smart contract. We are going to deploy this contract on Goerli Testnet. This testnet is used by developers to test their decentralized application before deploying it to the blockchain mainnet so they don’t have to waste money on gas fees. There are other testnet networks present as well but we are going to use goerli because their faucets (free small amount of Ethereum funds) are easily available. These Ethereum funds will work as the gas fee for our purpose. For our smart contract, a very less amount of gas fee i.e. Goerli Ethereum Funds will be required. 

Pre-requisites:



STEP 1: Setting up pre-requisites

Solidity Extension by Juan Blanco

This extension provides a compiler to compile our solidity contract. 

Warning: Please make sure you keep your private key super secret or you may lose your funds from your metamask.  For this use of the “dotenv” npm package is strongly recommended. Avoid sharing your private key or uploading it to github.

For getting your private key follow these steps 

Metamask Wallet

Save your private key in a txt or dotenv file, you will require it later to use your GoerliEth for deploying the contract. Prepending “0x” before your private key string is recommended if it is not already present before the private key or later you may face issues like “bytes-like object required”.  It is not compulsory if you do not face this issue later. 

Demo app created on Alchemy

It will look something like the above image, click on the view key. Now you will be able to see your API KEY. For privacy reasons API key shouldn’t be revealed, avoid publishing it on public platforms or sharing it. Save API KEY, it will also be required while deploying your smart contract.

STEP 2:  Generating abi and bytecode files from our solidity file.

npm init -y 




// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
 
contract EtherContract {
    string public name;
 
    function setName(string memory _name) public {
        name = _name;
    }
 
    function getName() public view returns(string memory){
        return name;
    }
}

Compilation Result

And you will see an extra folder will be generated named “bin” in your local directory which contains “abi”, “bin” and “.json” files. It will be like this:

File Structure

Now compilation of your smart contract is done.

STEP 3: Writing deployment code in js file: We will need the “ethers” library to interact with the blockchain. To install ethers just run the command below.

npm i ethers@5.7.2

Make sure you keep the version as defined above. Because things may change in upcoming versions or beta versions of the ethers library.

Now, we will put my javascript code here and explain the code line by line with the required arguments and files. First, create a js file of your desired name, for me, it is “deployContract.js”. And the code is:




const output = require("./bin/EtherContract.json");
const ABI = output.abi;
const bytecode = output.bytecode;
const ethers = require("ethers");
 
const deploy = async function () {
    try {
        const provider = new ethers.providers
            .AlchemyProvider("goerli", YOUR_ALCHEMY_API_KEY);
        const Wallet = new ethers.Wallet(
            YOUR_METAMASK_ACCOUNT_PRIVATE_KEY, provider);
        const ContractInstance = new ethers
            .ContractFactory(ABI, bytecode, Wallet);
        const contractInstance =
            await ContractInstance.deploy();
        await contractInstance.deployed();
        console.log("Deployed contract address - ",
            contractInstance.address);
        const setNameInitialResponse =
            await contractInstance.setName("GeeksforGeeks");
        await setNameInitialResponse.wait();
        let contractReturnedString =
            await contractInstance.getName();
        console.log("Output value of getName() function "
            + "of solidity Smart contract - ",
            contractReturnedString);
    } catch (err) {
        console.log("Error in deploying contract.");
        console.log(err);
    }
};
 
deploy();

const provider = new ethers.providers
    .AlchemyProvider("goerli", "YOUR_ALCHEMY_API_KEY");
const Wallet = new ethers.Wallet(
    "YOUR_METAMASK_ACCOUNT_PRIVATE_KEY", provider);
const ContractInstance = new ethers
    .ContractFactory(ABI, bytecode, Wallet);
const contractInstance = await ContractInstance.deploy();

STEP 4: Deploying Contract 

Now run your file with the node command, since my js file name is “deployContract.js”. I will run the command in the local folder terminal. I am running the function by command but this same thing can be done by running the function through REST APIs.

node deployContract.js

Wait till the transaction settles on the blockchain. And now we will be able to our output in the output window. 

Output:

Output

The contract and its transaction details can also be seen on the goerli etherscan which shows all transactions of the blockchain.

Etherscan Output

Note that with some minor changes in the above javascript code, we can also deploy the smart contracts on other testnet or mainnet as well.  

References:-


Article Tags :