Coder Social home page Coder Social logo

abitype's Introduction


ABIType logo

Strict TypeScript types for Ethereum ABIs


Strict TypeScript types for Ethereum ABIs. ABIType provides utilities and type definitions for ABI properties and values, covering the Contract ABI Specification, as well as EIP-712 Typed Data.

import type { AbiParametersToPrimitiveTypes, ExtractAbiFunction, ExtractAbiFunctionNames } from 'abitype'
import { erc20Abi } from 'abitype/abis'

type FunctionNames = ExtractAbiFunctionNames<typeof erc20Abi, 'view'>
//   ^? type FunctionNames = "symbol" | "name" | "allowance" | "balanceOf" | "decimals" | "totalSupply"

type TransferInputTypes = AbiParametersToPrimitiveTypes<
  // ^? type TransferInputTypes = readonly [`0x${string}`, bigint]
  ExtractAbiFunction<typeof erc20Abi, 'transfer'>['inputs']
>

Works great for adding blazing fast autocomplete and type checking to functions, variables, or your own types. No need to generate types with third-party tools – just use your ABI and let TypeScript do the rest!

TL;DR

ABIType might be a good option for your project if:

  • You want to typecheck your ABIs or EIP-712 Typed Data.
  • You want to add type inference and autocomplete to your library based on user-provided ABIs or EIP-712 Typed Data, like Wagmi and Viem.
  • You need to convert ABI types (e.g. 'string') to TypeScript types (e.g. string) or other type transformations.
  • You need to validate ABIs at runtime (e.g. after fetching from external resource).
  • You don’t want to set up a build process to generate types (e.g. TypeChain).

Documentation

For documentation and guides, visit abitype.dev.

Community

For help, discussion about best practices, or any other conversation that would benefit from being searchable:

Discuss ABIType on GitHub

For casual chit-chat with others using the library:

Join the Wevm Discord

Sponsors

If you find ABIType useful or use it for work, please consider supporting development on GitHub Sponsors or sending crypto to wevm.eth. Thank you πŸ™

Contributing

Contributions to ABIType are greatly appreciated! If you're interested in contributing to ABIType, please read the Contributing Guide before submitting a pull request.

abitype's People

Contributors

ardislu avatar benschac avatar bind avatar dependabot[bot] avatar frangio avatar github-actions[bot] avatar illyism avatar izayl avatar jxom avatar kevinbluer avatar kyscott18 avatar raiden1411 avatar shuoer86 avatar simlecode avatar ssalbdivad avatar stanleyding avatar tmm avatar xenoliss avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

abitype's Issues

bug: bytes32 type is too strict

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

latest

TypeScript Version

latest

Current Behavior

The type for bytes32 only accepts hex numbers of type 0x..... Have to awkwardly convert bytes to a hex value. I think not accepting a string makes sense as it could be a mistake but literal bytes should be valid
image

Expected Behavior

Should loosen type to accept bytes arrays too

Link to Minimal Reproducible Example (TypeScript Playground)

https://github.com/ethereum-optimism/optimism/blob/ef8d1454ddd68cc6a42129549595cb0f1d84af87/packages/atst/src/index.ts

Steps To Reproduce

Pass in any bytes array to a contract method that accepts bytes32

image

Anything else?

No response

Unable to resolve "abitype/zod" in Expo React Native

Describe the bug

Hi guys! How is it going? Hope you are doing well :)

I'm trying to use the SDK in my React Native project but I'm facing the following issue when trying to run the app. I'm using Expo and it's a development build.

iOS Bundling failed 3099ms
Unable to resolve "abitype/zod" from "node_modules/@alchemy/aa-core/dist/cjs/account/schema.js"
[MyApp] Unable to resolve module abitype/zod from
/Users/manu/Documents/MyApp/app/node_modules/@alchemy/aa-core/dist/cjs/account/schema.js:
abitype/zod could not be found within the project or in these directories:
node_modules/@alchemy/aa-core/node_modules
node_modules

