Nodejs with Smart contract for beginner version 0.4.17

Install Nodejs on ubuntu

bash
sudo
apt update
sudo
apt install nodejsnode -vv18.19.0

Truffle

Truffle is a development framework for building decentralized applications (dapps) on the blockchain, specifically on the Ethereum network. It provides tools and libraries to simplify development, including smart contract creation, testing, deployment, and management.

Vscode Plugin

Mochajs

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.

Build Nodejs project

bash
npm init

It will make package.json

Install solc

bash
npm install solc@0.4.26

inbox.sol

solidity
pragma solidity ^0.4.17;
contract Inbox {
  string public message;
  function Inbox(string initialMessage) public {
    message = initialMessage;
  }
  function setMessage(string newMessage) public {
    message = newMessage;
  }
}

compile.js

javascript
const path = require('path');
const fs = require('fs');
const solc = require('solc');
const inboxPath = path.resolve(__dirname, 'contracts', 'Inbox.sol');
const source = fs.readFileSync(inboxPath, 'utf8');
console.log(solc.compile(source, 1));
// 1 is the number of contracts we are compiling

Run compile.js

bash
npm install @truffle/hdwallet-providernode compile.js
json
{  contracts: {    ':Inbox': {      assembly: [Object],      bytecode: '606..',      functionHashes:
[Object],      gasEstimates: [Object],      interface:
'[{"constant":false,"inputs":[{"name":"newMessage","type":"string"}],"name":"setMessage","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"message","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"initialMessage","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]',      metadata: '{"compiler":{"version":"0.4.17+commit.bdeb9e52"},"language":"Solidity","output":{"abi":[{"constant":false,"inputs":[{"name":"newMessage","type":"string"}],"name":"setMessage","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"message","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"initialMessage","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}],"devdoc":{"methods":{}},"userdoc":{"methods":{}}},"settings":{"compilationTarget":{"":"Inbox"},"libraries":{},"optimizer":{"enabled":true,"runs":200},"remappings":[]},"sources":{"":{"keccak256":"0xcf32bc45deff4c661bc812c6626a1d59f89a03cbd33be9e29bc53877b7795dda","urls":["bzzr://4641a40b0545ee62b215e759ccbb1201d2c21103816847ea8f56f60353564be3"]}},"version":1}',      opcodes: 'PUSH1 0x60 PUSH1 0x40 MSTORE .. 0x58B712FA588DA6C4E604E56B37CEE21FAA100A0029000000 ',      runtimeBytecode: '60606..',      srcmap: ''    }  },  sourceList: [ '' ],  sources: { '': { AST: [Object] } }}

Ganache

https://trufflesuite.com/ganache/
https://github.com/trufflesuite/ganache-ui

Ganache is your personal blockchain for Ethereum development.

bash
npm install --save mocha ganache-cli web3
npm install web3@^0.20.6 //depricate
npm install web3

Abigen

Abigen is a binding-generator for easily interacting with Ethereum using Go. Abigen creates easy-to-use, type-safe Go packages from Ethereum smart contract definitions known as ABIs. This abstracts away a lot of the complexity of handling smart contract deployment and interaction in Go native applications such as encoding and decoding smart contracts into EVM bytecode. Abigen comes bundled with Geth. A full Geth installation includes the abigen binary. Abigen can also be built independently by navigating to go-ethereum/cmd/abigen and running go build, or equivalently:

What is an ABI?

Ethereum smart contracts have a schema that defines its functions and return types in the form of a JSON file. This JSON file is known as an Application Binary Interface, or ABI. The ABI acts as a specification for precisely how to encode data sent to a contract and how to decode the data the contract sends back. The ABI is the only essential piece of information required to generate Go bindings. Go developers can then use the bindings to interact with the contract from their Go application without having to deal directly with data encoding and decoding. An ABI is generated when a contract is compiled.

Inbox.test.js

javascript
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
// ganache.provider() is the provider that connects to the ganache network
class Car {
  park(){
    return 'stopped';
  }
  drive(){
    return 'vroom';
  }
}
describe('Car example', () => {
  it('can park', () => {
    const car = new Car();
    assert.equal(car.park(), 'stopped');
  });
  it('can drive', () => {
    const car = new Car();
    assert.equal(car.drive(), 'vroom');
  });
});

we need to change in package.json

jsonc
"scripts": {    // "test": "echo \"Error: no test specified\" && exit 1"    "test": "mocha"  },

then run the test

bash
npm run test
Nodejs with Smart contract for beginner version 0.4.17

Gnache makes accounts for working easily.

Nodejs with Smart contract for beginner version 0.4.17
web3.eth.accounts is deprecated.

1

I end up solving this error by changing the version of web3, I was in version 0.20.x, and I changed it to the latest version, which was 1.4.0.

Get list of account in web3:

javascript
// Get a list of all accounts    web3.eth.getAccounts()

check the code:

javascript
// Get a list of all accounts    web3.eth.getAccounts().then( fetchedAccounts => {
console.log(fetchedAccounts);        });    // Use one of those accounts to deploy the contract

‍‍‍Add in package.json:

jsonc
"scripts": {    "test": "mocha"  },

Run the test:

https://medium.com/coinmonks/ethereum-smart-contract-development-with-a-web-app-part-2-testing-and-deployment-34a885e750b2
https://medium.com/coinmonks/ethereum-smart-contract-development-with-a-web-app-part-2-testing-and-deployment-34a885e750b2
javascript
let accounts;
beforeEach(async () => {
  accounts = await web3.eth.getAccounts();
});
describe('Inbox', () => {
  it('deploys a contract', () => {
    console.log(accounts)
  });
});
Nodejs with Smart contract for beginner version 0.4.17

Deploy contract

javascript
const assert = require('assert');
const ganache = require('ganache-cli');
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
// ganache.provider() is the provider that connects to the ganache network
const {
  interface, bytecode
}
= require('../compile');
let accounts;
let inbox;
beforeEach(async () => {
  accounts = await web3.eth.getAccounts();
  // Use one of those accounts to deploy the contract inbox =
  await new web3.eth.Contract(JSON.parse(interface)).deploy({
    data : bytecode, arguments: ['Hi Bye']
  }).send({
    from: accounts[0], gas : '1000000'
  })
});

web3.eth.Contract

The web3.eth.Contract object makes it easy to interact with smart contracts on the ethereum blockchain. When you create a new contract object you give it the json interface of the respective smart contract and web3 will auto convert all calls into low level ABI calls over RPC for you.

This allows you to interact with smart contracts as if they were JavaScript objects.

Let me explain the ABI’s role. In the context of decentralized applications (dApps), the ABI is essential for interacting with a smart contract. The ABI acts as the bridge between two binary program modules, in this case, your front-end application and the deployed smart contract on the blockchain.

Without the ABI, your front-end wouldn’t know how to structure calls to the contract’s functions, what data types to use, or how to interpret the data returned from function calls.

So, if you’ve deployed a contract without saving its ABI, you’ll generally have trouble integrating it into a dApp. That said, the ABI is generated when you compile the smart contract, not when you deploy it. If you still have access to the original source code of the smart contract, you can re-compile it to obtain the ABI, without having to redeploy the contract. Many development tools and environments, like Truffle or Remix, make it easy to extract the ABI upon compilation.

Show the address

javascript
let accounts;
let inbox;
beforeEach(async () => {
  accounts = await web3.eth.getAccounts();
  // Use one of those accounts to deploy the contract inbox =
  await new web3.eth.Contract(JSON.parse(interface)).deploy({
    data : bytecode, arguments: ['Hi Bye']
  }).send({
    from: accounts[0], gas : '1000000'
  })
});
describe('Inbox', () => {
  it('deploys a contract', () => {
    console.log(inbox.options.address);
    assert.ok(inbox.options.address);
  });
});
Nodejs with Smart contract for beginner version 0.4.17

Get message value

javascript
it("has a default message", async () => {
  const message = await inbox.methods.message().call();
  assert.equal(message, "Hi Bye");
});
Nodejs with Smart contract for beginner version 0.4.17

Set Message Value

javascript
it("can change the message", async () => {
  await inbox.methods.setMessage("bye").send({ from: accounts[0] });
  const message = await inbox.methods.message().call();
  assert.equal(message, "bye");
});
Nodejs with Smart contract for beginner version 0.4.17

Connect to real network

bash
npm install @truffle/hdwallet-provider

Infura

https://www.infura.io/

Infura’s development suite provides instant, scalable API access to the Ethereum and IPFS networks. Connect your app to Ethereum and IPFS now, for free!

Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17

https://app.infura.io/register

Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17

Deploy.js

javascript
const HDWalletProvider = require('@truffle/hdwallet-provider');
const Web3 = require('web3');
const {
  interface, bytecode
}
= require('./compile');
const provider = new
HDWalletProvider('help mydecade fee world movie dmage issue clay country aware do',
'https://sepolia.infura.io/v3/1d23e111028d4e94aac4f272f1ab97298');
const web3 = new Web3(provider);
const deploy = async () => {
  const accounts = await web3.eth.getAccounts();
  console.log('Attempting to deploy from account', accounts[0]);
  const result = await new web3.eth.Contract(JSON.parse(interface)).deploy({
    data : bytecode, arguments: ['Hi there!']
  }).send({
    gas : '1000000', from: accounts[0]
  });
  console.log('Contract deployed to', result.options.address);
  provider.engine.stop();
}
deploy();

node deploy.js

https://sepolia.etherscan.io

Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17
Nodejs with Smart contract for beginner version 0.4.17

Update source code

Visit us at DataDrivenInvestor.com

Subscribe to DDIntel here.

Have a unique story to share? Submit to DDIntel here.

Join our creator ecosystem here.

DDIntel captures the more notable pieces from our main site and our popular DDI Medium publication. Check us out for more insightful work from our community.

DDI Official Telegram Channel: https://t.me/+tafUp6ecEys4YjQ1

Follow us on LinkedIn, Twitter, YouTube, and Facebook.