我按照此处的描述创建了一个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
})
实例化合同时,您将帐户地址传递给构造函数,而不是将已部署合同的地址]传递给构造函数。当执行contract.methods.getName().call()
时,它将尝试调用<your_account_name>.getName()
,这当然会失败,因为您的帐户后面没有合约代码,因为它只是一个常规的外部拥有的帐户。
使用$ truffle migrate
部署合同时,它应该已经显示了已部署合同的地址。您必须在JavaScript代码中使用该合同地址创建合同实例。
let contract_address = "0x12f1a3..."; // the address of your deployed contract (see the result of $truffle migrate)
contract = new web3.eth.Contract(abi, contract_address);