{
  "slug": "Nodejs-with-Smart-contract-for-beginner-version-0-4-17-59ee1d46aced",
  "title": "Nodejs with Smart contract for beginner version 0.4.17",
  "subtitle": "Install Nodejs on ubuntu",
  "excerpt": "Install Nodejs on ubuntu",
  "date": "2023-12-12",
  "tags": [
    "Linux"
  ],
  "readingTime": "6 min",
  "url": "https://medium.com/@mobinshaterian/nodejs-with-smart-contract-for-beginner-version-0-4-17-59ee1d46aced",
  "hero": "https://cdn-images-1.medium.com/max/800/1*z1WKbpTCs5nWum4sbg-nMg.png",
  "content": [
    {
      "type": "heading",
      "level": 2,
      "text": "Nodejs with Smart contract for beginner version 0.4.17"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Install Nodejs on ubuntu"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "sudo\napt update\nsudo\napt install nodejsnode -vv18.19.0"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Truffle"
    },
    {
      "type": "paragraph",
      "html": "Truffle is <strong>a development framework for building decentralized applications (dapps) on the blockchain, specifically on the Ethereum network</strong>. It provides tools and libraries to simplify development, including smart contract creation, testing, deployment, and management."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Vscode Plugin"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Mochajs"
    },
    {
      "type": "paragraph",
      "html": "Mocha is a feature-rich JavaScript test framework running on <a href=\"https://nodejs.org/\" target=\"_blank\" rel=\"noreferrer noopener\">Node.js</a> and in the browser, making asynchronous testing <em>simple</em> and <em>fun</em>. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on <a href=\"https://github.com/mochajs/mocha\" target=\"_blank\" rel=\"noreferrer noopener\">GitHub</a>."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Build Nodejs project"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm init"
    },
    {
      "type": "paragraph",
      "html": "It will make package.json"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Install solc"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm install solc@0.4.26"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "inbox.sol"
    },
    {
      "type": "code",
      "lang": "solidity",
      "code": "pragma solidity ^0.4.17;\ncontract Inbox {\n  string public message;\n  function Inbox(string initialMessage) public {\n    message = initialMessage;\n  }\n  function setMessage(string newMessage) public {\n    message = newMessage;\n  }\n}"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "compile.js"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "const path = require('path');\nconst fs = require('fs');\nconst solc = require('solc');\nconst inboxPath = path.resolve(__dirname, 'contracts', 'Inbox.sol');\nconst source = fs.readFileSync(inboxPath, 'utf8');\nconsole.log(solc.compile(source, 1));\n// 1 is the number of contracts we are compiling"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Run compile.js"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm install @truffle/hdwallet-providernode compile.js"
    },
    {
      "type": "code",
      "lang": "json",
      "code": "{  contracts: {    ':Inbox': {      assembly: [Object],      bytecode: '606..',      functionHashes:\n[Object],      gasEstimates: [Object],      interface:\n'[{\"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] } }}"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Ganache"
    },
    {
      "type": "paragraph",
      "html": "<a href=\"https://trufflesuite.com/ganache/\" target=\"_blank\" rel=\"noreferrer noopener\">https://trufflesuite.com/ganache/</a><br><a href=\"https://github.com/trufflesuite/ganache-ui\" target=\"_blank\" rel=\"noreferrer noopener\">https://github.com/trufflesuite/ganache-ui</a>"
    },
    {
      "type": "paragraph",
      "html": "Ganache is your personal blockchain for Ethereum development."
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm install --save mocha ganache-cli web3\nnpm install web3@^0.20.6 //depricate\nnpm install web3"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Abigen"
    },
    {
      "type": "paragraph",
      "html": "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:"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "What is an ABI?"
    },
    {
      "type": "paragraph",
      "html": "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 <em>Application Binary Interface</em>, 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."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Inbox.test.js"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "const assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\n// ganache.provider() is the provider that connects to the ganache network\nclass Car {\n  park(){\n    return 'stopped';\n  }\n  drive(){\n    return 'vroom';\n  }\n}\ndescribe('Car example', () => {\n  it('can park', () => {\n    const car = new Car();\n    assert.equal(car.park(), 'stopped');\n  });\n  it('can drive', () => {\n    const car = new Car();\n    assert.equal(car.drive(), 'vroom');\n  });\n});"
    },
    {
      "type": "paragraph",
      "html": "we need to change in package.json"
    },
    {
      "type": "code",
      "lang": "jsonc",
      "code": "\"scripts\": {    // \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"    \"test\": \"mocha\"  },"
    },
    {
      "type": "paragraph",
      "html": "then run the test"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm run test"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*YlicWKbSjz_oMKuI-Kj0NA.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 182,
      "height": 140
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Gnache makes accounts for working easily."
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*CnvbYk4j48BqTxpXW5UI7g.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 807,
      "height": 519
    },
    {
      "type": "quote",
      "html": "<em>web3.eth.accounts is deprecated.</em>"
    },
    {
      "type": "paragraph",
      "html": "1"
    },
    {
      "type": "paragraph",
      "html": "I end up solving this error by changing the version of <strong>web3</strong>, I was in version <em>0.20.x</em>, and I changed it to the latest version, which was 1.4.0."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Get list of account in web3:"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "// Get a list of all accounts    web3.eth.getAccounts()"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "check the code:"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "// Get a list of all accounts    web3.eth.getAccounts().then( fetchedAccounts => {\nconsole.log(fetchedAccounts);        });    // Use one of those accounts to deploy the contract"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "‍‍‍Add in package.json:"
    },
    {
      "type": "code",
      "lang": "jsonc",
      "code": "\"scripts\": {    \"test\": \"mocha\"  },"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Run the test:"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*z1WKbpTCs5nWum4sbg-nMg.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 440,
      "height": 339
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*ILtx0XkrBRp774MoTv5AhA.png",
      "alt": "https://medium.com/coinmonks/ethereum-smart-contract-development-with-a-web-app-part-2-testing-and-deployment-34a885e750b2",
      "caption": "https://medium.com/coinmonks/ethereum-smart-contract-development-with-a-web-app-part-2-testing-and-deployment-34a885e750b2",
      "width": 516,
      "height": 522
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "let accounts;\nbeforeEach(async () => {\n  accounts = await web3.eth.getAccounts();\n});\ndescribe('Inbox', () => {\n  it('deploys a contract', () => {\n    console.log(accounts)\n  });\n});"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*MtgCMse-sryOitKESzNkFQ.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 440,
      "height": 339
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Deploy contract"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "const assert = require('assert');\nconst ganache = require('ganache-cli');\nconst Web3 = require('web3');\nconst web3 = new Web3(ganache.provider());\n// ganache.provider() is the provider that connects to the ganache network\nconst {\n  interface, bytecode\n}\n= require('../compile');\nlet accounts;\nlet inbox;\nbeforeEach(async () => {\n  accounts = await web3.eth.getAccounts();\n  // Use one of those accounts to deploy the contract inbox =\n  await new web3.eth.Contract(JSON.parse(interface)).deploy({\n    data : bytecode, arguments: ['Hi Bye']\n  }).send({\n    from: accounts[0], gas : '1000000'\n  })\n});"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "web3.eth.Contract"
    },
    {
      "type": "paragraph",
      "html": "The <code>web3.eth.Contract</code> 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."
    },
    {
      "type": "paragraph",
      "html": "This allows you to interact with smart contracts as if they were JavaScript objects."
    },
    {
      "type": "paragraph",
      "html": "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."
    },
    {
      "type": "paragraph",
      "html": "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."
    },
    {
      "type": "paragraph",
      "html": "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."
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Show the address"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "let accounts;\nlet inbox;\nbeforeEach(async () => {\n  accounts = await web3.eth.getAccounts();\n  // Use one of those accounts to deploy the contract inbox =\n  await new web3.eth.Contract(JSON.parse(interface)).deploy({\n    data : bytecode, arguments: ['Hi Bye']\n  }).send({\n    from: accounts[0], gas : '1000000'\n  })\n});\ndescribe('Inbox', () => {\n  it('deploys a contract', () => {\n    console.log(inbox.options.address);\n    assert.ok(inbox.options.address);\n  });\n});"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*RGIQnN42uFHb_X2HE34uvQ.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 400,
      "height": 135
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Get message value"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "it(\"has a default message\", async () => {\n  const message = await inbox.methods.message().call();\n  assert.equal(message, \"Hi Bye\");\n});"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*r77m24ACQTifIxVovbs_OA.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 400,
      "height": 135
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Set Message Value"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "it(\"can change the message\", async () => {\n  await inbox.methods.setMessage(\"bye\").send({ from: accounts[0] });\n  const message = await inbox.methods.message().call();\n  assert.equal(message, \"bye\");\n});"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*_1_YSvGAFbZFXIDVAT766w.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 400,
      "height": 135
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Connect to real network"
    },
    {
      "type": "code",
      "lang": "bash",
      "code": "npm install @truffle/hdwallet-provider"
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Infura"
    },
    {
      "type": "paragraph",
      "html": "<a href=\"https://www.infura.io/\" target=\"_blank\" rel=\"noreferrer noopener\">https://www.infura.io/</a>"
    },
    {
      "type": "paragraph",
      "html": "Infura’s <em>development suite provides instant, scalable API access to the Ethereum and IPFS networks</em>. Connect your app to Ethereum and IPFS now, for free!"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*J0Ow5x-TsUk4MO40SOYlrw.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 961,
      "height": 171
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*qN8MQp8afjjoiKygJaadVA.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 746,
      "height": 383
    },
    {
      "type": "paragraph",
      "html": "<a href=\"https://app.infura.io/register\" target=\"_blank\" rel=\"noreferrer noopener\">https://app.infura.io/register</a>"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*WqeQusDyXuIMzKJHyvx1_w.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 258,
      "height": 78
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*-mInY32zeEtINHLgq2ZGDg.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 1506,
      "height": 162
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Deploy.js"
    },
    {
      "type": "code",
      "lang": "javascript",
      "code": "const HDWalletProvider = require('@truffle/hdwallet-provider');\nconst Web3 = require('web3');\nconst {\n  interface, bytecode\n}\n= require('./compile');\nconst provider = new\nHDWalletProvider('help mydecade fee world movie dmage issue clay country aware do',\n'https://sepolia.infura.io/v3/1d23e111028d4e94aac4f272f1ab97298');\nconst web3 = new Web3(provider);\nconst deploy = async () => {\n  const accounts = await web3.eth.getAccounts();\n  console.log('Attempting to deploy from account', accounts[0]);\n  const result = await new web3.eth.Contract(JSON.parse(interface)).deploy({\n    data : bytecode, arguments: ['Hi there!']\n  }).send({\n    gas : '1000000', from: accounts[0]\n  });\n  console.log('Contract deployed to', result.options.address);\n  provider.engine.stop();\n}\ndeploy();"
    },
    {
      "type": "heading",
      "level": 3,
      "text": "node deploy.js"
    },
    {
      "type": "paragraph",
      "html": "<a href=\"https://sepolia.etherscan.io\" target=\"_blank\" rel=\"noreferrer noopener\">https://sepolia.etherscan.io</a>"
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*LQh1ebdNXmxp6j0aUYYF2w.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 707,
      "height": 40
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*pXsFrvE_5A7IM4cKnWf50w.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 1404,
      "height": 157
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*0X5V8hN1k0cF3bL6tMzqtg.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 958,
      "height": 598
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*YZpvLdacb2drHt6v3WBQKg.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 300,
      "height": 625
    },
    {
      "type": "image",
      "src": "https://cdn-images-1.medium.com/max/800/1*8_1eXHUCjfRF1yxpVVTu-g.png",
      "alt": "Nodejs with Smart contract for beginner version 0.4.17",
      "caption": "",
      "width": 354,
      "height": 547
    },
    {
      "type": "heading",
      "level": 2,
      "text": "Update source code"
    },
    {
      "type": "paragraph",
      "html": "Visit us at <a href=\"https://www.datadriveninvestor.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>DataDrivenInvestor.com</em></a>"
    },
    {
      "type": "paragraph",
      "html": "Subscribe to DDIntel <a href=\"https://www.ddintel.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>here</em></a>."
    },
    {
      "type": "paragraph",
      "html": "Have a unique story to share? Submit to DDIntel <a href=\"https://datadriveninvestor.com/ddintelsubmission\" target=\"_blank\" rel=\"noreferrer noopener\"><em>here</em></a>."
    },
    {
      "type": "paragraph",
      "html": "Join our creator ecosystem <a href=\"https://join.datadriveninvestor.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>here</em></a>."
    },
    {
      "type": "paragraph",
      "html": "<a href=\"https://ddintel.datadriveninvestor.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>DDIntel</em> </a>captures the more notable pieces from our <a href=\"https://www.datadriveninvestor.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>main site</em></a> and our popular <a href=\"https://medium.datadriveninvestor.com/\" target=\"_blank\" rel=\"noreferrer noopener\"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community."
    },
    {
      "type": "paragraph",
      "html": "DDI Official Telegram Channel: <a href=\"https://t.me/+tafUp6ecEys4YjQ1\" target=\"_blank\" rel=\"noreferrer noopener\">https://t.me/+tafUp6ecEys4YjQ1</a>"
    },
    {
      "type": "paragraph",
      "html": "Follow us on <a href=\"https://www.linkedin.com/company/data-driven-investor\" target=\"_blank\" rel=\"noreferrer noopener\"><em>LinkedIn</em></a>, <a href=\"https://twitter.com/@DDInvestorHQ\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Twitter</em></a>, <a href=\"https://www.youtube.com/c/datadriveninvestor\" target=\"_blank\" rel=\"noreferrer noopener\"><em>YouTube</em></a>, and <a href=\"https://www.facebook.com/datadriveninvestor\" target=\"_blank\" rel=\"noreferrer noopener\"><em>Facebook</em></a>."
    }
  ]
}
