4

我有以下工作的 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();
});
4

1 回答 1

1

简单的例子web3js 1.0.0.beta*

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

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

web32)要求并与一些提供者一起初始化:

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();
}
于 2018-03-19T12:41:53.443 回答