Skip to content

Conversation

@joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented Nov 1, 2025


PR-Codex overview

This PR focuses on refactoring the handling of blockchain network identifiers, specifically transitioning from networkToChainId to extractEvmChainId and networkToCaip2ChainId. It also introduces error handling for unsupported chain IDs and adds a new accepts function in the facilitator.

Detailed summary

  • Removed FacilitatorSupportedAssetSchema type export from types.ts.
  • Replaced networkToChainId with extractEvmChainId and networkToCaip2ChainId in fetchWithPayment.ts, sign.ts, and common.ts.
  • Added error handling for unsupported chain IDs.
  • Introduced a new accepts function in facilitator.ts to handle payment requests.
  • Updated networkToChainId implementation in schemas.ts to networkToCaip2ChainId.
  • Removed unused functions and types related to payment processing in common.ts.

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

Summary by CodeRabbit

  • New Features

    • Added a facilitator endpoint to request payment acceptance details.
  • Improvements

    • Switched to CAIP‑2 based chain ID handling for more consistent multi‑chain resolution.
    • Simplified payment requirement construction by relying on facilitator responses.
    • Signing and payment flows now validate chain resolution and surface clearer errors for unsupported networks.
  • Chores

    • Removed legacy asset/type exports and obsolete internal helpers.

@vercel
Copy link

vercel bot commented Nov 1, 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 Nov 1, 2025 1:45am
nebula Ready Ready Preview Comment Nov 1, 2025 1:45am
thirdweb_playground Ready Ready Preview Comment Nov 1, 2025 1:45am
thirdweb-www Ready Ready Preview Comment Nov 1, 2025 1:45am
wallet-ui Ready Ready Preview Comment Nov 1, 2025 1:45am

@changeset-bot
Copy link

changeset-bot bot commented Nov 1, 2025

⚠️ No Changeset found

Latest commit: c8fa393

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions bot added packages SDK Involves changes to the thirdweb SDK labels Nov 1, 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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 1, 2025

Walkthrough

Reworks 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

Cohort / File(s) Summary
Facilitator API & Payment flow
packages/thirdweb/src/x402/facilitator.ts, packages/thirdweb/src/x402/common.ts
Adds facilitator.accepts(args: Omit<PaymentArgs,"facilitator">) => Promise<PaymentRequiredResult> that POSTs to /accepts and surfaces PaymentRequiredResult. common.ts delegates payment requirement generation to facilitator.accepts, removing inlined price/asset helpers and legacy requirement construction.
CAIP‑2 Chain ID & Schemas
packages/thirdweb/src/x402/schemas.ts
Removes networkToChainId. Adds Caip2ChainIdSchema, exported Caip2ChainId type, networkToCaip2ChainId, and extractEvmChainId plus internal chain classifiers (e.g., isEvmChain). Normalizes CAIP‑2 inputs (including Solana aliases) and provides CAIP‑2→EVM extraction.
Fetch & Sign Flows (chain resolution)
packages/thirdweb/src/x402/fetchWithPayment.ts, packages/thirdweb/src/x402/sign.ts
Replace networkToChainId usage with networkToCaip2ChainId + extractEvmChainId. Add null/unsupported-chain checks and errors/TODOs for non‑EVM/Solana cases. Update payment-matching and signing logic to use CAIP‑2→EVM-derived chain IDs.
Types cleanup
packages/thirdweb/src/x402/types.ts
Removes exported DefaultAsset type (previously derived from FacilitatorSupportedAssetSchema) and drops dependency on that schema from public types.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Areas needing extra attention:
    • Caip2ChainIdSchema normalization and edge-case handling for aliases and numeric inputs.
    • Correctness of extractEvmChainId return values and null paths (Solana/non‑EVM).
    • facilitator.accepts request/response shape, header handling, and integration with existing facilitator runtime.
    • Removal of legacy helpers in common.ts—verify all responsibilities moved and no missing transformations.
    • Payment-matching logic updates in fetchWithPayment.ts and signing null-checks in sign.ts.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The pull request description relies primarily on auto-generated PR-Codex output rather than fulfilling the required template structure. While the PR-Codex summary provides substantive technical information about the changes (file modifications, function replacements, new utilities), the required sections specified in the template are not adequately addressed. The description includes only placeholder text for "Notes for the reviewer" and "How to test" sections without providing manual guidance, leaving critical information for reviewers missing. No issue tag (TEAM-0000 format) is provided, and no explicit testing instructions are given beyond the placeholder comment.
