1.0.3 • Published 3 months ago

ethers-abitype v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
3 months ago

Makes ethers.js much better. Adds strict typing for Contract class based on ABI using the abitype library. For those who like this feature in viem, but not viem itself.

Installation

npm i ethers-abitype

Usage

The library provides a special type for the Contract class and in your code you only need to override the type

Example without ABI typing (your regular ethers.js code):

import { Contract } from "ethers";

const address = "0x...";
const abi = [
  /*..*/
];

const contract = new Contract(address, abi);

Example code with ABI typing:

import { Contract } from "ethers";
+ import { TypedContract } from "ethers-abitype";

const address = "0x...";
const abi = [
  /*..*/
- ];
+ ] as const;

- const contract = new Contract(address, abi);
+ const contract = new Contract(address, abi) as unknown as TypedContract<typeof abi>;

Congratulations, you now have a typed contract!

Alternatively, the library provides another approach. You can use a small wrapper function for creating an already typed contract:

- import { Contract } from "ethers";
+ import { typedContract } from "ethers-abitype";

const address = "0x...";
const abi = [
  /*..*/
- ];
+ ] as const;

- const contract = new Contract(address, abi);
+ const contract = typedContract(address, abi);

Important! Your ABI must be declared using a const assertion. This means that you will not be able to store them in a JSON file, because TypeScript doesn't support importing JSON as const

You can also use Human-Readable ABI using parseAbi from abitype:

import { typedContract } from "ethers-abitype";
import { parseAbi } from "abitype";

const address = "0x...";
const abi = parseAbi([
  "function symbol() external returns (string)",
  "function decimals() external returns (uint256)",
  /* ... */
]);

const contract = typedContract(address, abi);
1.0.3

3 months ago

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago