首页 > 解决方案 > Error: You must provide the json interface of the contract when instantiating a contract object

问题描述

const Web3 = require('web3');
const web3 = new Web3('http://foodchain-node1.etherhost.org:22001');
const CONTRACT_ADDRESS = "0xA4fafbE0ea4823e262b4916EF93CC5A6306A5DBc";

async function eventQuery(){
    'use strict';
    var fs = require('fs');
    var data = fs.readFileSync('food3.abi', 'utf-8');
    //console.log(data);
    //console.log(typeof JSON.parse(data).interface)
    const CONTRACT_ABI = JSON.parse(data);
    const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);
    const START_BLOCK = 7700000;
    const END_BLOCK = 7701000;
    contract.getPastEvents("FoodSection",
        {                               
            fromBlock: START_BLOCK,     
            toBlock: END_BLOCK     
        })                              
    .then(events => console.log(events))
    .catch((err) => console.error(err));
}

eventQuery();

I created this code and everytime I ran it, it returns the error of "Error: You must provide the json interface of the contract when instantiating a contract object." I am guessing it have something to do with the json parse of the 'food3.abi' file but I do not know how to correct it. Could somebody please let me know what is my mistake and how to fix it?

标签: node.jsjsonweb3js

解决方案


我尝试运行您的示例,但没有收到错误,因此您拥有的文件可能存在问题food3.abi(例如,如果您从某处复制粘贴 ABI,您可能错过了 [])。

这是我遵循的步骤。也许它也对你有用。

  1. 安装 solcnpm install -g solc
  2. 编译合约solcjs --abi contract.sol。这将contract_sol_contract.abi在同一文件夹中创建一个文件
  3. fs.readFileSync()在语句中使用生成的abi文件

推荐阅读