Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to deploy Smart Contracts using Ethers.js and Node.js on Goerli Testnet...

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:

  • Node.js
  • VS Code
  • Solidity Extension(by Juan Blanco)  from VS Code Extensions
  • MetaMask Wallet in your chrome browser(For your accounts private key and ether funds)
  • Alchemy API key

STEP 1: Setting up pre-requisites

  • Node.js and VS code can easily be installed for your respective operating systems.
  • For Solidity Extension in VS code. Go to VS code extensions and install the extension shown below image.

Solidity Extension by Juan Blanco

This extension provides a compiler to compile our solidity contract. 

  • For beginners in blockchain, MetaMask is a software cryptocurrency wallet. We can set it up in any of our browsers or in our mobile. If you already had set up your metamask wallet. Select your network from the Ethereum mainnet to the Goerli testnet. then you need to get goerli Ethereum (i.e. GoerliETH) funds in one of the accounts of your wallet. You can get test ethers from various goerli provider faucet available on the internet. Now after having GoerliEth. You will require your account’s PRIVATE KEY. 

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 

  • Login to your Metamask wallet in your browser.
  • Go to the three dots shown in below Metamask image

Metamask Wallet

  • Now go to “Account details” > “Export Private Key”
  • Enter your metamask password. Your private key will be revealed.

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. 

  • Alchemy is a blockchain developer platform that provides API that allows us to communicate with the Ethereum chain without having to run our own nodes.  For the API key or project id, you can grab it from Alchemy’s official website. To get an API key signup there It will ask some simple questions, make sure to select goerli as your network and it will create a demo app for you.  If it does not create a demo app, you can manually create your own.

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.

  • First, create your package.json file for setting up the node environment by running the below command in the terminal of your desired directory.
npm init -y 
  • Create a solidity Smart Contract file with the extension of “.sol”. We are deploying a simple contract that simply sets and gets a string variable name on the blockchain. My “.sol” file name is “etherContract.sol”. We made this contract simple because as we already mentioned the long, more complex, and memory-consuming contract is, the more gas fee will be. So my Smart contract is:

Solidity




// 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;
    }
}


  • Now open your solidity smart contract i.e. “etherContract.sol” file in VS code and press F5 It will compile your smart contract. This compilation is made possible by that solidity extension you installed earlier. Make sure your smart contract is formatted, If it is not formatted it will not compile. To format your code right click in your .sol file and click on “Format Document” there or just press Ctrl + Shift + I. After compiling your console window will be like this:-

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:

Javascript




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("neveropen");
        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();


  • On the first three lines of code, we have required the “abi” and “bytecode” of the smart contract So that we can make our local contract instance object be deployed. Make sure you give the right path to your JSON file.
  • On line 4 I am requiring the ethers library.
  • Now inside our “deploy()” function – on line 8,
const provider = new ethers.providers
    .AlchemyProvider("goerli", "YOUR_ALCHEMY_API_KEY");
  • The AlchemyProvider object takes two arguments, First is the name of the network on which we are going to deploy our contract, here I am deploying the contract on the testnet “goerli” so I have specified the same. The second argument is the API key from alchemy which we saved earlier and pass as a string.
  • Now on line 9, 
const Wallet = new ethers.Wallet(
    "YOUR_METAMASK_ACCOUNT_PRIVATE_KEY", provider);
  • Wallet object takes two arguments first is your PRIVATE KEY which we saved earlier and second is the provider object on line 8. For a private key set up your metamask wallet. This line is to make a Wallet instance for your code from your private key. 
  • Now on line 10,
const ContractInstance = new ethers
    .ContractFactory(ABI, bytecode, Wallet);
  • We are making an object of our contract to be deployed. It takes three arguments here ABI and bytecode which we required in the first three lines of code. The wallet is the object which we just created on line 10.
  • On line 11,
const contractInstance = await ContractInstance.deploy();
  • On this line, we are deploying the contract. In our smart contract, there is no constructor. But if your smart contract constructor takes arguments then those will be passed in this deploy function. This function returns a promise which gets resolved when the initial transaction is sent to the blockchain.
  • On line 12, The deployed() function returns the promise which gets resolved when the transaction of deployment gets settled on the blockchain. On this, our smart contract gets deployed on the blockchain. Transaction/gas fee will be deducted from your metamask wallet account.
  • On line 13, I am simply printing the address of the contract deployed on the blockchain. 
  • The “contractInstance” instance can also be used in the same javascript code to access public state variables in your smart contract or call your smart contract functions. Obviously, Functions and variables will only be available when the contract is successfully deployed.
  • So on line 14, we are calling the setName() function of our solidity smart Contract which takes one argument. The returned promise confirms that the transaction is sent successfully. And contains some initial transaction details.
  • On line 15, The wait() function returns the promise which gets resolved when the transaction gets settled on the blockchain.
  • On lines 16 and 17 I am getting the output of our program.
  • On the remaining lines, I have handled exceptions in case of any errors. 

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

RELATED ARTICLES

Most Popular

Recent Comments