How to call Web3js function from Nodejs file

I have the following web3js working code, Calling App.createContract () when the button is clicked works well on the web page, however I want to call the App.createContract () application or the like from another Nodejs controller. Infact, what I think of, is doing an API in Node that can call the web3js function and return the JSON result back to the caller. Could you help me import my web3js file and call a function from Node Controller? Thanks

import "../stylesheets/app.css";
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract';
import { default as CryptoJS} from 'crypto-js';

var accounts;
var account;
var shLogABI;
var shLogContract;
var shLogCode;
var shLogSource;
window.App = {
  start: function() {
    var self = this;
    web3.eth.getAccounts(function(err, accs) {
      if (err != null) {
        alert("There was an error fetching your accounts.");
        return;
      }
      if (accs.length == 0) {
        alert("Couldn't get any accounts! Make sure your Ethereum client is configured correctly.");
        return;
      }

      accounts = accs;
      console.log(accounts);
      account = accounts[0];
      web3.eth.defaultAccount= account;
      shLogSource= "pragma solidity ^0.4.6; contract SHLog { struct LogData{ string FileName; uint UploadTimeStamp; string AttestationDate; } mapping(uint => LogData) Trail; uint8 TrailCount=0; function AddNewLog(string FileName, uint UploadTimeStamp, string AttestationDate) { LogData memory newLog; newLog.FileName = FileName; newLog.UploadTimeStamp= UploadTimeStamp; newLog.AttestationDate= AttestationDate; Trail[TrailCount] = newLog; TrailCount++; } function GetTrailCount() returns(uint8){ return TrailCount; } function GetLog(uint8 TrailNo) returns (string,uint,string) { return (Trail[TrailNo].FileName, Trail[TrailNo].UploadTimeStamp, Trail[TrailNo].AttestationDate); } }";
      web3.eth.compile.solidity(shLogSource, function(error, shLogCompiled){

        shLogABI = JSON.parse(' [ { "constant": false, "inputs": [ { "name": "TrailNo", "type": "uint8" } ], "name": "GetLog", "outputs": [ { "name": "", "type": "string" }, { "name": "", "type": "uint256" }, { "name": "", "type": "string" } ], "payable": false, "type": "function" }, { "constant": false, "inputs": [ { "name": "FileName", "type": "string" }, { "name": "UploadTimeStamp", "type": "uint256" }, { "name": "AttestationDate", "type": "string" } ], "name": "AddNewLog", "outputs": [], "payable": false, "type": "function" }, { "constant": false, "inputs": [], "name": "GetTrailCount", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "type": "function" } ]');
        shLogContract = web3.eth.contract(shLogABI);

      });
    });
  },
  createContract: function()
  {
    shLogContract.new("", {from:account, gas: 3000000}, function (error, deployedContract){
      if(deployedContract.address)
      {
        document.getElementById("contractAddress").value=deployedContract.address;
        document.getElementById("fileName").value = '';
        document.getElementById("uploadTimeStamp").value = '';
        document.getElementById("attestationDate").value = '';
      }
    })
  },
  addNewLog: function()
  {

    var contractAddress = document.getElementById("contractAddress").value;
    var deployedshLog = shLogContract.at(contractAddress);
    var fileName = document.getElementById("fileName").value;
    var uploadTimeStamp = document.getElementById("uploadTimeStamp").value;
    var attestationDate = document.getElementById("attestationDate").value;
    deployedshLog.AddNewLog(fileName, uploadTimeStamp, attestationDate, function(error){
      console.log(error);
    })
  },
  getLog: function()
  {
    try{
      var contractAddress = document.getElementById("contractAddress").value;
      var deployedshLog = shLogContract.at(contractAddress);
      deployedshLog.GetTrailCount.call(function (error, trailCount){
        deployedshLog.GetLog.call(trailCount-1, function(error, returnValues){
          document.getElementById("fileName").value= returnValues[0];
          document.getElementById("uploadTimeStamp").value = returnValues[1];
          document.getElementById("attestationDate").value=returnValues[2];
        })
      })
    }
    catch (error) {

      document.getElementById("fileName").value= error.message;
      document.getElementById("uploadTimeStamp").value = error.message;
      document.getElementById("attestationDate").value= error.message;
    }
  }
};

window.addEventListener('load', function() {
  if (typeof web3 !== 'undefined') {
    console.warn("Using web3 detected from external source.  If using MetaMask, see the following link. Feel free to delete this warning. :) http://truffleframework.com/tutorials/truffle-and-metamask")
    window.web3 = new Web3(web3.currentProvider);
  } else {
    console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }
  App.start();
});
+4
source share
1 answer

A simple example for web3js 1.0.0.beta*

1) Add web3jsto your package.jsonserver side:

"web3": "^1.0.0-beta.27"

2) web3 :

const Web3 = require('web3');
const web3SocketProvider = new Web3.providers.WebsocketProvider('ws://0.0.0.0:8546');
const web3Obj = new Web3(web3Provider);

web3 :

async function getAccounts() {
   let accounts = await web3Obj.eth.getAccounts();
}
+1

Source: https://habr.com/ru/post/1683600/


All Articles