Docstring Coverage ⚠️ Warning Docstring coverage is 54.55% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "[SDK] Refactor payment processing to use facilitator.accepts" refers to a real and significant change in the pull request: the addition of the new accepts method to the ThirdwebX402Facilitator interface. This method is indeed a key component of the refactoring. The title accurately reflects this aspect of the changeset, allowing reviewers to understand that the PR involves refactoring payment processing with a new facilitator method. While the PR also encompasses a substantial CAIP-2 chain identifier migration across multiple files, the title does capture a genuine part of the overall refactoring objective.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch _X402_Refactor_payment_processing_to_use_facilitator.accepts

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.

@joaquim-verges joaquim-verges marked this pull request as ready for review November 1, 2025 01:01
@joaquim-verges joaquim-verges requested review from a team as code owners November 1, 2025 01:01
@joaquim-verges joaquim-verges changed the title [X402] Refactor payment processing to use facilitator.accepts [SDK] Refactor payment processing to use facilitator.accepts Nov 1, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Nov 1, 2025

size-limit report 📦

Path Size
@thirdweb-dev/nexus (esm) 104.88 KB (0%)
@thirdweb-dev/nexus (cjs) 316.6 KB (0%)

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: 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/thirdweb needs full TSDoc with an example and a custom tag. Please add it for isSolanaChain, isEvmChain, isZkSyncChain, extractEvmChainId, Caip2ChainIdSchema, and networkToCaip2ChainId. 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 8ef418c and e70f706.

📒 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 @/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/sign.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/fetchWithPayment.ts
  • packages/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.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/fetchWithPayment.ts
  • packages/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 @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/sign.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/fetchWithPayment.ts
  • packages/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.ts
  • packages/thirdweb/src/x402/common.ts
  • packages/thirdweb/src/x402/fetchWithPayment.ts
  • 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/sign.ts
  • packages/thirdweb/src/x402/fetchWithPayment.ts
  • 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/sign.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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 networkToCaip2ChainId keeps 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 errorMessages up 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 schemas keeps the file consistent with the rest of the CAIP-2 shift.


51-53: Surface area update for accepts looks correct.

The signature matches what decodePaymentRequest expects.

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 null for non-EVM namespaces keeps callers honest about unsupported networks.

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: 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.

📥 Commits

Reviewing files that changed from the base of the PR and between e70f706 and 8402662.

📒 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 @/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/common.ts
  • packages/thirdweb/src/x402/schemas.ts
  • packages/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.ts
  • packages/thirdweb/src/x402/schemas.ts
  • packages/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 @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/common.ts
  • packages/thirdweb/src/x402/schemas.ts
  • packages/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.ts
  • packages/thirdweb/src/x402/schemas.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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.ts
  • packages/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)

Comment on lines 95 to 198
/**
* 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);
}
Copy link
Contributor

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.

@joaquim-verges joaquim-verges merged commit 8d17685 into main Nov 1, 2025
17 of 21 checks passed
@joaquim-verges joaquim-verges deleted the _X402_Refactor_payment_processing_to_use_facilitator.accepts branch November 1, 2025 01:38
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: 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: extractEvmChainId and networkToCaip2ChainId are public exports under packages/thirdweb, but their docblocks still lack the mandated compiling @example and 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 8402662 and c8fa393.

📒 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 @/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/common.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/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.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/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 @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/common.ts
  • packages/thirdweb/src/x402/facilitator.ts
  • packages/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.ts
  • 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/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)

Comment on lines 87 to 92
const selectedPaymentRequirements = paymentRequirements.find(
(value) =>
value.scheme === decodedPayment.scheme &&
networkToChainId(value.network) ===
networkToChainId(decodedPayment.network),
networkToCaip2ChainId(value.network) ===
networkToCaip2ChainId(decodedPayment.network),
);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

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).

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

Labels

packages SDK Involves changes to the thirdweb SDK

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants