如何从Nodejs文件中调用Web3js函数

时间:2017-08-13 03:39:12

标签: node.js ethereum truffle web3js

我有以下工作web3js代码,按钮点击调用App.createContract()在网页上运行良好,但是我想从另一个Nodejs控制器调用App.createContract()或类似代码。事实上,我在想的是在Node中创建一个API,它可以调用web3js函数并将JSON结果返回给调用者。你能帮我解决一下如何导入我的web3js文件并从节点控制器调用该函数吗?感谢

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's 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();
});

1 个答案:

答案 0 :(得分:1)

web3js 1.0.0.beta*

的简单示例

1)将web3js添加到服务器端的package.json

"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();
}