-
Notifications
You must be signed in to change notification settings - Fork 619
[SDK] Refactor payment processing to use facilitator.accepts #8344
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
[SDK] Refactor payment processing to use facilitator.accepts #8344
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
How to use the Graphite Merge QueueAdd either label to this PR to merge it via the merge queue:
You must have a Graphite account in order to use the merge queue. Sign up using this link. An organization admin has enabled the Graphite Merge Queue in this repository. Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue. This stack of pull requests is managed by Graphite. Learn more about stacking. |
WalkthroughReworks x402 payment handling to delegate requirement discovery to a new facilitator.accepts endpoint and switches chain ID handling to CAIP‑2 with utilities to extract EVM chain IDs; removes legacy atomic-amount/asset helpers and inlined payment-construction logic. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant DecodeFlow
participant Facilitator
participant PaymentService
Client->>DecodeFlow: request payment decode (contains network)
DecodeFlow->>Facilitator: accepts(args without facilitator)
Facilitator->>PaymentService: POST /accepts (PaymentArgs)
PaymentService-->>Facilitator: PaymentRequiredResult (status, headers, body)
Facilitator-->>DecodeFlow: return PaymentRequiredResult
DecodeFlow-->>Client: forward payment requirements
opt CAIP‑2 resolution (internal)
DecodeFlow->>DecodeFlow: networkToCaip2ChainId -> extractEvmChainId
end
note right of Facilitator: New: delegate requirement derivation to facilitator.accepts\nRemoved: inline atomic-amount/asset processing in decode flow
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Comment |
size-limit report 📦
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/thirdweb/src/x402/schemas.ts (1)
127-198: Add TSDoc with @example/@internal for new public exports.Per the package guideline, every public symbol in
packages/thirdwebneeds full TSDoc with an example and a custom tag. Please add it forisSolanaChain,isEvmChain,isZkSyncChain,extractEvmChainId,Caip2ChainIdSchema, andnetworkToCaip2ChainId. As per coding guidelines
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/thirdweb/src/x402/common.ts(3 hunks)packages/thirdweb/src/x402/facilitator.ts(3 hunks)packages/thirdweb/src/x402/fetchWithPayment.ts(3 hunks)packages/thirdweb/src/x402/schemas.ts(1 hunks)packages/thirdweb/src/x402/sign.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size
Files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)
Files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
packages/thirdweb/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling@exampleand a custom tag (@beta,@internal,@experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g.,const { jsPDF } = await import("jspdf"))
Files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
🧠 Learnings (9)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
Applied to files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The SignTransactionInput schema in thirdweb-dev/ai-sdk-provider uses snake_case field names (chain_id) rather than camelCase (chainId).
Applied to files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to **/*.test.{ts,tsx} : Use `FORKED_ETHEREUM_CHAIN` for mainnet interactions and `ANVIL_CHAIN` for isolated tests
Applied to files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-06-03T23:44:40.243Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7268
File: packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts:210-216
Timestamp: 2025-06-03T23:44:40.243Z
Learning: EIP7702 wallets do not need special handling for switching chains, unlike EIP4337 wallets which require reconnection when switching chains. In the switchChain method condition, EIP7702 should be intentionally excluded from the reconnection logic.
Applied to files:
packages/thirdweb/src/x402/sign.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Unified `Wallet` and `Account` interfaces in wallet architecture
Applied to files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/extensions/** : Auto-generated contracts from ABI definitions in extensions
Applied to files:
packages/thirdweb/src/x402/common.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The thirdweb-dev/ai-sdk-provider schemas use snake_case field naming convention (e.g., chain_id, transaction_hash) rather than camelCase, as defined in the zod schemas in packages/ai-sdk-provider/src/tools.ts.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.tspackages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-05-30T17:14:25.332Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 7227
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/modules/components/OpenEditionMetadata.tsx:26-26
Timestamp: 2025-05-30T17:14:25.332Z
Learning: The ModuleCardUIProps interface already includes a client prop of type ThirdwebClient, so when components use `Omit<ModuleCardUIProps, "children" | "updateButton">`, they inherit the client prop without needing to add it explicitly.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-06-06T23:46:08.795Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:424-424
Timestamp: 2025-06-06T23:46:08.795Z
Learning: The thirdweb project has an ESLint rule that restricts direct usage of `defineChain`. When it's necessary to use `defineChain` directly, it's acceptable to disable the rule with `// eslint-disable-next-line no-restricted-syntax`.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.ts
🧬 Code graph analysis (4)
packages/thirdweb/src/x402/sign.ts (1)
packages/thirdweb/src/x402/schemas.ts (2)
networkToCaip2ChainId(193-198)extractEvmChainId(114-121)
packages/thirdweb/src/x402/facilitator.ts (2)
packages/thirdweb/src/x402/types.ts (2)
PaymentArgs(22-39)PaymentRequiredResult(45-63)packages/thirdweb/src/x402/schemas.ts (1)
networkToCaip2ChainId(193-198)
packages/thirdweb/src/x402/common.ts (2)
packages/thirdweb/src/x402/facilitator.ts (1)
facilitator(112-298)packages/thirdweb/src/x402/schemas.ts (1)
networkToCaip2ChainId(193-198)
packages/thirdweb/src/x402/fetchWithPayment.ts (1)
packages/thirdweb/src/x402/schemas.ts (2)
networkToCaip2ChainId(193-198)extractEvmChainId(114-121)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Size
🔇 Additional comments (16)
packages/thirdweb/src/x402/fetchWithPayment.ts (3)
5-6: CAIP-2 helper imports make sense.Thanks for swapping in the shared CAIP-2 utilities here—the module now lines up with the schema layer.
100-109: Defensive CAIP-2 conversion looks good.I like the early exit on non-EVM chains; this keeps us from switching to unsupported networks while we add Solana support later.
161-163: Network matching now CAIP-2 aware.Comparing via
networkToCaip2ChainIdkeeps alias inputs aligned without changing the rest of the selector logic.packages/thirdweb/src/x402/sign.ts (4)
13-15: Shared CAIP-2 helpers pulled in cleanly.The signing flows now rely on the same parsing surface as the rest of x402.
75-81: Solid guard for unsupported networks.Resolving via CAIP-2 then bailing on non-EVM networks prevents us from generating headers we can’t settle yet.
202-205: Consistent chain parsing for ERC-3009.Good to see this path share the same CAIP-2 extraction logic.
247-250: Permit signing now shares the CAIP-2 guard.Keeps both signing flows consistent and avoids silent NaN chain IDs.
packages/thirdweb/src/x402/common.ts (5)
49-49: Scoped error message access is tidy.Pulling
errorMessagesup front keeps the later branches readable.
50-57: Delegating to facilitator.accepts matches the refactor goals.This keeps the middleware thin and lets the service define current payment options.
59-62: Short-circuit when payment data is missing.Returning the facilitator payload early keeps behaviour unchanged for first-pass 402 responses.
64-65: Reusing facilitator-provided accepts array makes sense.No more duplicating requirement building on the middleware.
87-92: CAIP-2 comparison avoids alias mismatches.This should cover cases where the requirement/network use different naming variants.
packages/thirdweb/src/x402/facilitator.ts (2)
5-13: Import reshuffle aligns facilitator with schemas.Pulling these types/helpers from
schemaskeeps the file consistent with the rest of the CAIP-2 shift.
51-53: Surface area update foracceptslooks correct.The signature matches what
decodePaymentRequestexpects.packages/thirdweb/src/x402/schemas.ts (2)
95-109: Helper trio for chain type detection is clear.The focused predicates make it easy to gate features per namespace.
111-121: CAIP-2 extraction utility fits nicely.Returning
nullfor non-EVM namespaces keeps callers honest about unsupported networks.
e70f706 to
8402662
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (5)
packages/thirdweb/src/x402/common.ts(3 hunks)packages/thirdweb/src/x402/facilitator.ts(3 hunks)packages/thirdweb/src/x402/fetchWithPayment.ts(3 hunks)packages/thirdweb/src/x402/schemas.ts(1 hunks)packages/thirdweb/src/x402/sign.ts(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/thirdweb/src/x402/facilitator.ts
- packages/thirdweb/src/x402/sign.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
packages/thirdweb/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling@exampleand a custom tag (@beta,@internal,@experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g.,const { jsPDF } = await import("jspdf"))
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
🧠 Learnings (9)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
Applied to files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Unified `Wallet` and `Account` interfaces in wallet architecture
Applied to files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/extensions/** : Auto-generated contracts from ABI definitions in extensions
Applied to files:
packages/thirdweb/src/x402/common.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The thirdweb-dev/ai-sdk-provider schemas use snake_case field naming convention (e.g., chain_id, transaction_hash) rather than camelCase, as defined in the zod schemas in packages/ai-sdk-provider/src/tools.ts.
Applied to files:
packages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The SignTransactionInput schema in thirdweb-dev/ai-sdk-provider uses snake_case field names (chain_id) rather than camelCase (chainId).
Applied to files:
packages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to **/*.test.{ts,tsx} : Use `FORKED_ETHEREUM_CHAIN` for mainnet interactions and `ANVIL_CHAIN` for isolated tests
Applied to files:
packages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-06-03T23:44:40.243Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7268
File: packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts:210-216
Timestamp: 2025-06-03T23:44:40.243Z
Learning: EIP7702 wallets do not need special handling for switching chains, unlike EIP4337 wallets which require reconnection when switching chains. In the switchChain method condition, EIP7702 should be intentionally excluded from the reconnection logic.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-05-30T17:14:25.332Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 7227
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/modules/components/OpenEditionMetadata.tsx:26-26
Timestamp: 2025-05-30T17:14:25.332Z
Learning: The ModuleCardUIProps interface already includes a client prop of type ThirdwebClient, so when components use `Omit<ModuleCardUIProps, "children" | "updateButton">`, they inherit the client prop without needing to add it explicitly.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.ts
📚 Learning: 2025-06-06T23:46:08.795Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:424-424
Timestamp: 2025-06-06T23:46:08.795Z
Learning: The thirdweb project has an ESLint rule that restricts direct usage of `defineChain`. When it's necessary to use `defineChain` directly, it's acceptable to disable the rule with `// eslint-disable-next-line no-restricted-syntax`.
Applied to files:
packages/thirdweb/src/x402/fetchWithPayment.ts
🧬 Code graph analysis (2)
packages/thirdweb/src/x402/common.ts (2)
packages/thirdweb/src/x402/facilitator.ts (1)
facilitator(112-303)packages/thirdweb/src/x402/schemas.ts (1)
networkToCaip2ChainId(193-198)
packages/thirdweb/src/x402/fetchWithPayment.ts (1)
packages/thirdweb/src/x402/schemas.ts (2)
networkToCaip2ChainId(193-198)extractEvmChainId(114-121)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
- GitHub Check: E2E Tests (pnpm, vite)
- GitHub Check: E2E Tests (pnpm, esbuild)
- GitHub Check: E2E Tests (pnpm, webpack)
- GitHub Check: Size
- GitHub Check: Unit Tests
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript)
| /** | ||
| * Chain type helper functions | ||
| */ | ||
| export function isSolanaChain(caip2ChainId: Caip2ChainId): boolean { | ||
| return caip2ChainId.startsWith("solana:"); | ||
| } | ||
|
|
||
| export function isEvmChain(caip2ChainId: Caip2ChainId): boolean { | ||
| return caip2ChainId.startsWith("eip155:"); | ||
| } | ||
|
|
||
| export function isZkSyncChain(caip2ChainId: Caip2ChainId): boolean { | ||
| // zkSync Era mainnet = 324, testnet = 280 | ||
| return caip2ChainId === "eip155:324" || caip2ChainId === "eip155:280"; | ||
| } | ||
|
|
||
| /** | ||
| * Extract numeric chain ID from CAIP-2 EVM chain (e.g., "eip155:1" -> 1) | ||
| */ | ||
| export function extractEvmChainId(caip2ChainId: Caip2ChainId): number | null { | ||
| if (!isEvmChain(caip2ChainId)) { | ||
| return null; | ||
| } | ||
| if (network.startsWith("eip155:")) { | ||
| const chainId = parseInt(network.split(":")[1] ?? "0"); | ||
| if (!Number.isNaN(chainId) && chainId > 0) { | ||
| return chainId; | ||
| } else { | ||
| throw new Error(`Invalid network: ${network}`); | ||
| const parts = caip2ChainId.split(":"); | ||
| const chainId = Number(parts[1]); | ||
| return Number.isNaN(chainId) ? null : chainId; | ||
| } | ||
|
|
||
| /** | ||
| * CAIP-2 compliant blockchain identifier | ||
| * @see https://chainagnostic.org/CAIPs/caip-2 | ||
| */ | ||
| export const Caip2ChainIdSchema = z | ||
| .union([z.string(), z.number().int().positive()]) | ||
| .transform((value, ctx) => { | ||
| // Handle proper CAIP-2 format (already valid) | ||
| if (typeof value === "string" && value.includes(":")) { | ||
| const [namespace, reference] = value.split(":"); | ||
|
|
||
| // Solana mainnet/devnet aliases | ||
| if (namespace === "solana" && reference === "mainnet") { | ||
| return "solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ" as const; | ||
| } | ||
| if (namespace === "solana" && reference === "devnet") { | ||
| return "solana:8E9rvCKLFQia2Y35HXjjpWzj8weVo44K" as const; | ||
| } | ||
|
|
||
| // Validate CAIP-2 format | ||
| const namespaceRegex = /^[-a-z0-9]{3,8}$/; | ||
| const referenceRegex = /^[-_a-zA-Z0-9]{1,32}$/; | ||
|
|
||
| if (!namespaceRegex.test(namespace ?? "")) { | ||
| ctx.addIssue({ | ||
| code: z.ZodIssueCode.custom, | ||
| message: `Invalid CAIP-2 namespace: ${namespace}. Must match [-a-z0-9]{3,8}`, | ||
| }); | ||
| return z.NEVER; | ||
| } | ||
|
|
||
| if (!referenceRegex.test(reference ?? "")) { | ||
| ctx.addIssue({ | ||
| code: z.ZodIssueCode.custom, | ||
| message: `Invalid CAIP-2 reference: ${reference}. Must match [-_a-zA-Z0-9]{1,32}`, | ||
| }); | ||
| return z.NEVER; | ||
| } | ||
|
|
||
| return value as `${string}:${string}`; | ||
| } | ||
|
|
||
| // Handle number (EVM chain ID fallback) | ||
| if (typeof value === "number") { | ||
| return `eip155:${value}` as const; | ||
| } | ||
|
|
||
| // Handle string number (EVM chain ID fallback) | ||
| const numValue = Number(value); | ||
| if (!Number.isNaN(numValue) && Number.isInteger(numValue) && numValue > 0) { | ||
| return `eip155:${numValue}` as const; | ||
| } | ||
|
|
||
| const mappedChainId = EvmNetworkToChainId.get(value as Network); | ||
| if (mappedChainId) { | ||
| return `eip155:${mappedChainId}` as const; | ||
| } | ||
|
|
||
| ctx.addIssue({ | ||
| code: z.ZodIssueCode.custom, | ||
| message: `Invalid chain ID: ${value}. Must be a CAIP-2 identifier (e.g., "eip155:1", "solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ"), a numeric chain ID for EVM, or "solana:mainnet"/"solana:devnet"`, | ||
| }); | ||
| return z.NEVER; | ||
| }) | ||
| .describe( | ||
| "CAIP-2 blockchain identifier (e.g., 'eip155:1' for Ethereum, 'solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ' for Solana mainnet). Also accepts numeric EVM chain IDs (e.g., 1, 137) or aliases ('solana:mainnet', 'solana:devnet') for backward compatibility.", | ||
| ); | ||
|
|
||
| export type Caip2ChainId = z.output<typeof Caip2ChainIdSchema>; | ||
|
|
||
| export function networkToCaip2ChainId(network: string | Chain): Caip2ChainId { | ||
| if (typeof network === "object") { | ||
| return `eip155:${network.id}` as const; | ||
| } | ||
| const mappedChainId = EvmNetworkToChainId.get(network as Network); | ||
| if (!mappedChainId) { | ||
| throw new Error(`Invalid network: ${network}`); | ||
| } | ||
| // TODO (402): support solana networks | ||
| if (mappedChainId === 101 || mappedChainId === 103) { | ||
| throw new Error("Solana networks not supported yet."); | ||
| } | ||
| return mappedChainId; | ||
| return Caip2ChainIdSchema.parse(network); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major
Add required TSDoc for new public exports
Per the packages/thirdweb/** guidelines, every public symbol needs comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, etc.). The newly exported helpers here (isSolanaChain, isEvmChain, isZkSyncChain, extractEvmChainId, Caip2ChainIdSchema, and networkToCaip2ChainId) are missing that coverage. Please add the required documentation so the package stays compliant.
8402662 to
c8fa393
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/thirdweb/src/x402/schemas.ts (1)
102-186: Add required TSDoc (example + tag) for the new public helpers.
Follow-up on the earlier feedback:extractEvmChainIdandnetworkToCaip2ChainIdare public exports underpackages/thirdweb, but their docblocks still lack the mandated compiling@exampleand custom tag (@beta,@internal, etc.). Please add them so the documentation build and lint rules stay green.@@ -/** - * Extract numeric chain ID from CAIP-2 EVM chain (e.g., "eip155:1" -> 1) - */ +/** + * Extracts the numeric chain ID from a CAIP-2 EVM identifier (for example, `"eip155:1"` becomes `1`). + * + * @example + * ```ts + * const chainId = extractEvmChainId("eip155:1"); + * // chainId === 1 + * ``` + * @beta + */ export function extractEvmChainId(caip2ChainId: Caip2ChainId): number | null { @@ -export function networkToCaip2ChainId(network: string | Chain): Caip2ChainId { +/** + * Normalizes a thirdweb network value (slug, numeric ID, or CAIP-2 string) into a CAIP-2 chain identifier. + * + * @example + * ```ts + * const caip2 = networkToCaip2ChainId("polygon"); + * // caip2 === "eip155:137" + * ``` + * @beta + */ +export function networkToCaip2ChainId(network: string | Chain): Caip2ChainId {As per coding guidelines.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (6)
packages/thirdweb/src/x402/common.ts(3 hunks)packages/thirdweb/src/x402/facilitator.ts(3 hunks)packages/thirdweb/src/x402/fetchWithPayment.ts(3 hunks)packages/thirdweb/src/x402/schemas.ts(2 hunks)packages/thirdweb/src/x402/sign.ts(4 hunks)packages/thirdweb/src/x402/types.ts(0 hunks)
💤 Files with no reviewable changes (1)
- packages/thirdweb/src/x402/types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/thirdweb/src/x402/fetchWithPayment.ts
- packages/thirdweb/src/x402/sign.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/schemas.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/schemas.ts
packages/thirdweb/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling@exampleand a custom tag (@beta,@internal,@experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g.,const { jsPDF } = await import("jspdf"))
Files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/schemas.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7268
File: packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts:210-216
Timestamp: 2025-06-03T23:44:40.243Z
Learning: EIP7702 wallets do not need special handling for switching chains, unlike EIP4337 wallets which require reconnection when switching chains. In the switchChain method condition, EIP7702 should be intentionally excluded from the reconnection logic.
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
Applied to files:
packages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Unified `Wallet` and `Account` interfaces in wallet architecture
Applied to files:
packages/thirdweb/src/x402/common.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/extensions/** : Auto-generated contracts from ABI definitions in extensions
Applied to files:
packages/thirdweb/src/x402/common.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The thirdweb-dev/ai-sdk-provider schemas use snake_case field naming convention (e.g., chain_id, transaction_hash) rather than camelCase, as defined in the zod schemas in packages/ai-sdk-provider/src/tools.ts.
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-08-28T20:50:33.170Z
Learnt from: joaquim-verges
Repo: thirdweb-dev/js PR: 7922
File: apps/playground-web/src/app/ai/ai-sdk/components/chat-container.tsx:167-181
Timestamp: 2025-08-28T20:50:33.170Z
Learning: The SignTransactionInput schema in thirdweb-dev/ai-sdk-provider uses snake_case field names (chain_id) rather than camelCase (chainId).
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to **/*.test.{ts,tsx} : Use `FORKED_ETHEREUM_CHAIN` for mainnet interactions and `ANVIL_CHAIN` for isolated tests
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/exports/** : Every public symbol must have comprehensive TSDoc with at least one `example` block that compiles and custom annotation tags (`beta`, `internal`, `experimental`)
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-08-29T15:37:38.513Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-08-29T15:37:38.513Z
Learning: Applies to packages/thirdweb/**/*.{ts,tsx} : Every public symbol must have comprehensive TSDoc with at least one compiling `example` and a custom tag (`beta`, `internal`, `experimental`, etc.)
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-08-29T15:37:38.513Z
Learnt from: CR
Repo: thirdweb-dev/js PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-08-29T15:37:38.513Z
Learning: Applies to packages/thirdweb/**/*.{ts,tsx} : Comment only ambiguous logic; avoid restating TypeScript in prose
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-10-01T22:32:18.080Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 8169
File: packages/thirdweb/src/react/web/ui/Bridge/FundWallet.tsx:95-107
Timestamp: 2025-10-01T22:32:18.080Z
Learning: In the thirdweb-dev/js codebase, specifically for React components in packages/thirdweb/src/react/**/*.{ts,tsx} files, do not suggest adding TSDoc blocks to function components. The project maintainer MananTank has explicitly declined these suggestions.
Applied to files:
packages/thirdweb/src/x402/schemas.ts
📚 Learning: 2025-06-06T23:46:08.795Z
Learnt from: MananTank
Repo: thirdweb-dev/js PR: 7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:424-424
Timestamp: 2025-06-06T23:46:08.795Z
Learning: The thirdweb project has an ESLint rule that restricts direct usage of `defineChain`. When it's necessary to use `defineChain` directly, it's acceptable to disable the rule with `// eslint-disable-next-line no-restricted-syntax`.
Applied to files:
packages/thirdweb/src/x402/schemas.ts
🧬 Code graph analysis (2)
packages/thirdweb/src/x402/common.ts (2)
packages/thirdweb/src/x402/facilitator.ts (1)
facilitator(112-303)packages/thirdweb/src/x402/schemas.ts (1)
networkToCaip2ChainId(181-186)
packages/thirdweb/src/x402/facilitator.ts (2)
packages/thirdweb/src/x402/types.ts (2)
PaymentArgs(21-38)PaymentRequiredResult(44-62)packages/thirdweb/src/x402/schemas.ts (1)
networkToCaip2ChainId(181-186)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: Size
- GitHub Check: E2E Tests (pnpm, esbuild)
- GitHub Check: Unit Tests
- GitHub Check: E2E Tests (pnpm, webpack)
- GitHub Check: E2E Tests (pnpm, vite)
- GitHub Check: Lint Packages
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript)
| const selectedPaymentRequirements = paymentRequirements.find( | ||
| (value) => | ||
| value.scheme === decodedPayment.scheme && | ||
| networkToChainId(value.network) === | ||
| networkToChainId(decodedPayment.network), | ||
| networkToCaip2ChainId(value.network) === | ||
| networkToCaip2ChainId(decodedPayment.network), | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent invalid network strings from crashing decodePaymentRequest.
Right now networkToCaip2ChainId(decodedPayment.network) can throw (for example when a client tampers with the payment header and sends an unknown slug). That ZodError bubbles out of decodePaymentRequest, turning what should be a 402 “invalid payment” response into an unhandled 500. Please normalize the decoded network inside a try/catch and short-circuit with the existing 402 pathway before attempting the find, so malformed input can’t take down the handler.
@@
- const selectedPaymentRequirements = paymentRequirements.find(
- (value) =>
- value.scheme === decodedPayment.scheme &&
- networkToCaip2ChainId(value.network) ===
- networkToCaip2ChainId(decodedPayment.network),
- );
+ let decodedNetwork: string;
+ try {
+ decodedNetwork = networkToCaip2ChainId(decodedPayment.network);
+ } catch (error) {
+ return {
+ status: 402,
+ responseHeaders: {
+ "Content-Type": "application/json",
+ },
+ responseBody: {
+ x402Version,
+ error:
+ errorMessages?.invalidPayment ||
+ (error instanceof Error ? error.message : "Invalid payment"),
+ accepts: paymentRequirements,
+ },
+ };
+ }
+
+ const selectedPaymentRequirements = paymentRequirements.find((value) => {
+ try {
+ return (
+ value.scheme === decodedPayment.scheme &&
+ networkToCaip2ChainId(value.network) === decodedNetwork
+ );
+ } catch {
+ return false;
+ }
+ });🤖 Prompt for AI Agents
In packages/thirdweb/src/x402/common.ts around lines 87 to 92, calling
networkToCaip2ChainId(decodedPayment.network) can throw on malformed/unknown
network strings and currently bubbles up; wrap the normalization of
decodedPayment.network in a try/catch before running the
paymentRequirements.find so that any error from networkToCaip2ChainId is caught
and you short-circuit to the existing 402 "invalid payment" path (e.g., treat
the decoded network as invalid, do not perform the find, and return or set
selectedPaymentRequirements to undefined so the existing 402 handling runs).

PR-Codex overview
This PR focuses on refactoring the handling of blockchain network identifiers, specifically transitioning from
networkToChainIdtoextractEvmChainIdandnetworkToCaip2ChainId. It also introduces error handling for unsupported chain IDs and adds a newacceptsfunction in thefacilitator.Detailed summary
FacilitatorSupportedAssetSchematype export fromtypes.ts.networkToChainIdwithextractEvmChainIdandnetworkToCaip2ChainIdinfetchWithPayment.ts,sign.ts, andcommon.ts.acceptsfunction infacilitator.tsto handle payment requests.networkToChainIdimplementation inschemas.tstonetworkToCaip2ChainId.common.ts.Summary by CodeRabbit
New Features
Improvements
Chores