How to map an ABI interface to an object of functions in Typescript?

Viewed 267

Take for instance an ABI like this:

const abi = [
  {
    name: "myFirstFunction",
    inputs: [
      {
        name: "param1",
        type: "string"
      }
    ],
    outputs: [
      {
        name: "value1",
        type: "string"
      },
      {
        name: "value2",
        type: "number"
      }
    ]
  }
]

What I want to achieve is an object type containing the functions defined in the ABI, like this:

Type MyABIFunctions = {
  myFirstFunction: (param1: string) => [value1: string, value2: number]
}

Is something like this possible in Typescript?

2 Answers

You could use this npm package: ethereum-abi-types-generator

For each different solidity framework, it has different commands. For example for ethers I wrote this script in package.json:

  "genContractType": "abi-types-generator './public/NftMarket.json' --output='./types' --name=nftMarket --provider=ethers_v5",

this will generate a file for the types of your abi

Another option is to generate a complete dAPP smart contract clients with 0xWeb.

If you develop your contract, you can generate a TypeScript class from the ABI json

0xweb i ./artifacts/contracts/Foo.sol/Foo.json --name foo --chain eth

If you consume a deployed and validated contract, you can generate the class by the address

0xweb i 0x123457 --name foo --chain eth

That will generate a strongly typed class for the contract, which you can directly use to communicate with the blockchain, by calling the method like this

const foo = new Foo();
const [ value1, value2 ] = await foo.myFirstFunction();
Related