hardhat-abi-exporter icon indicating copy to clipboard operation
hardhat-abi-exporter copied to clipboard

feat: typescript format

Open hbriese opened this issue 1 year ago • 1 comments

Description

Add typescript as a format option.

This allows importing the abi with the constant type in TypeScript, making the abi usable by viem. Currently this is done either manually, using typechain or through bespoke generator scripts (example)

Example ABI

[
  {
    "inputs": [],
    "stateMutability": "nonpayable",
    "type": "constructor"
  }
]

becomes

export default [
  {
    "inputs": [],
    "stateMutability": "nonpayable",
    "type": "constructor"
  }
] as const;

Example usage (viem)

import { encodeFunctionData } from 'viem';
import ERC20 from '../abi/ERC20'; // Your exported contract abi

// Fully typed thanks to viem and the const abi
encodeFunctonData({
  abi: ERC20,
  functionName: 'transfer',
  args: ['0x...', 100n],
});

hbriese avatar Nov 21 '23 06:11 hbriese

This change is not compatible with the clear-abi task. For safety, files are verified to be valid ABIs before they're deleted. This is meant to prevent data loss if a user accidentally sets an incorrect ABI output directory.

Two specific problems in the clear-abi task:

  1. The .json file extension is hardcoded.
  2. The contents of the ABI are passed to the ethers Interface constructor for validation. Presumably the .ts format does not work here.

I'd rather not add branching logic for each special case, which must work consistently across multiple tasks. Testing that many branches can get rather difficult.

Maybe .ts support should be moved to a separate task, which would re-export the .json files to a separate directory. Though this probably wouldn't work with the pretty format option. Or maybe the need for .ts support is widespread enough that the extra complexity is worth it? I'm not sure, any thoughts?

ItsNickBarry avatar Nov 22 '23 02:11 ItsNickBarry