Type Safety & ABI Caching with thirdweb Generate

Mike Shin

We're excited to introduce a new command to our CLI; thirdweb generate.

npx thirdweb generate

Let's dive into what it is, why we built it, and how you can get started.

Background - Our SDK and ABI Management

Our React and TypeScript SDKs allow you to easily connect to your smart contracts by providing your smart contract address, like so:

const sdk = new ThirdwebSDK("polygon");
const contract = sdk.getContract("0x..."); // No ABI needed!

This abstracts away the complexity of copy-pasting smart contract ABIs, and saves you the headache of ensuring your ABIs are up-to-date with the latest version.

Learn more about how this works from our engineering team's blog post:

Self-verifiable contracts using solc and IPFS
Interacting with deployed contracts using web3 libraries like ethers.js requires having a copy of the contract ABI somewhere in your code, and keeping it up to date is a manual and error prone process. Using the thirdweb SDKs, ABIs are automatically inferred from any deployed contracts. All you need…
Post by Joaquim Verges, thirdweb Principal Engineer

The trade-off to this approach is that the SDK doesn't know your contract ABIs at build-time; meaning your IDE doesn't know what functions, arguments, and return values your smart contracts have while you're developing.

As a developer, there's a lack of type-safety and little IDE support when working with your smart contracts that don't conform to common standards like ERC721, ERC1155, ERC20, etc.

In addition to this, apps using these functions were waiting for the SDK to fetch the ABI each time they called getContract with our SDK; making the performance slightly slower on each new request than if they just provided the ABI upfront.

Introducing thirdweb Generate

For these reasons, we built generate; a new command in our CLI that:

  1. Detects all smart contract addresses in your project
  2. Fetches the ABIs for each address
  3. Caches them in memory (inside node_modules)
  4. Provides type safety for smart contract interactions on:
    - in the Typescript SDK
    - useContractRead and useContractWrite in the React SDK

This provides better performance in your application and a safer developer experience when working with your smart contracts.

Get Started with Generate

To get these benefits, all you need to do is use our CLI to run the generate command from within your project directory:

npx thirdweb generate

This will create a thirdweb.json file at the root of your project which you can update with any new contract addresses you want to cache in the future.

View the full reference and available options in our documentation:

Generate | thirdweb developer portal
Preload contract ABIs and generate types for your smart contract to strongly type the thirdweb SDK.

Here's a demo of the benefits you'll get out of the box: