TransWikia.com

How to dynamically load contracts data with their ABI from etherscan API?

Ethereum Asked on November 7, 2021

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

3 Answers

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

Answered by Anupam Kumar on November 7, 2021

The answer to this question is the following:

let abi = fetchContractABIfromEtherscan(addressURL);
let newContract = contract(abi);
        newContract.setProvider(this.props.web3.currentProvider);
let customABIInstance = newContract.at(address);

abi.map(item => {
let res = await customABIInstance[item.name]().call()

})

Answered by Zach on November 7, 2021

You can use the Etherscan API to get any verified contract's ABI. See: https://etherscan.io/apis#contracts for usage examples.

In order to display the available methods in your own application you can iterate through "MyContract.methods" in the example.

Hope this helps.

Answered by Micky Socaci on November 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP