0

I am trying to get the contract ABI using the Etherscan API, and then create a contract instance and call a method. I am able to get the ABI from Etherscan but when creating the contract object I am getting this error: "You must provide the json interface of the contract when instantiating a contract object." This is what my code looks like

let url = 'https://api.etherscan.io/api?module=contract&action=getabi&address=0x672C1f1C978b8FD1E9AE18e25D0E55176824989c&apikey=<api-key>';
request(url, (err, res, body) => {
  if (err) {
    console.log(err);
  }
  let data = JSON.parse(body);
  let contract_abi = data.result;
  console.log(contract_abi)
  let contract_address = '0x672C1f1C978b8FD1E9AE18e25D0E55176824989';
  const contract = new web3.eth.Contract(contract_abi);
  const contract_instance = contract.at(contract_address);
  // Call contract method
})

When I console.log the contract_abi I see the ABI data. I've also tried creating the contract by doing

const contract = new web3.eth.Contract(contract_abi, contract_address)

Thanks!

1 Answers1

1

data.result contains the JSON ABI as a string. You need to decode it as well to an object.

let contract_abi = JSON.parse(data.result);

Also, it's possible that you're using a deprecated version of Web3 that supports the contract.at() syntax.

But if you're using the current version, you'd get the contract.at is not a function error. In that case, you need to pass the address as the second argument of the Contract constructor.

const contract = new web3.eth.Contract(contract_abi, contract_address);
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100