Skip to content

0x v2 - #737

Merged
Dargon789 merged 7 commits into
v-3from
0x-v2
Aug 14, 2026
Merged

0x v2#737
Dargon789 merged 7 commits into
v-3from
0x-v2

Conversation

@Dargon789

@Dargon789 Dargon789 commented Aug 13, 2026

Copy link
Copy Markdown
Owner

Summary by Sourcery

Add shared precondition types and encoding utilities to the relayer and API services, integrating them with the generated RPC API and relayer package.

New Features:

  • Introduce typed precondition model in the relayer covering native balance, ERC-20/721/1155 balances, ownership, and approvals.
  • Expose precondition type and helper functions from the API service client, including chain-aware encoding for RPC payloads.

Enhancements:

  • Update the API client to extend the regenerated proto API surface and re-export its definitions for consumers.
  • Relax API client header typing to support richer request metadata.

@codesandbox

codesandbox Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

@bolt-new-by-stackblitz

Copy link
Copy Markdown

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@vercel

vercel Bot commented Aug 13, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
sequence-js-docs Ready Ready Preview Aug 13, 2026 8:02am
sequence-js-web Ready Ready Preview Aug 13, 2026 8:02am
sequence.js Ready Ready Preview Aug 13, 2026 8:02am
wagmi-project Building Building Preview Aug 13, 2026 8:02am

@sourcery-ai

sourcery-ai Bot commented Aug 13, 2026

Copy link
Copy Markdown

Reviewer's Guide

Introduces a typed precondition encoding/validation layer for the relayer, wires it into the API client, and adjusts exports and headers to support the new 0x v2 precondition protocol.

Sequence diagram for encoding 0x v2 preconditions in the API client

sequenceDiagram
  actor Dapp
  participant SequenceAPIClient
  participant RelayerPrecondition as encodeChainPrecondition
  participant Ethers as ethers

  Dapp->>SequenceAPIClient: encodePrecondition(precondition)
  SequenceAPIClient->>RelayerPrecondition: encodeChainPrecondition(precondition)
  RelayerPrecondition-->>SequenceAPIClient: { type, precondition: args }
  SequenceAPIClient->>Ethers: ethers.toBigInt(precondition.chainId)
  Ethers-->>SequenceAPIClient: chainIdBigInt
  SequenceAPIClient-->>Dapp: proto.Precondition { type, chainID, precondition: args }
Loading

File-Level Changes

Change Details Files
Wire the generated proto API and relayer precondition helpers into the SequenceAPIClient and expose new precondition utilities from the API package.
  • Switch SequenceAPIClient base class from the named API import to the proto.API namespace import from ./api.gen
  • Import ChainPrecondition helpers from @0xsequence/relayer and ethers for BigNumberish handling
  • Relax internal fetch header typing from string-only to an index signature with any values to allow richer headers
  • Re-export all symbols from ./api.gen after the client class definition
  • Add a Precondition type that composes chainId with ChainPrecondition and corresponding isPrecondition type guard
  • Add encodePrecondition helper that adapts relayer preconditions to proto.Precondition, including chainId encoding and removal from args
  • Add internal isBigNumberish and encodeBigNumberish helpers using ethers.toBigInt for validation and string encoding
packages/services/api/src/index.ts
Add a dedicated relayer precondition module that defines all supported precondition variants, their runtime type guards, and encoding logic into the relayer protobuf protocol.
  • Define a discriminated union Precondition type covering native balance, ERC20 balance/approval, ERC721 ownership/approval, and ERC1155 balance/approval
  • Implement isPrecondition dispatcher that checks against specific type-guard predicates for each precondition variant
  • For each precondition variant, add a strongly-typed shape, an isXxxPrecondition validator leveraging ethers.isAddress and BigNumberish checks, and an encodeXxxPrecondition that converts values into proto.Precondition with type stripped from payload
  • Ensure numeric fields (min, max, tokenId) are validated/encoded via shared isBigNumberish and encodeBigNumberish helpers
  • Normalize boolean owned flag in ERC721 ownership encoding so undefined/true map to true and false is preserved
packages/relayer/src/precondition.ts
Update dependency lockfile to reflect new/updated 0x v2 and related packages.
  • Adjust pnpm-lock.yaml entries to account for the new relayer precondition module and its dependencies (e.g., ethers, @0xsequence/relayer, updated proto definitions)
pnpm-lock.yaml

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@snyk-io

snyk-io Bot commented Aug 13, 2026

Copy link
Copy Markdown

Snyk checks have passed. No issues have been found so far.

Status Scan Engine Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues
Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 3 issues, and left some high level feedback:

  • In SequenceAPIClient._fetch the headers type was relaxed to { [key: string]: any }; since fetch expects header values as strings, consider keeping this as Record<string, string> (or Record<string, string | undefined>) to avoid accidentally passing non-string values.
  • In encodePrecondition (API client) you mutate args with delete args.chainId after calling encodeChainPrecondition; to avoid unintended side effects, consider building the payload via destructuring/omission rather than deleting properties on an object returned from another function.
  • The generic typing of encodeBigNumberish (both in relayer and API client) relies on as any when returning undefined; simplifying the function to return string | undefined (and updating call sites accordingly) would make the type behavior clearer and remove the need for unsafe casts.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `SequenceAPIClient._fetch` the `headers` type was relaxed to `{ [key: string]: any }`; since `fetch` expects header values as strings, consider keeping this as `Record<string, string>` (or `Record<string, string | undefined>`) to avoid accidentally passing non-string values.
- In `encodePrecondition` (API client) you mutate `args` with `delete args.chainId` after calling `encodeChainPrecondition`; to avoid unintended side effects, consider building the payload via destructuring/omission rather than deleting properties on an object returned from another function.
- The generic typing of `encodeBigNumberish` (both in relayer and API client) relies on `as any` when returning `undefined`; simplifying the function to return `string | undefined` (and updating call sites accordingly) would make the type behavior clearer and remove the need for unsafe casts.

## Individual Comments

### Comment 1
<location path="packages/services/api/src/index.ts" line_range="23" />
<code_context>
     // automatically include jwt and access key auth header to requests
     // if its been set on the api client
-    const headers: Record<string, string> = {}
+    const headers: { [key: string]: any } = {}

     const jwtAuth = this.jwtAuth
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Avoid using `any` for headers to preserve type safety and alignment with `fetch` expectations.

Changing `headers` to `{ [key: string]: any }` removes guarantees that values are strings and can allow invalid header values, which may break compatibility with `HeadersInit` in the Fetch API and cause runtime errors. If you need conditional or flexible headers, prefer `Record<string, string>` or `HeadersInit` and convert values to strings when assigning them.

Suggested implementation:

```typescript
    // automatically include jwt and access key auth header to requests
    // if its been set on the api client
    const headers: Record<string, string> = {}

```

1. Wherever `headers` is populated later in this method, ensure all assigned values are explicitly converted to strings (e.g. `headers['Authorization'] = String(jwtAuth)`).
2. When invoking `fetch`, make sure these headers are actually used by merging into `init` (e.g. `fetch(input, { ...(init || {}), headers: { ...(init?.headers || {}), ...headers } })`), preserving existing headers.
3. If `init.headers` may be a `Headers` object or array form, you may need a small helper to normalize it to `Record<string, string>` before merging, to stay compatible with `HeadersInit`.
</issue_to_address>

### Comment 2
<location path="packages/relayer/src/precondition.ts" line_range="270-274" />
<code_context>
+  }
+}
+
+function encodeBigNumberish<T extends ethers.BigNumberish | undefined>(
+  value: T
+): T extends ethers.BigNumberish ? string : undefined {
+  return value !== undefined ? ethers.toBigInt(value).toString() : (undefined as any)
+}
</code_context>
<issue_to_address>
**suggestion:** The generic conditional type on `encodeBigNumberish` doesn’t match the implementation and relies on an unsafe cast.

The generic return type doesn’t match the actual behavior: the function always returns `string | undefined`, but forces the type system with `(undefined as any)`. This undermines type safety and can mislead callers about the result type. Consider changing the signature to `(value: ethers.BigNumberish | undefined) => string | undefined`, or, if you need conditional typing, using proper overloads instead of a generic whose implementation doesn’t conform to its declaration.

```suggestion
function encodeBigNumberish(value: ethers.BigNumberish | undefined): string | undefined {
  return value !== undefined ? ethers.toBigInt(value).toString() : undefined
}
```
</issue_to_address>

### Comment 3
<location path="packages/relayer/src/precondition.ts" line_range="14" />
<code_context>
+  | Erc1155BalancePrecondition
+  | Erc1155ApprovalPrecondition
+
+export function isPrecondition(precondition: any): precondition is Precondition {
+  return [
+    isNativeBalancePrecondition,
</code_context>
<issue_to_address>
**issue (complexity):** Consider introducing a config-driven handler map and shared helpers so that all precondition validation and encoding logic is centralized instead of repeated per type.

The repetition in the `isXPrecondition` / `encodeXPrecondition` functions and the manual dispatch can be reduced with a small config‑driven layer while keeping behavior unchanged.

You can introduce a central handler map that encapsulates validation and encoding per `type`, and then implement `isPrecondition`/`encodePrecondition` in terms of that map:

```ts
type PreconditionType =
  | 'native-balance'
  | 'erc20-balance'
  | 'erc20-approval'
  | 'erc721-ownership'
  | 'erc721-approval'
  | 'erc1155-balance'
  | 'erc1155-approval'

type NativeBalancePrecondition = {
  type: 'native-balance'
  address: `0x${string}`
  min?: ethers.BigNumberish
  max?: ethers.BigNumberish
}

// ...other specific precondition types

type AnyPrecondition =
  | NativeBalancePrecondition
  | Erc20BalancePrecondition
  | Erc20ApprovalPrecondition
  | Erc721OwnershipPrecondition
  | Erc721ApprovalPrecondition
  | Erc1155BalancePrecondition
  | Erc1155ApprovalPrecondition

type PreconditionHandler<P extends AnyPrecondition> = {
  is: (value: any) => value is P
  encode: (p: P) => proto.Precondition
}

const preconditionHandlers: Record<PreconditionType, PreconditionHandler<any>> = {
  'native-balance': {
    is(value: any): value is NativeBalancePrecondition {
      return (
        typeof value === 'object' &&
        value &&
        value.type === 'native-balance' &&
        ethers.isAddress(value.address) &&
        (value.min === undefined || isBigNumberish(value.min)) &&
        (value.max === undefined || isBigNumberish(value.max))
      )
    },
    encode(precondition: NativeBalancePrecondition): proto.Precondition {
      return {
        type: precondition.type,
        precondition: {
          ...precondition,
          type: undefined,
          min: encodeBigNumberish(precondition.min),
          max: encodeBigNumberish(precondition.max),
        },
      }
    },
  },
  // ...same pattern for other types
}

export function isPrecondition(precondition: any): precondition is AnyPrecondition {
  return (
    typeof precondition === 'object' &&
    precondition &&
    typeof precondition.type === 'string' &&
    precondition.type in preconditionHandlers &&
    preconditionHandlers[precondition.type as PreconditionType].is(precondition)
  )
}

export function encodePrecondition(precondition: AnyPrecondition): proto.Precondition {
  const handler = preconditionHandlers[precondition.type]
  if (!handler) throw new Error('unreachable')
  return handler.encode(precondition as any)
}
```

For the repetitive encoding shapes, a small generic `encodeWithConfig` helper can reduce boilerplate while preserving the per‑field behavior:

```ts
type EncodeConfig<T> = {
  bigNumberishFields?: (keyof T)[]
  booleanDefaults?: Partial<Record<keyof T, boolean>>
}

function encodeWithConfig<T extends { type: PreconditionType }>(
  precondition: T,
  config: EncodeConfig<T>
): proto.Precondition {
  const encoded: any = { ...precondition, type: undefined }

  for (const field of config.bigNumberishFields ?? []) {
    encoded[field] = encodeBigNumberish(precondition[field] as any)
  }

  for (const [field, defaultValue] of Object.entries(config.booleanDefaults ?? {})) {
    const key = field as keyof T
    encoded[key] = precondition[key] === undefined ? defaultValue : precondition[key]
  }

  return { type: precondition.type, precondition: encoded }
}

// Usage example:
function encodeErc721OwnershipPrecondition(
  precondition: Erc721OwnershipPrecondition
): proto.Precondition {
  return encodeWithConfig(precondition, {
    bigNumberishFields: ['tokenId'],
    booleanDefaults: { owned: true },
  })
}
```

Finally, since `isBigNumberish` / `encodeBigNumberish` exist elsewhere, pulling them into a shared utility (e.g. `bigNumberish.ts`) and reusing them here will reduce duplication:

```ts
// bigNumberish.ts
export function isBigNumberish(value: any): value is ethers.BigNumberish {
  try {
    ethers.toBigInt(value)
    return true
  } catch {
    return false
  }
}

export function encodeBigNumberish<T extends ethers.BigNumberish | undefined>(
  value: T
): T extends ethers.BigNumberish ? string : undefined {
  return value !== undefined ? ethers.toBigInt(value).toString() : (undefined as any)
}

// current file
import { isBigNumberish, encodeBigNumberish } from '../utils/bigNumberish'
```

These changes keep the current functionality and type safety but collapse the repetitive patterns into a smaller, easier‑to‑extend surface.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread packages/services/api/src/index.ts
Comment thread packages/relayer/src/precondition.ts Outdated
Comment thread packages/relayer/src/precondition.ts
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
Signed-off-by: Dargon789 <64915515+Dargon789@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants