Skip to content

Conversation

@joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented Sep 25, 2025


PR-Codex overview

This PR focuses on updating the thirdweb library to accept chain objects for x402 APIs, enhancing flexibility and usability in payment processing across different blockchain networks.

Detailed summary

  • Updated network parameter to accept chain objects in various files.
  • Introduced arbitrumSepolia as a network option in multiple middleware and payment functions.
  • Modified error messages to include chain-specific details.
  • Adjusted networkToChainId function to handle Chain type.
  • Updated payment requirement handling to use chain ID instead of network strings.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features
    • x402 APIs now accept chain objects for the network parameter, enabling simpler, type-safe configuration.
    • Improved payment error message when exceeding maximum allowed amount, including the current limit in base units.
    • Playground updated to use a chain constant (e.g., arbitrumSepolia) instead of hard-coded network strings.
  • Documentation
    • Usage examples updated to pass chain objects for network across settle and verify flows.
  • Chores
    • Added changeset for a patch release of the thirdweb package.

@vercel
Copy link

vercel bot commented Sep 25, 2025

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

Project Deployment Preview Comments Updated (UTC)
docs-v2 Ready Ready Preview Comment Sep 25, 2025 3:03am
nebula Ready Ready Preview Comment Sep 25, 2025 3:03am
thirdweb_playground Ready Ready Preview Comment Sep 25, 2025 3:03am
thirdweb-www Ready Ready Preview Comment Sep 25, 2025 3:03am
wallet-ui Ready Ready Preview Comment Sep 25, 2025 3:03am

@changeset-bot
Copy link

changeset-bot bot commented Sep 25, 2025

🦋 Changeset detected

Latest commit: 3180161

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
thirdweb Patch
@thirdweb-dev/nebula Patch
@thirdweb-dev/wagmi-adapter Patch

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 25, 2025

Walkthrough

Adds 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

Cohort / File(s) Summary of changes
Core x402 chain-object support
packages/thirdweb/src/x402/common.ts, packages/thirdweb/src/x402/schemas.ts, packages/thirdweb/src/x402/types.ts
Accept Chain or string for network; derive chainId via networkToChainId; refactor processing to use chainId; adjust default asset resolution; update PaymentArgs.network type to include Chain; simplify 402 requirement construction; revise error messages.
App integration updates
apps/playground-web/src/app/payments/x402/page.tsx, apps/playground-web/src/middleware.ts, apps/portal/src/app/payments/x402/page.mdx
Replace CAIP2 string networks with arbitrumSepolia Chain object; import arbitrumSepolia; pass chain directly to settlePayment.
x402 examples/docs refresh
packages/thirdweb/src/x402/settle-payment.ts, packages/thirdweb/src/x402/verify-payment.ts, packages/thirdweb/src/x402/facilitator.ts
Update examples to import and use arbitrumSepolia instead of eip155 strings; add a usage import snippet for paymentMiddleware; comment adjustments.
Payment error message tweak
packages/thirdweb/src/x402/fetchWithPayment.ts
Expand max-amount error message to include current maxValue in base units.
Release metadata
.changeset/polite-banks-peel.md
Add changeset defining a patch release for “thirdweb” noting acceptance of Chain objects for x402 APIs.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The provided PR description retains the commented-out template and only includes a PR-Codex overview without populating the required sections for title, reviewer notes, or testing instructions. The placeholder headings were not replaced with actual content, so the description does not follow the repository’s template. As a result, it fails to meet the guidelines for PR descriptions. Please update the PR description by replacing the commented template with a concise title in the required “[SDK/Dashboard/Portal] Feature/Fix: …” format, filling in the “Notes for the reviewer” section with any important details, and adding a “How to test” section that outlines steps or commands to verify the changes, then remove the placeholder comments.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title “[SDK] Support Chain objects in x402 payment utilities” clearly and concisely describes the primary change in this pull request, indicating the scope (SDK) and the key feature (support for Chain objects in x402 utilities) without unnecessary detail.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch _SDK_Support_Chain_objects_in_x402_payment_utilities

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added the Playground Changes involving the Playground codebase. label Sep 25, 2025
@github-actions github-actions bot added Portal Involves changes to the Portal (docs) codebase. packages SDK Involves changes to the thirdweb SDK labels Sep 25, 2025
Copy link
Member Author


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

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.

@github-actions
Copy link
Contributor

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.07 KB (0%) 1.3 s (0%) 366 ms (+49.8% 🔺) 1.7 s
thirdweb (cjs) 361.6 KB (0%) 7.3 s (0%) 2.3 s (+6.72% 🔺) 9.6 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 54 ms (+214.11% 🔺) 169 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 76 ms (+1175.76% 🔺) 87 ms
thirdweb/react (minimal + tree-shaking) 19.14 KB (0%) 383 ms (0%) 96 ms (+711.23% 🔺) 479 ms

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 be minor, not patch.

This PR expands the public PaymentArgs.network surface, 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 name

The implementation now accepts chainId, but the @param tag still references network. 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 for
packages/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 broadened network input.

Since callers can now pass either a facilitator network string or a Chain object, 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.

📥 Commits

Reviewing files that changed from the base of the PR and between a83104e and 3180161.

📒 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 @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless 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 @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless 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.ts
  • apps/playground-web/src/middleware.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/types.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/settle-payment.ts
  • packages/thirdweb/src/x402/schemas.ts
  • apps/playground-web/src/app/payments/x402/page.tsx
  • packages/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.ts
  • apps/playground-web/src/middleware.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/types.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/settle-payment.ts
  • packages/thirdweb/src/x402/schemas.ts
  • apps/playground-web/src/app/payments/x402/page.tsx
  • packages/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 @example and 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.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/types.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/settle-payment.ts
  • packages/thirdweb/src/x402/schemas.ts
  • packages/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
Use NavLink for internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Use cn() from @/lib/utils for conditional class logic
Use design system tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components (Node edge): Start files with import "server-only";
Client Components (browser): Begin files with 'use client';
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header – never embed tokens in URLs
Return typed results (e.g., Project[], User[]) – avoid any
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys for React Query cache hits
Configure staleTime/cacheTime in React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never import posthog-js in server components

Files:

  • apps/playground-web/src/middleware.ts
  • apps/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.ts file

Files:

  • packages/thirdweb/src/x402/types.ts
.changeset/*.md

📄 CodeRabbit inference engine (AGENTS.md)

.changeset/*.md: Each change in packages/* 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 LGTM

Returning network.id when a Chain object is provided lines up neatly with the shape exported from thirdweb/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 messaging

Nice 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 API

Thanks for updating the docs to showcase the arbitrumSepolia chain object—this keeps the guidance in sync with the new PaymentArgs.network contract.

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 arbitrumSepolia constant; 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 Chain input 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 Chain object through to settlePayment matches the widened PaymentArgs.network union.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

packages Playground Changes involving the Playground codebase. Portal Involves changes to the Portal (docs) codebase. SDK Involves changes to the thirdweb SDK

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants