How to deploy Solidity smart contracts using ethers.js

How to deploy Solidity smart contracts using ethers.js

If you have developed DApps on Ethereum, you may have used web3.js in your front-end JavaScript. Ethers.js is a lightweight alternative to web3.js.

Ethers.js has many advantages over Web3.js, and one of my favorite features is the state and key management that Ethers.js provides. The design scenario of Web3 is that DApp should connect to a local node, which is responsible for storing keys, signing transactions and interacting with the Ethereum blockchain. The reality is that this is not the case, and the vast majority of users will not run a geth node locally. Metamask effectively simulates this node environment in browser applications, so most web3 applications need to use Metamask to save keys, sign transactions, and complete interactions with Ethereum.

Ethers.js adopts a different design approach, which provides developers with more flexibility. Ethers.js splits a "node" into two distinct roles:

Wallet: responsible for key storage and transaction signature provider: responsible for anonymous connection, status checking and transaction sending of the Ethereum network.

ethers.js is a very streamlined Ethereum operation library, which contains the following four modules:
Ethers.provider
Ethers.contract
Ethers.utils
Ethers.wallets
Among them, Ethers.provider is responsible for connecting with Ethereum nodes, querying transactions, broadcasting transactions, obtaining account balances, etc.
Ethers.contract is responsible for interacting with smart contracts, including deploying contracts, monitoring events in contracts, obtaining information in contracts, calling functions in contracts, etc.
Ethers.utils is a tool library that is mainly used to process input and output data, and convert data types and formats;
Ethers.wallets is mainly used to create new wallets, connect or switch existing wallets, and sign transactions.
Next, we will introduce how to deploy smart contracts using Ethers.js.

1. Create a new project sendtokenone

mkdir sendtokenone
cd sendtokenone
npm init -y
truffle init

2. Modify package.json and install dependent packages

a) The modified package.json file is as follows:
//package.json

{
  "name": "sendtokenone",
  "version": "1.0.0",
  "description": "ethers.js deployment contract",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@openzeppelin/contracts": "^3.4",
    "@truffle/hdwallet-provider": "^1.5.0",
    "bignumber": "^1.1.0",
    "bignumber.js": "^8.1.1",
    "chai": "^4.2.0",
    "chai-as-promised": "^7.1.1",
    "eslint": "^5.15.0",
    "ethereumjs-tx": "^1.3.7",
    "ethers": "^5.4.7",
    "request": "^2.88.2",
    "web3": "^1.3.0"
  },
  "devDependencies": {
    "@babel/core": "^7.12.3",
    "@babel/preset-env": "^7.12.1"
  }
}

b) Install dependent packages

npm install

3. Create a new smart contract

3.1 Create an EventValue.sol contract

In the sendtokenone/contacts directory, create an EventValue.sol contract with the following content:
// EventValue.sol

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

contract EventValue {
    event ValueChanged(address indexed author,uint oldValue,uint newValue);
    uint _value;

    constructor(uint value) public {
        uint tmp = _value;
        _value = value;
        emit ValueChanged(msg.sender, tmp, value);
    }
    function getValue() view public returns (uint) {
        return _value;
    }
    function setValue(uint value) public {
        uint tmp = _value;
        _value = value;
        emit ValueChanged(msg.sender, tmp, value);
    }
}

3.2 Writing deployment scripts

Create a new folder named migDeploy, and then create a deployment script 1_deploy_event.js in this folder

mkdir migDeploy
cd migDeploy
touch 1_deploy_event.js

The content of 1_deploy_event.js is as follows:
// sendtokenone/migDeploy/1_deploy_event.js

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

let provider = new ethers.providers.JsonRpcProvider('http://localhost:8545')

function getHexString(prikeyPath) {
    const privKeyFile = fs.readFileSync(prikeyPath).toString().trim();
    const privKey = new Buffer.from(privKeyFile, 'hex');    
    return privKey
}

// var privKey = getHexString(".secret")
var privKey = '0x403d...23d5'
let wallet = new ethers.Wallet(privKey,provider)

var jsonStr = fs.readFileSync('./build/contracts/EventValue.json')
var jsonInfo = JSON.parse(jsonStr)
var jsonAbi = jsonInfo.abi
var bytecode = jsonInfo.bytecode

async function deployContract(abi,bytecode,wallet) {
    let factory = new ethers.ContractFactory(abi,bytecode,wallet)
    let contractObj = await factory.deploy(100)
    console.log('contractAddress=',contractObj.address)
    console.log('deploy txHash=',contractObj.deployTransaction.hash)

    await contractObj.deployed()   
}

deployContract(jsonAbi,bytecode,wallet)



3.3 Compile the contract

a) Set ganache's IP to 127.0.0.1 and port to 8545
b) In truffle-config.js, enable the development network segment and specify the solc version as 0.6.6, as follows:
// truffle-config.js

module.exports = {
  networks:

    development:
     host: "127.0.0.1", // Localhost (default: none)
     port: 8545, // Standard Ethereum port (default: none)
     network_id: "*", // Any network (default: none)
    },

  },

  // Set default mocha options here, use special reporters etc.
  mocha:
    // timeout: 100000
  },

  // Configure your compilers
  compilers:
    solc: {
      version: "0.6.6", // Fetch exact version from solc-bin (default: truffle's version)
      // docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
      // settings: { // See the solidity docs for advice about optimization and evmVersion
      // optimizer: {
      // enabled: false,
      // runs: 200
      // },
      // evmVersion: "byzantium"
      // }
    }
  },

};

Open a black frame console and use truffle to compile the contract

cd sendtokenone
truffle console
compile

3.4 Deployment of Contract

In the black frame terminal, enter the following command to deploy the contract

cd sendtokenone
node migDeploy\1_deploy_event.js

The effect is as follows:

Figure (1) Deployment of contract using ether.js

The contract address and txHash can be printed, indicating that the contract deployment is successful.

This is the end of this article about using ethers.js to deploy Solidity smart contracts. For more information about ethers.js deploying Solidity smart contracts, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  Docker installation and configuration image acceleration implementation

>>:  Implementation of mysql data type conversion

Recommend

Solution to the welcome to emergency mode message when booting CentOS7.4

Today I used a virtual machine to do an experimen...

JavaScript canvas realizes colorful sun halo effect

This article example shares the specific code of ...

How to disable the automatic password saving prompt function of Chrome browser

Note: In web development, after adding autocomplet...

How to submit a pure HTML page, pass parameters, and verify identity

Since the project requires a questionnaire, but th...

An article to solve the echarts map carousel highlight

Table of contents Preface toDoList just do it Pre...

Detailed explanation of Linux command unzip

Table of contents 1. unzip command 1.1 Syntax 1.2...

SQL Server database error 5123 solution

Because I have a database tutorial based on SQL S...

Docker's four network types principle examples

Four network types: None: Do not configure any ne...

VUE implements a Flappy Bird game sample code

Flappy Bird is a very simple little game that eve...

Mybatis fuzzy query implementation method

Mybatis fuzzy query implementation method The rev...

The difference between div and span in HTML (commonalities and differences)

Common points: The DIV tag and SPAN tag treat som...

Share 5 JS high-order functions

Table of contents 1. Introduction 2. Recursion 3....