[Ethereum] How to dynamically load contracts data with their ABI from etherscan API

etheretherscango-ethereumjavascript

Im wanting to pull data from a smart contract I've loaded via user address and etherscan API for the ABI.

But how would I go about programmatically adding all the functions from the ABI into my front end?

Basically, say I want to look up the crypto kitties contract and get the ABI via etherscan API.

But how would I know what functions to call or list?

Say I want to do what etherscan does and let you call different functions from the abi?

Basically workflow:

User puts in address.
Pull ABI from etherscan
Load contract with ABI
??? How to add all the functions to my front end via the ABI, using JS. ???

How do I call a function without knowing the function name such as getKittyData

Best Answer

You can do a get query through axios, which can fetch the ABI directly:

rpcEndpoint = `...`;
addressURL = `...`;

const axios = require("axios");
const Web3 = require("web3");
var web3 = new Web3(new Web3.providers.HttpProvider(rpcEndpoint));

async function main() {
  url =
    `http://api-kovan.etherscan.io/api?module=contract&action=getabi&address=` +
    addressURL +
    `&format=raw`;
  console.log("Get request at: ", url);

  res = await axios.get(url);
  console.log(res.data);
}
main();

Successful output:

 [{ inputs: [ [Object], [Object] ],
    name: 'withdraw',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function' },
  ...
  { inputs: [],
    name: 'withdrawable',
    outputs: [ [Object] ],
    stateMutability: 'view',
    type: 'function' } ]

Unsuccessful output:

Contract source code not verified
Related Topic