-
Notifications
You must be signed in to change notification settings - Fork 615
[SDK] Support Chain objects in x402 payment utilities #8126
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] Support Chain objects in x402 payment utilities #8126
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 3180161 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
WalkthroughAdds support for passing Chain objects to x402 APIs by updating schema/type signatures and internal handling to derive chainId from either strings or Chain objects. Refactors payment processing to operate on chainId. Updates app usage and examples to import and pass arbitrumSepolia instead of CAIP2 strings. Minor error message and docs tweaks. Adds a changeset. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant App as App / Middleware
participant X402 as x402.decodePaymentRequest
participant Schema as networkToChainId
participant Proc as processPriceToAtomicAmount
participant Asset as getDefaultAsset
Client->>App: Request protected resource
App->>X402: decodePaymentRequest({ network: Chain | string, price, ... })
X402->>Schema: networkToChainId(network)
alt network is Chain object
Schema-->>X402: chainId = network.id
else network is string
Schema-->>X402: chainId = parsed eip155 or mapped
end
alt invalid network
X402-->>App: 402 response (invalid network, accepts: [])
App-->>Client: 402 Payment Required
else valid chainId
X402->>Proc: processPriceToAtomicAmount(chainId, price)
Proc-->>X402: atomic amount
X402->>Asset: getDefaultAsset(chainId)
Asset-->>X402: default asset (or error)
alt asset resolved
X402-->>App: 402 with payment requirements (network: eip155:chainId)
App-->>Client: 402 Payment Required with requirements
else asset resolution failed
X402-->>App: 402 error (asset resolution failure)
App-->>Client: 402 Payment Required (error details)
end
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Comment |
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. |
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: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
.changeset/polite-banks-peel.md (1)
1-6: Bump should beminor, notpatch.This PR expands the public
PaymentArgs.networksurface, which is a new API capability. Per our changeset guidelines, widening public API warrants a minor release.-"thirdweb": patch +"thirdweb": minor
🧹 Nitpick comments (3)
packages/thirdweb/src/x402/common.ts (1)
180-182: Synchronize TSDoc with new parameter nameThe implementation now accepts
chainId, but the@paramtag still referencesnetwork. Let’s update the docs to avoid confusion.- * @param network - The network to get the default asset for + * @param chainId - The chain to get the default asset forpackages/thirdweb/src/x402/facilitator.ts (1)
31-31: Keep example style consistent with surrounding imports.The new snippet should match the rest of the example (double quotes + semicolon) so copy/paste stays lint‑clean.
-* import { paymentMiddleware } from 'x402-hono' +* import { paymentMiddleware } from "x402-hono";packages/thirdweb/src/x402/types.ts (1)
6-35: Document the broadenednetworkinput.Since callers can now pass either a facilitator network string or a
Chainobject, the TSDoc should spell that out for clarity.- /** The blockchain network where the payment should be processed */ - network: FacilitatorNetwork | Chain; + /** + * The blockchain network where the payment should be processed. + * Accepts an x402 facilitator network string or a {@link Chain} object. + */ + network: FacilitatorNetwork | Chain;
📜 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 (11)
.changeset/polite-banks-peel.md(1 hunks)apps/playground-web/src/app/payments/x402/page.tsx(2 hunks)apps/playground-web/src/middleware.ts(1 hunks)apps/portal/src/app/payments/x402/page.mdx(2 hunks)packages/thirdweb/src/x402/common.ts(6 hunks)packages/thirdweb/src/x402/facilitator.ts(1 hunks)packages/thirdweb/src/x402/fetchWithPayment.ts(1 hunks)packages/thirdweb/src/x402/schemas.ts(2 hunks)packages/thirdweb/src/x402/settle-payment.ts(4 hunks)packages/thirdweb/src/x402/types.ts(2 hunks)packages/thirdweb/src/x402/verify-payment.ts(2 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{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/fetchWithPayment.tsapps/playground-web/src/middleware.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/types.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/settle-payment.tspackages/thirdweb/src/x402/schemas.tsapps/playground-web/src/app/payments/x402/page.tsxpackages/thirdweb/src/x402/verify-payment.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/fetchWithPayment.tsapps/playground-web/src/middleware.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/types.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/settle-payment.tspackages/thirdweb/src/x402/schemas.tsapps/playground-web/src/app/payments/x402/page.tsxpackages/thirdweb/src/x402/verify-payment.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/fetchWithPayment.tspackages/thirdweb/src/x402/facilitator.tspackages/thirdweb/src/x402/types.tspackages/thirdweb/src/x402/common.tspackages/thirdweb/src/x402/settle-payment.tspackages/thirdweb/src/x402/schemas.tspackages/thirdweb/src/x402/verify-payment.ts
apps/{dashboard,playground-web}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/{dashboard,playground-web}/**/*.{ts,tsx}: Import UI primitives from@/components/ui/*(Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground apps
UseNavLinkfor internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Usecn()from@/lib/utilsfor conditional class logic
Use design system tokens (e.g.,bg-card,border-border,text-muted-foreground)
Server Components (Node edge): Start files withimport "server-only";
Client Components (browser): Begin files with'use client';
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader – never embed tokens in URLs
Return typed results (e.g.,Project[],User[]) – avoidany
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysfor React Query cache hits
ConfigurestaleTime/cacheTimein React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never importposthog-jsin server components
Files:
apps/playground-web/src/middleware.tsapps/playground-web/src/app/payments/x402/page.tsx
**/types.ts
📄 CodeRabbit inference engine (AGENTS.md)
Provide and re‑use local type barrels in a
types.tsfile
Files:
packages/thirdweb/src/x402/types.ts
.changeset/*.md
📄 CodeRabbit inference engine (AGENTS.md)
.changeset/*.md: Each change inpackages/*must include a changeset for the appropriate package
Version bump rules: patch for non‑API changes; minor for new/modified public API
Files:
.changeset/polite-banks-peel.md
🧠 Learnings (4)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
PR: thirdweb-dev/js#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.ts
📚 Learning: 2025-08-29T15:37:38.513Z
Learnt from: CR
PR: thirdweb-dev/js#0
File: AGENTS.md:0-0
Timestamp: 2025-08-29T15:37:38.513Z
Learning: Applies to .changeset/*.md : Version bump rules: patch for non‑API changes; minor for new/modified public API
Applied to files:
.changeset/polite-banks-peel.md
📚 Learning: 2025-06-06T23:46:08.795Z
Learnt from: MananTank
PR: thirdweb-dev/js#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:
.changeset/polite-banks-peel.md
📚 Learning: 2025-08-29T15:37:38.513Z
Learnt from: CR
PR: thirdweb-dev/js#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/verify-payment.ts
🧬 Code graph analysis (2)
packages/thirdweb/src/x402/types.ts (1)
packages/thirdweb/src/x402/schemas.ts (1)
FacilitatorNetwork(27-27)
packages/thirdweb/src/x402/common.ts (2)
packages/thirdweb/src/x402/schemas.ts (1)
networkToChainId(59-80)packages/thirdweb/src/x402/facilitator.ts (1)
facilitator(59-196)
⏰ 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). (2)
- GitHub Check: Unit Tests
- GitHub Check: Size
🔇 Additional comments (7)
packages/thirdweb/src/x402/schemas.ts (1)
59-62: Chain input normalization LGTMReturning
network.idwhen a Chain object is provided lines up neatly with the shape exported fromthirdweb/chains, so the new union path integrates cleanly with the existing string handling.packages/thirdweb/src/x402/fetchWithPayment.ts (1)
87-89: Clearer max-value error messagingNice touch on surfacing the configured cap in the exception; this should make debugging misconfigured payment ceilings much quicker.
packages/thirdweb/src/x402/settle-payment.ts (1)
28-49: Examples now align with Chain-based APIThanks for updating the docs to showcase the
arbitrumSepoliachain object—this keeps the guidance in sync with the newPaymentArgs.networkcontract.apps/portal/src/app/payments/x402/page.mdx (1)
53-72: Example update matches the new Chain-aware API.Thanks for switching the docs to the shared
arbitrumSepoliaconstant; it keeps the narrative aligned with the new typings.packages/thirdweb/src/x402/verify-payment.ts (1)
20-40: Docs stay in sync with Chain support.Great to see the verification example updated to the new
Chaininput style.apps/playground-web/src/app/payments/x402/page.tsx (1)
62-80: Playground snippet reflects real usage.The embedded middleware sample now mirrors the Chain-based API—looks good.
apps/playground-web/src/middleware.ts (1)
29-35: Runtime change aligns with the typed surface.Passing the
Chainobject through tosettlePaymentmatches the widenedPaymentArgs.networkunion.

PR-Codex overview
This PR focuses on updating the
thirdweblibrary to accept chain objects for x402 APIs, enhancing flexibility and usability in payment processing across different blockchain networks.Detailed summary
networkparameter to acceptchainobjects in various files.arbitrumSepoliaas a network option in multiple middleware and payment functions.networkToChainIdfunction to handleChaintype.Summary by CodeRabbit