\^[[0m \^[[90m  5 |\^[[39m \^[[33mObject\^[[39m\^[[33m.\^[[39mdefineProperty(exports\^[[33m,\^[[39m
\^[[32m"__esModule"\^[[39m\^[[33m,\^[[39m { value\^[[33m:\^[[39m \^[[36mtrue\^[[39m
})\^[[33m;\^[[39m\^[[0m
\^[[0m \^[[90m  6 |\^[[39m exports\^[[33m.\^[[39m\^[[33mSimpleSmartAccountParamsSchema\^[[39m
\^[[33m=\^[[39m exports\^[[33m.\^[[39mcreateBaseSmartAccountParamsSchema \^[[33m=\^[[39m
\^[[36mvoid\^[[39m \^[[35m0\^[[39m\^[[33m;\^[[39m\^[[0m
\^[[0m\^[[31m\^[[1m>\^[[22m\^[[39m\^[[90m  7 |\^[[39m \^[[36mconst\^[[39m zod_1 \^[[33m=\^[[39m
require(\^[[32m"abitype/zod"\^[[39m)\^[[33m;\^[[39m\^[[0m
\^[[0m \^[[90m    |\^[[39m                        \^[[31m\^[[1m^\^[[22m\^[[39m\^[[0m
\^[[0m \^[[90m  8 |\^[[39m \^[[36mconst\^[[39m viem_1 <…>

Do you have some idea of the origin of the issue? Please and thank you

Related issue in Alchemy SDK: alchemyplatform/aa-sdk#282

Link to Minimal Reproducible Example

No response

Steps To Reproduce

No response

Package Version

0.8.11

TypeScript Version

5.2.2

Anything else?

No response

Validations

Abi `Zod` schema does not infer to `Abi` type

Describe the bug

The Zod Abi schema provided from abitype/zod does not match the Abi type from abitype

Link to Minimal Reproducible Example

https://github.com/mathieu-bour/abitype-zod/blob/main/index.ts

Steps To Reproduce

import { Abi } from 'abitype';
import { Abi as AbiSchema } from 'abitype/zod';

const result: Abi = AbiSchema.parse([]);

Package Version

0.9.8

TypeScript Version

5.2.2

Anything else?

TypeScript error:

index.ts:4:7 - error TS2322: Type '({ type: "error"; name: string; inputs: AbiParameter[]; } | { type: "event"; name: string; inputs: (AbiParameter & { indexed?: boolean | undefined; })[]; anonymous?: boolean | undefined; } | ({ ...; } & ({ ...; } | ... 2 more ... | { ...; })))[]' is not assignable to type 'Abi'.
  Type '{ type: "error"; name: string; inputs: AbiParameter[]; } | { type: "event"; name: string; inputs: (AbiParameter & { indexed?: boolean | undefined; })[]; anonymous?: boolean | undefined; } | ({ ...; } & ({ ...; } | ... 2 more ... | { ...; }))' is not assignable to type 'AbiConstructor | AbiError | AbiEvent | AbiFallback | AbiFunction | AbiReceive'.
    Type '{ stateMutability: "pure" | "view" | "nonpayable" | "payable"; constant?: boolean | undefined; gas?: number | undefined; payable?: boolean | undefined; } & { type: "constructor"; inputs: AbiParameter[]; }' is not assignable to type 'AbiConstructor | AbiError | AbiEvent | AbiFallback | AbiFunction | AbiReceive'.
      Type '{ stateMutability: "pure" | "view" | "nonpayable" | "payable"; constant?: boolean | undefined; gas?: number | undefined; payable?: boolean | undefined; } & { type: "constructor"; inputs: AbiParameter[]; }' is missing the following properties from type 'AbiFunction': name, outputs

4 const result: Abi = AbiSchema.parse([]);

Validations

Error when build in Nextjs 12.1.6

Describe the bug

I'm using wallet connect 2 in my project and when I run "npm run build" have an error
./node_modules/viem/node_modules/abitype/dist/types/human-readable/formatAbi.d.ts:18:35
Type error: Type parameter declaration expected.

export declare function formatAbi<const TAbi extends Abi | readonly unknown[]>(abi: TAbi): FormatAbi;

  • How to fix errors?

image

Link to Minimal Reproducible Example

No response

Steps To Reproduce

No response

Package Version

0.8.11

TypeScript Version

5.1.6

Anything else?

No response

Validations

Extra space in formatAbi return type

Describe the bug

Trying to write a test that involves asserting the correct types are emited by Evmts, I noticed a mismatch between formatAbi and abitype. Abitype has an extra space in the parameters. Not a big deal in practice but a little janky looking and for me it's blocking me asserting that Evmts LSP is emitting right type here

Link to Minimal Reproducible Example

https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAbzgM2iAhjAggI2HAXxSghDgHJ08YBPMAU3IChRJZE4B3KYGegMWAAbegGUaAOwDGhYqQrIAzsyZSIExfHpQpAJgAMufAF44AbSYBIBFcsAiNRpjoJMOwC44MKAFd6AGls7YAkwHxhFD3MAXUDLewl0E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RBgkC6k0si0lFPeVIADWqUNqOeoSMVORch1OW3VjjzAgAHvQgJZThhmeUjBMHqt6Mk1Om3RiElvW7b0O0TVuP4yjhMu+ObuUh7vZe-QVs29z7YI8We7M5UrPBWTeJYIyzLDCreL0CyNyjTrLjqAbPhG59pSzZGGlR-jse+wn2O7PeqMQq75kS3XnzR43Tp24zF4QCny6dxtZt9z78f2zVu37SHh2EkFpNBJ5AAqUBXldeepAXeNuHWTDRHA6CKHATZMKoCkoGgmB8ICRhwKYqBQBg2B4AAFNoeiGHgACUQA

Steps To Reproduce

Use formatAbi and notice extra spaces when you hover
image

Package Version

0.9.3

TypeScript Version

5.1.6

Anything else?

No response

Validations

bug: tuple[] generated type is incorrect?

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

0.2.5

TypeScript Version

4.7.4

Current Behavior

for a given function in ABI

{
    inputs: [{ internalType: 'uint64[]', name: 'partIds', type: 'uint64[]' }],
    name: 'getParts',
    outputs: [
      {
        components: [
          { internalType: 'enum IRMRKBaseStorage.ItemType', name: 'itemType', type: 'uint8' },
          { internalType: 'uint8', name: 'z', type: 'uint8' },
          { internalType: 'address[]', name: 'equippable', type: 'address[]' },
          { internalType: 'string', name: 'metadataURI', type: 'string' },
        ],
        internalType: 'struct IRMRKBaseStorage.Part[]',
        name: '',
        type: 'tuple[]',
      },
    ],
    stateMutability: 'view',
    type: 'function',
  }

abittype tells me that the return value is (Array of objects)

readonly {itemType: number, z: number, equippable: readonly `0x${string}`[], metadataURI: string}[]

but in reality it is (Array of arrays)

[number, number, `0x${string}`, string][]

Not 100% sure if the problem is on abitype side?

Expected Behavior

return type to be readonly [number, number, 0x${string}, string][]

Link to Minimal Reproducible Example (TypeScript Playground)

not clear how to present reproducable example

Steps To Reproduce

No response

Anything else?

No response

Conflict with Typescript version

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

0.1.8-0.2.5

TypeScript Version

4.6.4

Current Behavior

Multiple errors in index.d.ts trying to compile.

node_modules/abitype/dist/index.d.ts:77:66 - error TS1005: '?' expected. components: infer TComponents extends readonly AbiParameter[];

Expected Behavior

Type definitions shouldn't cause errors even in a version behind the project. Considering @wagmi/core TS is 4.6.4 also.

Link to Minimal Reproducible Example (TypeScript Playground)

No response

Steps To Reproduce

Inside Package.json

"dependencies": {
    "abitype": "^0.1.8",
    "typescript": "^4.6.4"
  }

test.ts

import { Address } from 'abitype';

export const address: Address = '0x';

run: tsc test.ts

Anything else?

I'm running into this issue while working inside of an Angular project which can't upgrade to TS 4.7+ at this time. I'm unable to use the below package due to the shared dependency of abitype:

  • @web3modal/ethereum

typing issue with parseAbi(formatAbi(myABI)) : lost of types

Describe the bug

When formating an abi to human readable format and then parsing it, the types loses some of its field

In the example here the inputs and stateMutabilitiy field resolve to never

Link to Minimal Reproducible Example

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbwGbRAQxgQQEbADRxhpQDOApjsAL5xJQQhwDkauMAnmGUwNwBQfMgA9IsOAGMIAOxLxWwOAF44AbT4BIBBvXApYAK4wSALlXbN59ZPDSyUo6bXrnzrS5e6YZKFLQAbABVOMlMmfU8AJgBWADYmPEtnXxAQ5nEAC2I0cS8oAEkAEXjE9Q4uUPD7aLiE93UqWvc3Os9vX0Dgis8YgBZiuvVk1KYpMgB3AAUIEmAYYGl+urLhyphexZcGxOb3Vp9-IPLmVYi+xvch0JENl2WuqrPErbqdj3s2g87jyMeBy+YyJAMjdnHdvg8Qc8miU9u1DitPAAOEGDNApULpMAosFhJGQ86uErWSCjewmMwDCyUnTvfYdI5MTwAZgiKKSaOGQjZpS+jPsLLZUJeJWcsM+DOZrIJFw5oXY3JxksF0sJ1LF9IR9mRKvZ6OYmIVvNW2pFQuhatpcKNeJ1qL1TAA1roACaGhnG5UlAC6KvV8NCsig+hycAA4hyAEpkABuZH8ADoALLSWTeFRRL0o-5MEAp3IkbG8mD6MB+MjpzPSs1UurE2xkxwi167S3izUwE3U7O5mS5PJSZ3CCZ+fQkACMbvbnYG1dVlL91q13OzGB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Q-B91jVxT1wY1OObOjv23cNRMuNmToDpOd2IXUWXiR8Q1MLRsmRmFCbJr2aYZmtoQ9qmpCzaEgllhWr3CgMVVfeStVS-OZO4qRXZcYLfYDkOI7jrT5P0wre1Y4Ty5cQ+4ibtuBFvrBxHY-rdWG8z0OnreK4wGu5v4a+7668rGHg0hpNGy98OhDhMh4Zb3s25S7kU-UJOQ07duh9hZDgRHXuEb7Ls-uRvpK2z9Ec8xSlse7VklNmPEV8JAwWUJksuIzmPJwyRdhiXikqWpxn5aZwX2m5RaWXXV2NFlhleImhjyH4szsKEBihYsOJIPoUjOQstRbF6cBoCQEh5vwfCSL2++4JgSC5AAYqgGCYAOEzEOQSiEC-FC4AAFCgUDoFg395AAEogEn3kFfW+98sBPw-nAEgGBgAkCQMAXScBlgQCQBfYA-AgA

Package Version

1.04

TypeScript Version

5.5.2

Check existing issues

Anything else?

No response

Compilation issue with TypeScript 5.2.2

Describe the bug

I'm seeing the following compiler error when using TypeScript 5.2.2:

$ npx tsc
src/utils.ts:3:35 - error TS1479: The current file is a CommonJS module whose imports will produce 'require' calls; however, the referenced file is an ECMAScript module and cannot be imported with 'require'. Consider writing a dynamic 'import("abitype")' call instead.
  To convert this file to an ECMAScript module, change its file extension to '.mts' or create a local package.json file with `{ "type": "module" }`.

3 import type { AbiParameter } from 'abitype';
                                    ~~~~~~~~~

I have these settings in my tsconfig.json:

"module": "node16",
"moduleResolution": "node16",

I noticed that abitype publishes CommonJS files with a .js extension, even though in package.json it says "type": "module". Manually changing "type": "module" to "type": "commonjs" fixes the compiler error. This seems like an odd fix because ES modules are also published with a .js extension, however those are perhaps hardcoded to be interpreted as ES modules because they are reached through the explicit "import" entrypoints?

Link to Minimal Reproducible Example

The playground doesn't work with ES Modules.

Steps To Reproduce

No response

Package Version

0.10.1

I don't see the same issue with 0.9.10.

TypeScript Version

5.2.2

Anything else?

No response

Validations

bug: parseAbi throws type error

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

1.0.0

Current Behavior

The following code was copied directly from the docs and throws the following type errors:

  • "Type 'string' is not assignable to type 'string & [Error: Signature "${string}" is invalid at position 0.]'"
  • "Type 'string' is not assignable to type 'string & [Error: Signature "${string}" is invalid at position 1.]'"
parseAbi([`
  "function balanceOf(address owner) view returns (uint256)",
  "event Transfer(address indexed from, address indexed to, uint256 amount)",
]);

Screenshot_35

Expected Behavior

No type error

Steps To Reproduce

Copied directly from the docs here: https://viem.sh/docs/abi/parseAbi.html#usage

Note: Could not reproduce error on https://new.viem.sh with the same version, tsconfig, and code.

Link to Minimal Reproducible Example (StackBlitz, CodeSandbox, GitHub repo etc.)

No response

Anything else?

import { parseAbi, parseAbiItem } from "viem";

// Throws type error
parseAbi([
  "function balanceOf(address owner) view returns (uint256)",
  "event Transfer(address indexed from, address indexed to, uint256 amount)",
]);

// Doesn't throw type error
parseAbiItem("function balanceOf(address owner) view returns (uint256)");
parseAbiItem(
  "event Transfer(address indexed from, address indexed to, uint256 amount)"
);
// tsconfig.json
{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*", "botswarm.config.ts"]
}

parseAbi cached inputs/outputs problem

Describe the bug

Context

I work on a web app that is a rollups explorer to support users who are developing with Cartesi technology. That said, I am working on a UI to support the developers in defining a JSON abi using the human-readable format that they can use to decode standard abi-encoded data through our App.

Expected

As a user defining my function signatures and structs, if I have a struct as a function return or input parameter and come to change it (e.g. types, param-name or remove a parameter), I expect the generated JSON ABI to reflect these changes.

What is actually happening

It does not consider the change in the struct. It only reflects the update if I change something in the function signature, but if I come back to the same signature, let's say the original function param is Baz baz. After changes to the struct, nothing happens, so changing to Baz baz2 will reflect the change immediately, but then coming back to Baz baz will reflect the old component definitions in the generated ABI.

Link to Minimal Reproducible Example

https://rollups-explorer-sepolia-git-feature-165-add-dec-dd1128-cartesi.vercel.app/specifications/new

Steps To Reproduce

I added a link to the running application.

  1. Copy the signatures below in the ABI Textarea input and check the accordions below, i.e. ABI Signatures and JSON ABI Generated.
  2. Modify the struct, e.g. change the parameter name from amount to price and check the JSON ABI Generated accordion; nothing will have changed there.
  3. Change the function balanceOf parameter name from baz to baz2, then check the accordion; it should now change.
  4. Last, roll back the function parameter name to baz and check the accordion. The outdated tuple definition should be back.

Input data example:

function balanceOf(Baz baz)
struct Baz {uint amount; string role;}

Package Version

1.0.5 (through [email protected])

TypeScript Version

5.3.2

Check existing issues

Anything else?

After ruling out ui-libraries being responsible for any caching, I started looking into the parseAbi(). There is a seeded cache (Map()) that also adds information. However, it does not consider a change in the struct, so the cached data could be marked as stale and skipped to be overridden.

List of calls:

I believe these functions were not designed for prototyping and generating on-demand JSON abi through user input (my case) but rather statically defined in the application itself. So I have a couple of suggestions for a solution.

  1. In the uppermost layer, externalize a not-required Options object-like type for the parseAbi() just like parseAbiParameter. So, that becomes an opt-in situation that does not cause trouble for existing users. e.g. ts type Options = {noCache: boolean} that internally would bypass the caching as I notice some concern comments in the seeding for performance problems with increasing that map.
  2. Do not change the external API. Internally, recognise that important pieces of the cached data have changed and skip the cache read so it is overridden in the process. However, the nature of prototyping and generating on the fly may grow that cache Map.

bug: uint and uint256 parsed different in EIP-712 Typed Data event signatures

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

0.1.7

Current Behavior

This results in two different types ie. uint doesn't get coerced to uint256.

// works
  const logs = await client.getLogs({
    address: erc20Address,
    event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint256 value)'),
    fromBlock: 16790000n,
  })

//doesnt work (no results)
  const logs2 = await client.getLogs({
    address: erc20Address,
    event: parseAbiItem('event Transfer(address indexed from, address indexed to, uint value)'), // uint instead of uint256 here
    fromBlock: 16790000n,
  })

NOTE: Maybe this issue should be moved to abitype, i am not sure which library is responsible for ABI normalization.

Expected Behavior

Both queries works.

Steps To Reproduce

Just run the code stored above.

Link to Minimal Reproducible Example (StackBlitz, CodeSandbox, GitHub repo etc.)

https://stackblitz.com/edit/viem-getting-started-vwxiwl?file=index.ts

Anything else?

Sorry I couldn't create repro on stackblitz due to some random error. I think the problem is also that template new.viev.sh uses old viem version in package.json.

Anyway, great job on the library! I can't wait to use it more.

Noticeably slow type inference, especially when using `createTestClient` and `.extend`

Describe the bug

I am creating a test client with both public and wallet actions and what I expect is type inference to be relatively fast. What actually is happening is that on my M2 Ultra Max it takes 2s or more to load the client's properties and function arguments. I'd like to clarify that this isn't just using createTestClient().extend(), there are noticeably slow types in other places such as the wallet client itself but it's bearable.

Originally a discussion but after creating a reproduction and seeing that it can take over 5s (in some cases 10s), I figured it's worth an issue.

Link to Minimal Reproducible Example

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgYygUwIYzQFTQZxgGEAbYNAOxgBo4ALGGMWsAVwCMzkBBZGYCBXy0A7hhIk0MXv0H44AXzgAzKBBBwA5ADdyITQG4AUKEixEKiKwoATKAE9FKtRp16A9MjoZgQw0aNkOXhkMkp4AF4UdCxcAmIwqgAKBCM4FG9fAC5Lazt7ajS4EAgbNBzNDApdEk1C9JgoKvwzGByGJiSASkKFLqKAOjQAD2xbJLZOYB4+ASF+9KHRyhsksQkpGTn8LuMjd3c4AGUYDHMYezBfAHM4AANQ8ioBu7gB97gqmzhGx1Z8G6fCiOZTWWaCOAiYAwOifKDXfADIxAA

Steps To Reproduce

Stackblitz reproduction (10s slow types): https://stackblitz.com/edit/stackblitz-starters-bdo9jm?file=index.ts

Package Version

^2.12.5

TypeScript Version

^5.4.5

Check existing issues

Anything else?

No response

bug: type inference won't work when `constructor` has no `stateMutability` property

Is there an existing issue for this?

  • I have searched the existing issues

Package Version

0.6.8

TypeScript Version

4.9.4

Current Behavior

Type inference won't work when constructor in abi has no stateMutability:

[
    {
      type: 'constructor',
      inputs: [
        { type: 'address', name: 'token_addr' },
        { type: 'address', name: 'art_proxy' },
      ],
    },
    {
      name: 'balanceOf',
      type: 'function',
      stateMutability: 'view',
      inputs: [{ name: 'account', type: 'address' }],
      outputs: [{ type: 'uint256' }],
    },
    {
      name: 'totalSupply',
      type: 'function',
      stateMutability: 'view',
      inputs: [],
      outputs: [{ type: 'uint256' }],
    },
    {
      name: 'transfer',
      type: 'function',
      stateMutability: 'nonpayable',
      inputs: [
        { name: 'recipient', type: 'address' },
        { name: 'tokenId', type: 'uint256' },
      ],
      outputs: [{ type: 'bool' }],
    },
  ]

CleanShot 2023-03-09 at 19 32 07@2x

Expected Behavior

I would expect type inference functioning well in the above case as stateMutability isn't a required field per https://docs.soliditylang.org/en/v0.8.15/abi-spec.html#json

CleanShot 2023-03-09 at 19 33 40@2x

Link to Minimal Reproducible Example (TypeScript Playground)

https://viem.sh/docs/typescript.html#contract-abis

Steps To Reproduce

  1. copy the code here https://viem.sh/docs/typescript.html#contract-abis
  2. add below code to abi:
  {
      type: 'constructor',
      inputs: [
        { type: 'address', name: 'token_addr' },
        { type: 'address', name: 'art_proxy' },
      ],
    },
  1. check types of functionName

Anything else?

I believe this can be fixed by changing stateMutability of constructor to optional.

TS build error: instantiation is excessively deep

Describe the bug

Building with Typescript 5 fails with the following error:

/node_modules/abitype/dist/types/human-readable/formatAbiParameter.d.ts(19,15): error TS2589: Type instantiation is excessively deep and possibly infinite.

Link to Minimal Reproducible Example

https://codesandbox.io/p/sandbox/infallible-chatelet-98xg5y?file=%2F.codesandbox%2Fworkspace.json%3A1%2C1

Steps To Reproduce

Build with typescript (e.g. yarn tsc)

Package Version

0.8.11

TypeScript Version

5.1.6

Anything else?

This error arose sometime between v0.8.7 and v0.8.11. I know that because Viem 1.2.2 builds fine but Viem 1.2.3+ fails. See https://github.com/wagmi-dev/viem/pull/802/files

Validations

test issue ci workflow

Describe the bug

Just testing out the new CI workflow for issue labeling.

Link to Minimal Reproducible Example

No response

Steps To Reproduce

No response

Package Version

0.7.1

TypeScript Version

4.9.5

Anything else?

No response

Validations

`FormatAbiParameter` infers incorrect string on nested unnamed `components`

Describe the bug

Found this bug completely by chance while working on something else.

This will only happen if the parameter has unnamed nested components and is of type tuple.

Example:

const param = {
  readonly components: [
    {
      readonly components: [
        {
          readonly type: 'string'
          readonly name: 'foo'
        },
      ]
      readonly type: 'tuple'
    },
  ]
  readonly type: 'tuple'
}

This will result in a type of '(tuple)' instead of the desired ((string)).

Link to Minimal Reproducible Example

https://tsplay.dev/weaGEw

Steps To Reproduce

No response

Package Version

0.9.3

TypeScript Version

5.0.4

Anything else?

No response

Validations

Identifiers with `$` are not recognized

Describe the bug

Minimum code to reproduce the issue:

import { parseAbi } from 'abitype';

const abi = [
  'function _()',
  'function $()',
  'function $_()',
  'function $_a9()',
  'function a9$_()'
];

const result = parseAbi(abi);

Expected result: ABI is parsed successfully.

Actual result: UnknownSignatureError is thrown:

node_modules\abitype\src\human-readable\runtime\utils.ts:148
  throw new UnknownSignatureError({ signature })
        ^
UnknownSignatureError: Unknown signature.

I believe the issue is with the regex to match the function name (functionSignatureRegex in /src/human-readable/runtime/signatures.ts):

const functionSignatureRegex =
  /^function (?<name>[a-zA-Z0-9_]+)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/

From the Solidity docs, the regex to match a valid identifier is: [a-zA-Z$_][a-zA-Z0-9$_]*. So it should be a quick fix:

-  /^function (?<name>[a-zA-Z0-9_]+)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/
+  /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/

I only tested functions, but events, errors, structs, etc. all use the same identifier logic so those regexes should be updated too.

Also wanted to note this ABI works in ethers as expected:

const abi = [
  'function _()',
  'function $()',
  'function $_()',
  'function $_a9()',
  'function a9$_()'
];
const ethers = await import('https://cdn.jsdelivr.net/npm/[email protected]/+esm');
const interface = new ethers.Interface(abi);
interface.getFunction('$').selector;
// '0xf461e06a'

Lastly for reference, I was able to successfully deploy a smart contract on Sepolia using these identifiers and uploaded it to Etherscan: https://sepolia.etherscan.io/address/0x8ae917bd7ba1bc35ebf7ef1e6ff815565647ab9a#code

Link to Minimal Reproducible Example

No response

Steps To Reproduce

No response

Package Version

0.9.0

TypeScript Version

5.1.6

Anything else?

No response

Validations

`(encode|parse)AbiParameters` detects types correctly when passed as string but not array

Describe the bug

This doesn't work:

encodeAbiParameters(parseAbiParameters(["(uint256 a)", "(uint256 b)"]), [
	{ a: BigInt(1) },
	{ b: BigInt(1) },
])

Error: Source has 2 element(s) but target allows only 1

This works:

encodeAbiParameters(parseAbiParameters(["(uint256 a),(uint256 b)"]), [
	{ a: BigInt(1) },
	{ b: BigInt(1) },
])

Sorry, in case there has been a misconception from my side :)

Cheers, Dennis

Link to Minimal Reproducible Example

No response

Steps To Reproduce

No response

Package Version

1.0.0 (installed by [email protected])

TypeScript Version

5.3.2

Anything else?

No response

Validations

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.