Deploying a Smart Contract

Requirements

  1. Node.js
  2. Npm
  3. Ganache
  4. VsCode

Setting up the project

Let’s begin by starting ganache and starting a project

#!/bin/bash# Directory setup
git init ;
mkdir ethereum-project && cd ethereum-project ;
mkdir app;
touch .gitignore app/main.js app/saluten.sol ;
echo node_modules/ > .gitignore
# Npm setup
npm init -y ;
npm install web3 solc ;

We are going to use web3, a collection of libraries that allow you to interact with a local or remote Ethereum node; and solc, a compiler for files with .sol extension.

Creating a Smart Contract

First, we start by writing a simple smart contract that will have two simple getter and setter functions, and a constructor that sets the storedNumber to 5 when the contract gets instantiated.

// "SPDX-License-Identifier: MIT"pragma solidity 0.7.4;contract NumberStorage {
uint storedNumber;

constructor() {
storedNumber = 5;
}
function setNumber(uint x) public {
storedNumber = x;
}
function getNumber() public view returns (uint) {
return storedNumber;
}
}

Basic concepts:

  • uint: Unsigned integer.
  • public: Accessible from outside. For example, other contracts.
  • view: Ensures that it will not modify the state.
  • pure: Ensure that it will not modify or read the state.

Uploading the Contract

Open the main.js file and let’s write

  1. Library imports
const solc = require("solc");
const fs = require("fs");
const Web3 = require("web3");
const web3 = new Web3("http://127.0.0.1:7545"); // Points to ganache

2. Contract compilation, more info at their npm package

var input = {
language: "Solidity",
sources: {
"saluten.sol" : {
content: fs.readFileSync("./app/saluten.sol", "utf8")
}
},
settings: {
outputSelection: { // It returns everything
"*": {
"*": ["*"]
}
}
}
};
const CompiledContract = JSON.parse(solc.compile(JSON.stringify(input)));

3. Data preparation


let contractABI = CompiledContract.contracts['saluten.sol'].NumberStorage.abi
let bytecode = CompiledContract.contracts['saluten.sol'].NumberStorage.evm.bytecode.object

This third step may change depending on the compiler/pragma version you are using. The Json object result of the compiling process might be different but debugging it one can navigate through the nested objects to find the abi and bytecode

4. Contract object and account address

let deployedContract = new web3.eth.Contract(contractABI);
let account = '0xdCC9F2874f78C04dDEED66e51C83c1652A73E663';
// A Ganache application's account address

5. Parameters

let payload = {
data: bytecode
}
let parameter = {
from: account,
gas: web3.utils.toHex(800000),
gasPrice: web3.utils.toHex(web3.utils.toWei('30', 'gwei'))
}

6. Deploying:

deployedContract.deploy(payload).send(parameter, (err, transactionHash) => {
console.log('Transaction Hash :', transactionHash);
}).on('confirmation', () => {}).then((newContractInstance) => {
console.log('Deployed Contract Address : ', newContractInstance.options.address);
})

Full Code With Step Explanation

Now, with ganache running and a simple command…

node app/main.js

.. we can create, compile and upload our smart contract. On the next blog, we will see how to interact with this contract.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Get All values for a key in JSONArray using JAVA

Let’s write JQuery from scratch and why I think JQuery is useless in 2019.

$hopping List App

Tinder Style Movie Night Picker with VueJs and Firebase

mobx-keystone, an alternative to mobx-state-tree without some of its pains

15 Cool VSCode Themes I think you would like

Connect AWS Lambda with snowflake and inserting data in snowflake table (Typescript/JavaScript)

== and === in javascript which is faster?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rodrigo Labrador

Rodrigo Labrador

More from Medium

Coinbase Abruptly Freezes ZCash Transactions

Meta Freecity Uses BSC.tevil462–1.1 Smart Contract

2022 Cloudbric Roadmap Explanation

WAX DEX and marketplaces to explore: AtomicHub, Alcor Exchange, NeftyBlocks and NFTHive