Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(human-readable): parameter validation and strict mode #138

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,17 +151,17 @@ declare module 'abitype' {
}
```

### `StrictAbiType`
### `Strict`

When set, validates `AbiParameter`'s `type` against `AbiType`.
When set, validates `AbiParameter`'s `type` against `AbiType` and enforces stricter checks on human readable ABIs.

- Type `boolean`
- Default `false`

```ts twoslash
declare module 'abitype' {
export interface Config {
StrictAbiType: false
Strict: false
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this change it will affect type checking not only on types but also valid modifiers and parameter names. Kept as default so folks can hop in instead of out.

}
}
```
Expand Down
19 changes: 17 additions & 2 deletions src/abi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ export type AbiType =
| SolidityInt
| SolidityString
| SolidityTuple
type ResolvedAbiType = ResolvedConfig['StrictAbiType'] extends true
? AbiType
type ResolvedAbiType = ResolvedConfig['Strict'] extends true
? AbiType & string
: string

export type AbiInternalType =
Expand All @@ -95,6 +95,21 @@ export type AbiInternalType =
| `enum ${string}`
| `struct ${string}`

export type InferredAbiParameter = Prettify<
{
type: string
name?: string | undefined
/** Representation used by Solidity compiler */
internalType?: string | undefined
} & (
| { type: string }
| {
type: string
components: readonly InferredAbiParameter[]
}
)
>

export type AbiParameter = Prettify<
{
type: ResolvedAbiType
Expand Down
8 changes: 4 additions & 4 deletions src/config.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { assertType, test } from 'vitest'
import type { ResolvedConfig } from './config.js'

// For testing updates to config properties:
// declare module './config' {
// declare module './config.js' {
// export interface Config {
// FixedArrayMaxLength: 6
// Strict: true
// }
// }

Expand All @@ -29,6 +29,6 @@ test('Config', () => {
type BigIntType = ResolvedConfig['BigIntType']
assertType<BigIntType>(123n)

type StrictAbiType = ResolvedConfig['StrictAbiType']
assertType<StrictAbiType>(false)
type Strict = ResolvedConfig['Strict']
assertType<Strict>(false)
})
14 changes: 7 additions & 7 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ export interface DefaultConfig {
/** TypeScript type to use for `int<M>` and `uint<M>` values, where `M <= 48` */
IntType: number

/** When set, validates {@link AbiParameter}'s `type` against {@link AbiType} */
StrictAbiType: false
/** When set, validates {@link AbiParameter}'s `type` against {@link AbiType} and enforces stricter checks on human readable ABIs */
Strict: false
}

/**
Expand Down Expand Up @@ -110,14 +110,14 @@ export interface ResolvedConfig {
: Config['IntType']

/**
* When set, validates {@link AbiParameter}'s `type` against {@link AbiType}
* When set, validates {@link AbiParameter}'s `type` against {@link AbiType} and enforces stricter checks on human readable ABIs
*
* Note: You probably only want to set this to `true` if parsed types are returning as `unknown`
* and you want to figure out why.
* and you want to figure out why or if you want stricter validation on your types.
*
* @default false
*/
StrictAbiType: Config['StrictAbiType'] extends true
? Config['StrictAbiType']
: DefaultConfig['StrictAbiType']
Strict: Config['Strict'] extends true
? Config['Strict']
: DefaultConfig['Strict']
}
4 changes: 2 additions & 2 deletions src/human-readable/errors/abiParameter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,15 @@ test('InvalidFunctionModifierError', () => {
test('InvalidAbiTypeParameterError', () => {
expect(
new InvalidAbiTypeParameterError({
abiParameter: { type: 'addres' },
abiParameter: { type: 'address' },
}),
).toMatchInlineSnapshot(`
[InvalidAbiTypeParameterError: Invalid ABI parameter.

ABI parameter type is invalid.

Details: {
"type": "addres"
"type": "address"
}
Version: [email protected]]
`)
Expand Down
4 changes: 4 additions & 0 deletions src/human-readable/parseAbiParameter.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ test('ParseAbiParameter', () => {
test('parseAbiParameter', () => {
// @ts-expect-error empty array not allowed
expectTypeOf(parseAbiParameter([])).toEqualTypeOf<never>()
expectTypeOf(
// @ts-expect-error no valid struct arguments
parseAbiParameter(['address owner', 'struct Foo { string name; }']),
).toEqualTypeOf<never>()
expectTypeOf(
parseAbiParameter(['struct Foo { string name; }']),
).toEqualTypeOf<never>()
Expand Down
57 changes: 41 additions & 16 deletions src/human-readable/parseAbiParameter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { AbiParameter } from '../abi.js'
import type { Narrow } from '../narrow.js'
import type { Error, Filter } from '../types.js'
import type { Error, Filter, IsEmptyObject } from '../types.js'
import { InvalidAbiParameterError } from './errors/index.js'
import {
isStructSignature,
Expand All @@ -15,6 +15,23 @@ import type {
ParseStructs,
} from './types/index.js'

export type ValidateAbiParameter<TParams extends readonly string[]> =
ParseStructs<TParams> extends infer ParsedStructs extends object
? IsEmptyObject<ParsedStructs> extends true
? Error<'No Struct signature found. Please provide valid struct signatures.'>
: {
[K in keyof TParams]: IsStructSignature<TParams[K]> extends true
? never
: TParams[K] extends `${infer Type} ${string}`
? Type extends keyof ParsedStructs
? never
: Error<`Invalid Parameter "${TParams[K]}". Only Struct parameters are allowed`>
: TParams[K] extends keyof ParsedStructs
? never
: Error<`Invalid Parameter "${TParams[K]}". Only Struct parameters are allowed`>
}
: unknown

/**
* Parses human-readable ABI parameter into {@link AbiParameter}
*
Expand Down Expand Up @@ -44,21 +61,25 @@ export type ParseAbiParameter<
| (TParam extends readonly string[]
? string[] extends TParam
? AbiParameter // Return generic AbiParameter item since type was no inferrable
: ParseStructs<TParam> extends infer Structs
? {
[K in keyof TParam]: TParam[K] extends string
? IsStructSignature<TParam[K]> extends true
? never
: ParseAbiParameter_<
TParam[K],
{ Modifier: Modifier; Structs: Structs }
>
: ValidateAbiParameter<TParam> extends infer Validated
? Validated extends never[]
? ParseStructs<TParam> extends infer Structs
? {
[K in keyof TParam]: TParam[K] extends string
? IsStructSignature<TParam[K]> extends true
? never
: ParseAbiParameter_<
TParam[K],
{ Modifier: Modifier; Structs: Structs }
>
: never
} extends infer Mapped extends readonly unknown[]
? Filter<Mapped, never>[0] extends infer Result
? Result extends undefined
? never
: Result
: never
: never
} extends infer Mapped extends readonly unknown[]
? Filter<Mapped, never>[0] extends infer Result
? Result extends undefined
? never
: Result
: never
: never
: never
Expand Down Expand Up @@ -96,7 +117,11 @@ export function parseAbiParameter<
? Error<'At least one parameter required.'>
: string[] extends TParam
? unknown
: unknown // TODO: Validate param string
: ValidateAbiParameter<TParam> extends infer ValidatedParams extends readonly unknown[]
? ValidatedParams extends never[]
? unknown
: ValidatedParams
: never
: never)
),
): ParseAbiParameter<TParam> {
Expand Down
1 change: 1 addition & 0 deletions src/human-readable/parseAbiParameters.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ test('parseAbiParameters', () => {
// @ts-expect-error empty array not allowed
expectTypeOf(parseAbiParameters([])).toEqualTypeOf<never>()
expectTypeOf(
// @ts-expect-error invalid no parameter given
parseAbiParameters(['struct Foo { string name; }']),
).toEqualTypeOf<never>()

Expand Down
1 change: 1 addition & 0 deletions src/human-readable/parseAbiParameters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ test('parseAbiParameters', () => {
`,
)
expect(() =>
// @ts-expect-error invalid no parameter given
parseAbiParameters(['struct Foo { string name; }']),
).toThrowErrorMatchingInlineSnapshot(
`
Expand Down
15 changes: 13 additions & 2 deletions src/human-readable/parseAbiParameters.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { AbiParameter } from '../abi.js'
import type { Narrow } from '../narrow.js'
import type { Error, Filter } from '../types.js'
import type { Error, Filter, Flatten } from '../types.js'
import type { ExtractAbiParseErrors } from '../utils.js'
import { InvalidAbiParametersError } from './errors/index.js'
import {
isStructSignature,
Expand All @@ -17,6 +18,10 @@ import type {
SplitParameters,
} from './types/index.js'

export type ValidateAbiParameters<T extends readonly string[]> =
ParseAbiParameters<T> extends infer ParsedParams extends readonly unknown[]
? Flatten<ExtractAbiParseErrors<ParsedParams>>
: never
/**
* Parses human-readable ABI parameters into {@link AbiParameter}s
*
Expand Down Expand Up @@ -98,7 +103,13 @@ export function parseAbiParameters<
? Error<'At least one parameter required.'>
: string[] extends TParams
? unknown
: unknown // TODO: Validate param string
: ValidateAbiParameters<TParams> extends infer Parsed
? Parsed extends readonly []
? unknown
: Parsed extends readonly string[]
? Parsed[number]
: Parsed
: never
: never)
),
): ParseAbiParameters<TParams> {
Expand Down
3 changes: 2 additions & 1 deletion src/human-readable/types/signatures.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { AbiStateMutability } from '../../abi.js'
import type { ResolvedConfig } from '../../config.js'
import type { Error } from '../../types.js'

export type ErrorSignature<
Expand Down Expand Up @@ -128,7 +129,7 @@ export type IsName<TName extends string> = TName extends ''
: false
export type ValidateName<
TName extends string,
CheckCharacters extends boolean = false,
CheckCharacters extends boolean = ResolvedConfig['Strict'],
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This now gets enabled once folks enable strict mode instead of always being false.

> = TName extends `${string}${' '}${string}`
? Error<`Name "${TName}" cannot contain whitespace.`>
: IsSolidityKeyword<TName> extends true
Expand Down
15 changes: 9 additions & 6 deletions src/human-readable/types/structs.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import type { AbiParameter } from '../../abi.js'
import type { InferredAbiParameter } from '../../abi.js'
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Had to change this to InferredAbiParameter because while parsing structs with StrictAbiType = true it would cause some components to be never.

import type { Error, Trim } from '../../types.js'
import type { StructSignature } from './signatures.js'
import type { ParseAbiParameter } from './utils.js'

export type StructLookup = Record<string, readonly AbiParameter[]>
export type StructLookup = Record<string, readonly InferredAbiParameter[]>

export type ParseStructs<TSignatures extends readonly string[]> =
// Create "shallow" version of each struct (and filter out non-structs or invalid structs)
Expand All @@ -16,7 +16,7 @@ export type ParseStructs<TSignatures extends readonly string[]> =
: never]: ParseStruct<Signature>['components']
} extends infer Structs extends Record<
string,
readonly (AbiParameter & { type: string })[]
readonly (InferredAbiParameter & { type: string })[]
>
? // Resolve nested structs inside each struct
{
Expand All @@ -38,8 +38,11 @@ export type ParseStruct<
: never

export type ResolveStructs<
TAbiParameters extends readonly (AbiParameter & { type: string })[],
TStructs extends Record<string, readonly (AbiParameter & { type: string })[]>,
TAbiParameters extends readonly (InferredAbiParameter & { type: string })[],
TStructs extends Record<
string,
readonly (InferredAbiParameter & { type: string })[]
>,
TKeyReferences extends { [_: string]: unknown } | unknown = unknown,
> = readonly [
...{
Expand Down Expand Up @@ -82,6 +85,6 @@ export type ParseStructProperties<
? ParseStructProperties<
Tail,
TStructs,
[...Result, ParseAbiParameter<Head, { Structs: TStructs }>]
[...Result, ParseAbiParameter<Head, { Structs: TStructs; Strict: false }>]
>
: Result
Loading