2

我创建了一个 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
})
4

1 回答 1

3

实例化您的合约时,您将您的帐户地址传递给构造函数,而不是您部署的合约的地址。执行时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);
于 2019-12-17T20:22:04.813 回答