Published on 8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs

Interacting with smart contract function from client side is very easy, there we can easily use metamask as provider and sign the transaction but from backend its somewhat difficult because we have to sign transaction manually.

Prerequisites

There are may methods to do this, I will explain easiest one for the beginners point of view. For this tutorial we are using ropsten testnet, you can use any but keep same testent everywhere otherwise it will not work.

 

Key pairs

We need account public,private key pairs . You can get it from metamask itself. 

 

web3

we need npm web3 module you can install it from 

npm install web3

 

HDwalletprovider

npm install @truffle/hdwallet-provider

 

RPC Url

You can use localhost if you are using ganache , but for ropsten infura is good, go to infura website create account craete poject and get rpc url it will look like this - https://ropsten.infura.io/v3/your_api_key

 

Contract Address, ABI

we need smart contract address and ABI, deploy contract on remix and get address and ABI, deploy it on ropsten.

 

Sample contract

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract Storage {

    uint256 number;

    function store(uint256 num) public {
        number = num;
    }

    function retrieve() public view returns (uint256){
        return number;
    }
}

 

package.json

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@truffle/hdwallet-provider": "^1.4.1",
    "express": "^4.17.1",
    "web3": "^1.2.9"
  }
}

 

index.js

var express = require('express');
var Web3 = require('web3');
const Provider = require('@truffle/hdwallet-provider');

var app = express();
var port = process.env.PORT || 3000;

var SmartContractAddress = "your smart contract address";
var SmartContractABI = contract_abi;
var address = "account adress"
var privatekey = "private key of the above account address";
var rpcurl = "infura rpc url";

const sendData = async () => {

  console.log("in function");
  var provider = new Provider(privatekey, rpcurl);
  var web3 = new Web3(provider);
  var myContract = new web3.eth.Contract(SmartContractABI, SmartContractAddress);
  var oldvalue = await myContract.methods.retrieve().call();
  console.log("oldvalue", oldvalue);


  var receipt = await myContract.methods.store(5781).send({ from: address });
  console.log(receipt);

  var newvalue = await myContract.methods.retrieve().call();
  console.log("newvalue", newvalue);

  console.log("done with all things");

}

sendData();

app.listen(port);
console.log('listening on', port);

 

Explanation

 

Step 1:

complete prerequisites..

 

Step 2:

prepare nodejs project, just 2 files are enough, index.js and package.json.

paste the above package.json in file and use npm install this will create node_modules folder

paste index.js code in your file replace all the variables with your own variables

 

Step3:

const sendData = async () => {

  console.log("in function");
  var provider = new Provider(privatekey, rpcurl);
  var web3 = new Web3(provider);
  var myContract = new web3.eth.Contract(SmartContractABI, SmartContractAddress);
  var oldvalue = await myContract.methods.retrieve().call();
  console.log("oldvalue", oldvalue);


  var receipt = await myContract.methods.store(5781).send({ from: address });
  console.log(receipt);

  var newvalue = await myContract.methods.retrieve().call();
  console.log("newvalue", newvalue);


  console.log("done with all things");

}

sendData();
  • Defined provider with private key and rpcurl
  • initiated web3 with provider
  • got our contract instance with web3, contract abi, contract address
  • fetched the old value number from contract (retrieve() is the funtion defined in our smart contract which returns the number)
  • then sent data to change the number with the help of store function (store() is the function defined in our smart contract which takes argument and changes the value of number)
  • then again fetched the value to check if its changed

thats it, now you are able to interact with smart contract functions from backend nodeJS,
hapy DApp building !

5273
1
2