Node.js-以太坊合约无法调用函数

时间:2018-08-22 14:03:13

标签: javascript node.js blockchain ethereum web3

我是区块链开发的新手。为了学习目的,开始在Node.js中使用以太坊区块链概念开发小型合同

我已经安装了"solc": "^0.4.24""web3": "^0.20.7"软件包,以便在Node中构建和编译合同。

我的Grades.sol文件:

pragma solidity ^0.4.24;

contract Grades {
    mapping (bytes32 => string) public grades;
    bytes32[] public studentList;

    function Grades(bytes32[] studentNames) public {
        studentList = studentNames;
    }

    function giveGradeToStudent(bytes32 student, string grade) public {
        require(validStudent(student));
        grades[student] = grade;
    }

    function validStudent(bytes32 student) view public returns (bool) {
        for(uint i = 0; i < studentList.length; i++) {
            if (studentList[i] == student) {
                return true;
            }
        }
        return false;
    }

    function getGradeForStudent(bytes32 student) view public returns (string) {
        require(validStudent(student));
        return grades[student];
    }
}

还有我的compile.js文件。

const path = require('path');
const fs = require('fs');
const solc = require('solc');
const Web3 = require('web3');


const helloPath = path.resolve(__dirname,'contracts','Grades.sol');
const source = fs.readFileSync(helloPath,'UTF-8');

compiledCode = solc.compile(source);

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

abiDefinition = JSON.parse(compiledCode.contracts[':Grades'].interface);

GradesContract = web3.eth.contract(abiDefinition);

byteCode = compiledCode.contracts[':Grades'].bytecode

deployedContract = GradesContract.new(['John','James'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000}); 

deployedContract.giveGradeToStudent('John', 'A+', {from: web3.eth.accounts[0]});

我试图编译并运行,但出现异常

TypeError: deployedContract.giveGradeToStudent is not a function

在deployedContract中,我可以看到这些方法。有人可以帮我吗?

注意:我已经安装了"ganache-cli": "^6.1.8"来添加事务并单独运行。我可以在ganache中查看交易。

1 个答案:

答案 0 :(得分:1)

我相信问题在这里

deployedContract = GradesContract.new(['John','James'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000});

.new()不会返回已部署的合同实例。 (我不确定它是否返回任何东西?)您需要一个回调,如下所示:

deployedContract = GradesContract.new(
  ['John', 'James'],
  {data: byteCode, from: web3.eth.accounts[0], gas: 4700000},
  function (err, instance) {
    if (instance.address) {
      instance.giveGradeToStudent(...);
    }
  }
);