My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 6 Aug 2021
Deploy smart contract on ethereum from nodejs
How to deploy custom smart contract on ethereum from nodejs without truffle, remix or other tools
img
Ganesh Deshpande
0
Like
1356

Introduction

The blockchain developer may get in a need of deploying new smart contract with the help of user interaction. Let's say if the DApp is designed on ethereum blockchain which enables the user to create a lottery pool of its own and destroy after some fixed time period, The DApp developer might be willing to create a new smart contract for each of the lottery pools created by user just to enhance security and some functionalities to his DApp, He may need to compile and deploy several smart contracts then, that too involving user interaction.

 

Prerequisites

Get Public/Private key

In order to deploy smart contract , ethereum account is required. These key pairs can be got from any ethereum wallet, eg. metamask. Make sure the selected wallet has some funds in it.

RPC provider

To connect the appliction to blockchain RPC provider has a vital role. There are may free and paid rpc providers for ethereum network. Since free rpc provider might have very big load on it, you can select infura as provider. Create project and get api key.

 

Configurations & Installations

Install NodeJs

As the complete project code is designed in node , install nodejs.

Initialise node

$ npm init

Create file

$ touch index.js

Install web3

$ npm install web3

Install solc

npm install solc

Package.json

The complete package.json will look like this -

{
  "name": "deploysmfromnodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "solc": "^0.8.6",
    "web3": "^1.5.1"
  }
}

 

Writig code

Steps :

Import variables

Open index.js in any editor & Import the following in index.js file

const path = require('path');
const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');

Define file path

Set the smart contract file path 

const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');

 here the contract file is Storage.sol

Initialise compiler

Configure the solidity compiler and compile the file

const input = {
    language: 'Solidity',
    sources: {
        'Storage.sol': {
            content: source,
        },
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['*'],
            },
        },
    },
};

const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];

define variables

const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

const privKey = '<private key>'; 
const address = '<address>';

const web3 = new Web3("https://ropsten.infura.io/v3/<api>");

replace the privatekey and address variables with the public/private key pairs and also the provider url in Web3(provider). Select the proper provider along with the network. Here the contract will be deployed on ropsten test network.

The bytecode and abi is taken from the compiled contract. these are needed to sign the transaction later.

Create a function

const deploy = async() => {

    console.log('Attempting to deploy from account:', address);
    const incrementer = new web3.eth.Contract(abi);

    const incrementerTx = incrementer.deploy({
        data: bytecode
        // arguments: [],
    })
    const createTransaction = await web3.eth.accounts.signTransaction({
            from: address,
            data: incrementerTx.encodeABI(),
            gas: 3000000,
        },
        privKey
    )
    const createReceipt = web3.eth.sendSignedTransaction(createTransaction.rawTransaction).then((res) => {
        console.log('Contract deployed at address', res.contractAddress);
    });

};

First get the instance of contract in incrementer then create a raw transaction by deploying the contract and signing it with private key. later send the signed transaction to blockchain, the return receipt will be complete info about deployed contract.

call the function

deploy();

Execute the file

$ node index.js

 

complete code 

const path = require('path');
const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');

// Compile contract
const contractPath = path.resolve(__dirname, 'Storage.sol');
const source = fs.readFileSync(contractPath, 'utf8');

const input = {
    language: 'Solidity',
    sources: {
        'Storage.sol': {
            content: source,
        },
    },
    settings: {
        outputSelection: {
            '*': {
                '*': ['*'],
            },
        },
    },
};

const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Storage.sol']['Storage'];


// Initialization
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

const privKey = '<private key>'; 
const address = '<address>';

const web3 = new Web3("https://ropsten.infura.io/v3/<api>");

// Deploy contract
const deploy = async() => {

    console.log('Attempting to deploy from account:', address);
    const incrementer = new web3.eth.Contract(abi);

    const incrementerTx = incrementer.deploy({
        data: bytecode
        // arguments: [],
    })
    const createTransaction = await web3.eth.accounts.signTransaction({
            from: address,
            data: incrementerTx.encodeABI(),
            gas: 3000000,
        },
        privKey
    )
    const createReceipt = web3.eth.sendSignedTransaction(createTransaction.rawTransaction).then((res) => {
        console.log('Contract deployed at address', res.contractAddress);
    });

};
deploy();
Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11508
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8103
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6229
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5540
3