我是区 block 链开发的新手。为了了解目的,开始在 Node.js 中使用以太坊区 block 链概念开发小型合约
我已经安装了包 "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
在已部署的合约中,我可以看到这些方法。谁能帮我解决这个问题吗?
注意:我已经安装了 "ganache-cli": "^6.1.8"
用于添加事务并单独运行。我可以看到 ganache 中的交易。
最佳答案
我相信问题出在这里:
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(...);
}
}
);
关于javascript - Node.js - 以太坊合约无法调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51968651/