DEV Community

Eray Kaya
Eray Kaya

Posted on • Edited on

Coding Smart: Using TypeChain for Type Generation from Smart Contract ABI

Utilizing the right tools is crucial to establishing a typesafe development environment when navigating blockchain data. One such instrument is TypeChain, which streamlines this process by converting ABI (Application Binary Interface) files into TypeScript types. This straightforward conversion allows developers to construct fully typesafe queries or mutations with react-query, leading to an enhanced development experience.

Let's delve into how this process works.

First, we need to install the necessary packages: typechain and @typechain/ethers-v5.

Installation is straightforward and can be executed by running the following commands:

yarn add typechain @typechain/ethers-v5 -D

Next, it's recommended to house your ABIs in a dedicated folder for better organization. For example, you could place them in src/abis. Let's also assume that the output directory is types/abis.

To facilitate this process, an npm script should be written as follows to package.json:

"typechain": "typechain --target ethers-v5 --out-dir ./types/config/abis './src/config/abis/*.json'"

The script will utilize TypeChain to generate TypeScript typings for Ethereum smart contracts. It targets ethers-v5 and specifies an output directory for the typings.

Running this script is as simple as executing yarn typechain in your terminal.

In conclusion, by adopting TypeChain and integrating it into your development environment, you can easily interact with your contract and elevate the overall developer experience. The ability to create type-safe queries or mutations, combined with an organized, dedicated location for your ABIs, paves the way for a more streamlined and efficient coding experience.

Top comments (1)

Collapse
 
sawakaga profile image
Mert Anıl Gören

Great article ! It helped Thanks