1

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 3

2

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
0

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.

1
  • I get an API from verified contracts, but my issue is mapping through the array and pulling the names of the functions to display, and then programmatically calling these functions, WITHOUT knowing them before. How can I require you input the correct params, if I don't know that function X requires ABC, and function Y requires only A and B
    – Zach
    Nov 9, 2018 at 5:17
-1

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()

})
1
  • where is fetchContractABIfromEtherscan() defined?
    – Anupam
    Apr 11, 2021 at 5:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.