Conversation
Review or Edit in CodeSandboxOpen the branch in Web Editor • VS Code • Insiders |
|
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Reviewer's GuideIntroduces 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 clientsequenceDiagram
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 }
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
There was a problem hiding this comment.
Hey - I've found 3 issues, and left some high level feedback:
- In
SequenceAPIClient._fetchtheheaderstype was relaxed to{ [key: string]: any }; sincefetchexpects header values as strings, consider keeping this asRecord<string, string>(orRecord<string, string | undefined>) to avoid accidentally passing non-string values. - In
encodePrecondition(API client) you mutateargswithdelete args.chainIdafter callingencodeChainPrecondition; 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 onas anywhen returningundefined; simplifying the function to returnstring | 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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com> Signed-off-by: Dargon789 <64915515+Dargon789@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
Enhancements: