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

Node.js - Ethereum Contracts unable to call the functions

我是区块链开发的新手。为了学习目的,在 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" 用于添加交易和 运行ning sepratly。我可以在 ganache 中看到交易。

我认为问题出在这里:

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

.new()这里不会return部署的合约实例。 (我不确定 return 是什么?)您需要回调,例如:

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