我创建了一个 NameContracts,如下所述:https ://bitsofco.de/calling-smart-contract-functions-using-web3-js-call-vs-send/
我用松露编译和迁移它并启动了 ganache-cli。然后我尝试用web3调用函数getName,但总是报错:
Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
我不确定这意味着什么或我做错了什么。我已经在网上搜索过,但没有一个建议的解决方案对我有用。这是我的代码:
const Web3 = require('web3');
const fs = require('fs');
const rpcURL = "http://localhost:8545";
const web3 = new Web3(rpcURL);
const rawData = fs.readFileSync('NameContract.json');
const jsonData = JSON.parse(rawData);
const abi = jsonData["abi"];
let accounts;
let contract;
web3.eth.getAccounts().then(result =>{
accounts = result;
web3.eth.getBalance(accounts[0], (err, wei) => {
balance = web3.utils.fromWei(wei, 'ether')
console.log("Balance of accounts[0]: " + balance); // works as expected
})
contract = new web3.eth.Contract(abi, accounts[0]);
console.log(contract.methods); // works as expected
console.log(contract.address); // prints undefined
contract.methods.getName().call((result) => {console.log(result)}); // throws error
})