@bosonprotocol/x402-server 0.1.0-alpha-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +65 -0
  3. package/dist/cjs/challenge/index.d.ts +64 -0
  4. package/dist/cjs/challenge/index.js +96 -0
  5. package/dist/cjs/challenge/index.js.map +1 -0
  6. package/dist/cjs/client-tnrpqVMW.d.ts +36 -0
  7. package/dist/cjs/config-CBr9qMps.d.ts +419 -0
  8. package/dist/cjs/facilitator/index.d.ts +26 -0
  9. package/dist/cjs/facilitator/index.js +136 -0
  10. package/dist/cjs/facilitator/index.js.map +1 -0
  11. package/dist/cjs/handlers/index.d.ts +267 -0
  12. package/dist/cjs/handlers/index.js +1182 -0
  13. package/dist/cjs/handlers/index.js.map +1 -0
  14. package/dist/cjs/index.d.ts +72 -0
  15. package/dist/cjs/index.js +1643 -0
  16. package/dist/cjs/index.js.map +1 -0
  17. package/dist/cjs/onchain/index.d.ts +73 -0
  18. package/dist/cjs/onchain/index.js +87 -0
  19. package/dist/cjs/onchain/index.js.map +1 -0
  20. package/dist/cjs/package.json +3 -0
  21. package/dist/cjs/validate/index.d.ts +67 -0
  22. package/dist/cjs/validate/index.js +429 -0
  23. package/dist/cjs/validate/index.js.map +1 -0
  24. package/dist/esm/challenge/index.js +3 -0
  25. package/dist/esm/challenge/index.js.map +1 -0
  26. package/dist/esm/chunk-4NQ3VKC3.js +84 -0
  27. package/dist/esm/chunk-4NQ3VKC3.js.map +1 -0
  28. package/dist/esm/chunk-CGVXQX5V.js +426 -0
  29. package/dist/esm/chunk-CGVXQX5V.js.map +1 -0
  30. package/dist/esm/chunk-DJMCSCBE.js +3 -0
  31. package/dist/esm/chunk-DJMCSCBE.js.map +1 -0
  32. package/dist/esm/chunk-EAKQ4EFZ.js +124 -0
  33. package/dist/esm/chunk-EAKQ4EFZ.js.map +1 -0
  34. package/dist/esm/chunk-GBPU373M.js +93 -0
  35. package/dist/esm/chunk-GBPU373M.js.map +1 -0
  36. package/dist/esm/chunk-PU5Y7FZG.js +14 -0
  37. package/dist/esm/chunk-PU5Y7FZG.js.map +1 -0
  38. package/dist/esm/chunk-WU7QJ7YP.js +3 -0
  39. package/dist/esm/chunk-WU7QJ7YP.js.map +1 -0
  40. package/dist/esm/chunk-Y5HFLCAT.js +657 -0
  41. package/dist/esm/chunk-Y5HFLCAT.js.map +1 -0
  42. package/dist/esm/facilitator/index.js +4 -0
  43. package/dist/esm/facilitator/index.js.map +1 -0
  44. package/dist/esm/handlers/index.js +6 -0
  45. package/dist/esm/handlers/index.js.map +1 -0
  46. package/dist/esm/index.js +261 -0
  47. package/dist/esm/index.js.map +1 -0
  48. package/dist/esm/onchain/index.js +4 -0
  49. package/dist/esm/onchain/index.js.map +1 -0
  50. package/dist/esm/package.json +3 -0
  51. package/dist/esm/validate/index.js +4 -0
  52. package/dist/esm/validate/index.js.map +1 -0
  53. package/package.json +88 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/internal/facilitator-endpoints.ts","../../src/handlers/next-actions.ts","../../src/handlers/types.ts","../../src/handlers/commit-and-redeem.ts","../../src/handlers/perform-action.ts","../../src/handlers/entity-input-validators.ts","../../src/handlers/resolve-entity.ts","../../src/handlers/withdraw-funds.ts","../../src/handlers/available-funds.ts"],"names":["ExchangeState"],"mappings":";;;;;;;;;AASA,IAAM,iBAAA,uBAAwB,GAAA,CAAI;AAAA,EAChC,4BAAA;AAAA,EACA;AACF,CAAC,CAAA;AAQM,SAAS,sBAAA,CAAuB,UAAkB,cAAA,EAAgC;AACvF,EAAA,MAAM,IAAA,GAAO,cAAA,CAAe,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC9C,EAAA,IAAI,iBAAA,CAAkB,GAAA,CAAI,QAAQ,CAAA,EAAG;AACnC,IAAA,OAAO,GAAG,IAAI,CAAA,OAAA,CAAA;AAAA,EAChB;AACA,EAAA,OAAO,CA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ACxC,QAAA;AAAA,IACA,GAAI,IAAA,KAAS,MAAA,GAAY,EAAE,IAAA,KAAS,EAAC;AAAA,IACrC;AAAA,GACD,CAAA;AACH;AAEA,SAAS,kBAAkB,QAAA,EAIc;AACvC,EAAA,IAAI,QAAA,CAAS,IAAA,KAAS,WAAA,EAAa,OAAO,MAAA;AAC1C,EAAA,MAAM,UAAoC,EAAC;AAC3C,EAAA,IAAI,QAAA,CAAS,SAAA,KAAc,MAAA,EAAW,OAAA,CAAQ,YAAY,QAAA,CAAS,SAAA;AACnE,EAAA,IAAI,QAAA,CAAS,QAAA,KAAa,MAAA,EAAW,OAAA,CAAQ,WAAW,QAAA,CAAS,QAAA;AACjE,EAAA,OAAO,OAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,GAAS,IAAI,OAAA,GAAU,MAAA;AACrD","file":"chunk-Y5HFLCAT.js","sourcesContent":["// Helpers for stamping `endpoints.facilitator` on every `NextAction`\n// entry that advertises the `facilitator` channel. Used both at the\n// 402 challenge (pre-commit `EscrowPaymentRequirements.actions.next`)\n// and on every post-commit `EscrowNextActions` envelope a handler\n// returns — keeping the URL-shape logic in one place so the two\n// surfaces can't drift.\n\nimport type { NextAction } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nconst COMMIT_ACTION_IDS = new Set([\n \"boson-createOfferAndCommit\",\n \"boson-createOfferCommitAndRedeem\",\n]);\n\n/**\n * Pick the facilitator endpoint URL for a given action id. Commit-time\n * actions route to `/settle`; every other action routes to\n * `/perform-action?action=<id>` so the facilitator can dispatch per\n * action without re-parsing the meta-tx calldata.\n */\nexport function facilitatorEndpointFor(actionId: string, facilitatorUrl: string): string {\n const base = facilitatorUrl.replace(/\\/+$/, \"\");\n if (COMMIT_ACTION_IDS.has(actionId)) {\n return `${base}/settle`;\n }\n return `${base}/perform-action?action=${encodeURIComponent(actionId)}`;\n}\n\n/**\n * Return a new `NextAction[]` with `endpoints.facilitator` stamped on\n * every entry that advertises the `facilitator` channel. Entries that\n * already carry an explicit `endpoints.facilitator` are left as-is\n * (the caller wins) — same for entries whose `channels` don't include\n * `\"facilitator\"`.\n */\nexport function stampFacilitatorEndpoints(\n next: readonly NextAction[],\n facilitatorUrl: string,\n): NextAction[] {\n return next.map((entry) => {\n if (!entry.channels.includes(\"facilitator\")) {\n return entry;\n }\n if (entry.endpoints?.facilitator !== undefined) {\n return entry;\n }\n return {\n ...entry,\n endpoints: {\n ...entry.endpoints,\n facilitator: facilitatorEndpointFor(entry.id, facilitatorUrl),\n },\n };\n });\n}\n","// `emitNextActions` — thin wrapper over `deriveNextActions` from\n// `@bosonprotocol/x402-actions`. Stamps the seller's per-action\n// `endpoints` / `channels` from the configured `ChannelRegistry`,\n// returns the discriminated `EscrowNextActions` shape (post-commit)\n// every convenience handler attaches to its response body.\n//\n// When the caller passes `facilitatorUrl`, the wrapper additionally\n// stamps `endpoints.facilitator` on every entry whose `channels`\n// include `\"facilitator\"` — matching the pre-commit behaviour in\n// `server.buildPaymentRequirements`. Without that stamp the buyer\n// sees `facilitator` advertised in `channels` but no URL to hit; the\n// channel is effectively dead.\n\nimport {\n deriveNextActions,\n DisputeState,\n ExchangeState,\n type ChannelRegistry,\n type EscrowNextActions,\n} from \"@bosonprotocol/x402-actions\";\n\nimport { stampFacilitatorEndpoints } from \"../internal/facilitator-endpoints.js\";\n\nexport type EmitNextActionsInput = {\n exchangeId: string;\n} & (\n | { exchangeState: Exclude<ExchangeState, typeof ExchangeState.DISPUTED>; disputeState?: never }\n | { exchangeState: typeof ExchangeState.DISPUTED; disputeState: DisputeState }\n);\n\n/**\n * Build the `nextActions` envelope a handler attaches to its 200 body.\n * Pure wrapper; the logic beyond `deriveNextActions` is the\n * `DISPUTED → disputeState required` narrowing and the optional\n * facilitator-endpoint stamp.\n */\nexport function emitNextActions(\n input: EmitNextActionsInput,\n registry: ChannelRegistry,\n facilitatorUrl?: string,\n): EscrowNextActions {\n const derived =\n input.exchangeState === ExchangeState.DISPUTED\n ? deriveNextActions(\n {\n exchangeId: input.exchangeId,\n exchangeState: ExchangeState.DISPUTED,\n disputeState: input.disputeState,\n },\n registry,\n )\n : deriveNextActions(\n { exchangeId: input.exchangeId, exchangeState: input.exchangeState },\n registry,\n );\n\n if (facilitatorUrl === undefined) {\n return derived;\n }\n\n return {\n ...derived,\n next: stampFacilitatorEndpoints(derived.next, facilitatorUrl),\n };\n}\n","// Shared result + error shapes for every convenience handler.\n//\n// Each handler returns a `HandlerResult<TBody>` whose `ok: true`\n// variant carries an HTTP-200 body augmented with the `nextActions`\n// envelope, and whose `ok: false` variant carries the suggested HTTP\n// status + a structured error body the framework adapter (PR 5) can\n// serialise into the response.\n\nimport type { EscrowNextActions } from \"@bosonprotocol/x402-actions\";\n\nexport type HandlerStatus = 200 | 400 | 402 | 404 | 409 | 500 | 502;\n\nexport type HandlerResult<TBody> =\n | { ok: true; status: 200; body: TBody & { nextActions: EscrowNextActions } }\n | { ok: false; status: Exclude<HandlerStatus, 200>; body: HandlerErrorBody };\n\n/**\n * Result shape for handlers whose success body does NOT carry a\n * `nextActions` envelope — used by entity-keyed actions\n * (`boson-withdrawFunds`) and the read-only `available-funds`\n * endpoint, neither of which advance the exchange state machine.\n */\nexport type PlainHandlerResult<TBody> =\n | { ok: true; status: 200; body: TBody }\n | { ok: false; status: Exclude<HandlerStatus, 200>; body: HandlerErrorBody };\n\nexport interface HandlerErrorBody {\n /** Stable identifier — caller branches on this rather than the human-readable `reason`. */\n code: string;\n reason: string;\n /** Optional rich detail — validator field/expected/got, facilitator code, etc. */\n details?: unknown;\n}\n\nexport interface HandlerWarning {\n /** Stable identifier — caller branches on this rather than the human-readable `reason`. */\n code: string;\n reason: string;\n /** Optional rich detail — tx hash, exchange id, deferred operation, etc. */\n details?: unknown;\n}\n\nexport function handlerOk<TBody>(\n body: TBody & { nextActions: EscrowNextActions },\n): HandlerResult<TBody> {\n return { ok: true, status: 200, body };\n}\n\nexport function plainHandlerOk<TBody>(body: TBody): PlainHandlerResult<TBody> {\n return { ok: true, status: 200, body };\n}\n\nexport function handlerErr(\n status: Exclude<HandlerStatus, 200>,\n code: string,\n reason: string,\n details?: unknown,\n): HandlerResult<never> & PlainHandlerResult<never> {\n const body: HandlerErrorBody = { code, reason };\n if (details !== undefined) body.details = details;\n return { ok: false, status, body };\n}\n","// Commit-time handlers — `handleCommit` (Flow A, post-state\n// COMMITTED) and `handleCommitAndRedeem` (Flow B, post-state\n// REDEEMED). Both decode `X-PAYMENT`, run the 13-rule validator,\n// forward the signed payload to the facilitator's `/settle`, verify\n// the resulting exchange snapshot, and emit a fresh `nextActions`\n// envelope.\n\nimport { ExchangeState } from \"@bosonprotocol/x402-actions\";\nimport type { EscrowPaymentRequirements } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { ActionId } from \"@bosonprotocol/x402-core/state-machine\";\n\nimport { emitNextActions } from \"./next-actions.js\";\nimport { handlerErr, handlerOk, type HandlerResult, type HandlerWarning } from \"./types.js\";\nimport { decodeXPaymentHeader } from \"../validate/decode.js\";\nimport { validatePaymentPayload } from \"../validate/payment-payload.js\";\nimport {\n verifyExchange,\n type ExchangeReader,\n type VerifyExchangeExpected,\n} from \"../onchain/verify-exchange.js\";\nimport type { FacilitatorClient } from \"../facilitator/client.js\";\nimport { FacilitatorHttpError } from \"../facilitator/errors.js\";\nimport type { FulfillmentRecoveryEntry, X402bServerConfig } from \"../config.js\";\n\nexport interface CommitHandlerInput {\n /** Raw `X-PAYMENT` header value (base64'd JSON). */\n paymentHeader: string | undefined | null;\n /** The 402 `PaymentRequirements` the buyer is responding to. */\n requirements: EscrowPaymentRequirements;\n}\n\nexport interface CommitHandlerContext {\n config: X402bServerConfig;\n facilitator: FacilitatorClient;\n exchangeReader: ExchangeReader;\n fulfillmentRecoveryStore: Map<string, FulfillmentRecoveryEntry>;\n /**\n * Per-exchange fulfillment option policy. Flow A writes the ids\n * advertised by the original requirements so the redeem-time choice\n * is constrained to the offer's own channel set.\n */\n exchangeFulfillmentOptionStore: Map<string, readonly string[]>;\n}\n\nexport interface CommitOk {\n exchangeId: string;\n txHash: string;\n /**\n * Non-fatal post-settle conditions. Today only Flow B uses this slot —\n * the on-chain redeem may have succeeded while the configured channel\n * adapter's `onCommit(...)` failed (the buyer's funds and voucher are\n * already gone; the seller's host needs to recover the delivery target\n * out-of-band). The exchange state is the wire-format source of truth;\n * warnings are advisory.\n */\n warnings?: HandlerWarning[];\n}\n\n/**\n * Flow A — `boson-createOfferAndCommit`. Settles via facilitator,\n * expects the resulting exchange in `COMMITTED`, returns 200 with\n * `nextActions` advertising the legal post-COMMITTED transitions.\n */\nexport async function handleCommit(\n input: CommitHandlerInput,\n ctx: CommitHandlerContext,\n): Promise<HandlerResult<CommitOk>> {\n return await handleCommitImpl(input, ctx, {\n expectedAction: \"boson-createOfferAndCommit\",\n expectedState: ExchangeState.COMMITTED,\n });\n}\n\n/**\n * Flow B — `boson-createOfferCommitAndRedeem`. Same pipeline as\n * `handleCommit` but verifies the exchange reached `REDEEMED`.\n */\nexport async function handleCommitAndRedeem(\n input: CommitHandlerInput,\n ctx: CommitHandlerContext,\n): Promise<HandlerResult<CommitOk>> {\n return await handleCommitImpl(input, ctx, {\n expectedAction: \"boson-createOfferCommitAndRedeem\",\n expectedState: ExchangeState.REDEEMED,\n });\n}\n\nasync function handleCommitImpl(\n input: CommitHandlerInput,\n ctx: CommitHandlerContext,\n expected: { expectedAction: ActionId; expectedState: ExchangeState },\n): Promise<HandlerResult<CommitOk>> {\n const decoded = decodeXPaymentHeader(input.paymentHeader);\n if (!decoded.ok) {\n const status = decoded.code === \"MISSING_HEADER\" ? 402 : 400;\n return handlerErr(status, decoded.code, decoded.reason);\n }\n if (decoded.payload.payload.action !== expected.expectedAction) {\n return handlerErr(\n 400,\n \"ACTION_ROUTE_MISMATCH\",\n `handler expected action ${expected.expectedAction}, got ${decoded.payload.payload.action}`,\n {\n expected: expected.expectedAction,\n got: decoded.payload.payload.action,\n },\n );\n }\n\n // For atomic Flow B the validator needs a per-channel data validator\n // so it can reject malformed buyer data before the on-chain redeem\n // happens. Flow A doesn't carry `fulfillment.data` at commit time so\n // the validator never invokes this callback; pass it anyway and let\n // rule 13 dispatch on `payload.action`.\n const channels = ctx.config.fulfillmentChannels ?? [];\n const channelById = new Map(channels.map((c) => [c.id, c]));\n const validation = await validatePaymentPayload({\n payload: decoded.payload,\n requirements: input.requirements,\n chainId: ctx.config.chainId,\n validateFulfillmentData: (option, data) => {\n const channel = channelById.get(option);\n if (channel === undefined) {\n return {\n ok: false,\n reason: `fulfillment.option '${option}' has no registered channel adapter on this server`,\n };\n }\n try {\n return channel.validate(data);\n } catch (e) {\n return { ok: false, reason: e instanceof Error ? e.message : String(e) };\n }\n },\n });\n if (!validation.ok) {\n return handlerErr(400, validation.code, validation.reason ?? `rule ${validation.rule} failed`, {\n rule: validation.rule,\n field: validation.field,\n expected: validation.expected,\n got: validation.got,\n });\n }\n\n let settleResult: Awaited<ReturnType<FacilitatorClient[\"settle\"]>>;\n try {\n settleResult = await ctx.facilitator.settle({\n scheme: \"escrow\",\n network: input.requirements.network,\n payload: decoded.payload,\n requirements: input.requirements,\n });\n } catch (e) {\n if (e instanceof FacilitatorHttpError) {\n return handlerErr(502, \"FACILITATOR_UNREACHABLE\", e.message, {\n code: e.code,\n status: e.status,\n facilitatorCode: e.facilitatorCode,\n });\n }\n throw e;\n }\n\n if (!settleResult.ok) {\n return handlerErr(502, \"FACILITATOR_REJECTED\", settleResult.reason, {\n facilitatorCode: settleResult.code,\n });\n }\n\n const verifyResult = await verifyExchange(\n ctx.exchangeReader,\n settleResult.exchangeId,\n buildExpectedFromRequirements(input.requirements, expected.expectedState),\n );\n if (!verifyResult.ok) {\n return handlerErr(\n 502,\n `STATE_VERIFY_${verifyResult.code}`,\n \"post-settle state verification failed\",\n {\n exchangeId: settleResult.exchangeId,\n txHash: settleResult.txHash,\n field: verifyResult.field,\n expected: verifyResult.expected,\n got: verifyResult.got,\n },\n );\n }\n\n // Flow A only: persist the *advertised* option ids from the original\n // 402 so the redeem handler can constrain the buyer's redeem-time\n // fulfillment choice to the offer's own channel set. Flow B is\n // already in REDEEMED — there is no later redeem step to gate.\n if (expected.expectedState === ExchangeState.COMMITTED) {\n ctx.exchangeFulfillmentOptionStore.set(\n settleResult.exchangeId,\n input.requirements.fulfillment?.options.map((option) => option.id) ?? [],\n );\n }\n\n // Flow B only: the buyer's delivery data rides along with the\n // commit-time payload because atomic redeem leaves no later round\n // trip for it. The on-chain redeem has already settled at this\n // point; channel persistence is best-effort and surfaces as a\n // warning on failure (the buyer's funds + voucher are irreversibly\n // committed regardless). Record a pending update before the channel\n // write so the host can recover if the write fails after redeem.\n const warnings: HandlerWarning[] = [];\n if (\n expected.expectedState === ExchangeState.REDEEMED &&\n decoded.payload.fulfillment !== undefined &&\n decoded.payload.fulfillment.data !== undefined\n ) {\n const pending: FulfillmentRecoveryEntry = {\n exchangeId: settleResult.exchangeId,\n option: decoded.payload.fulfillment.option,\n data: decoded.payload.fulfillment.data,\n redeemer: decoded.payload.payload.buyer,\n recordedAt: Date.now(),\n };\n ctx.fulfillmentRecoveryStore.set(settleResult.exchangeId, pending);\n\n const channel = channelById.get(decoded.payload.fulfillment.option);\n if (channel === undefined) {\n const reason = \"no channel adapter is registered\";\n ctx.fulfillmentRecoveryStore.set(settleResult.exchangeId, {\n ...pending,\n error: reason,\n });\n // Validation should have caught this (rule 13 rejects an option\n // with no registered adapter). Surface a warning rather than\n // silently dropping the data if it slips past.\n warnings.push({\n code: \"FULFILLMENT_COMMIT_DEFERRED\",\n reason: \"atomic redeem succeeded on-chain, but no channel adapter is registered\",\n details: {\n exchangeId: settleResult.exchangeId,\n option: decoded.payload.fulfillment.option,\n error: reason,\n },\n });\n } else {\n try {\n await channel.onCommit(settleResult.exchangeId, decoded.payload.fulfillment.data);\n ctx.fulfillmentRecoveryStore.delete(settleResult.exchangeId);\n } catch (e) {\n const reason = e instanceof Error ? e.message : String(e);\n ctx.fulfillmentRecoveryStore.set(settleResult.exchangeId, {\n ...pending,\n error: reason,\n });\n warnings.push({\n code: \"FULFILLMENT_COMMIT_DEFERRED\",\n reason: \"atomic redeem succeeded on-chain, but the channel adapter rejected the data\",\n details: {\n exchangeId: settleResult.exchangeId,\n option: decoded.payload.fulfillment.option,\n error: reason,\n },\n });\n }\n }\n }\n\n // Both commit-side actions transition to non-DISPUTED states\n // (COMMITTED for Flow A, REDEEMED for Flow B), so the cast to\n // `Exclude<ExchangeState, DISPUTED>` is sound — the function only\n // narrows `expected.expectedState` itself which is typed loosely as\n // `ExchangeState` for shared use by both wrappers.\n const nextActions = emitNextActions(\n {\n exchangeId: settleResult.exchangeId,\n exchangeState: expected.expectedState as Exclude<\n ExchangeState,\n typeof ExchangeState.DISPUTED\n >,\n },\n ctx.config.channelRegistry,\n ctx.config.facilitator.url,\n );\n return handlerOk({\n exchangeId: settleResult.exchangeId,\n txHash: settleResult.txHash,\n nextActions,\n ...(warnings.length > 0 ? { warnings } : {}),\n });\n}\n\nfunction buildExpectedFromRequirements(\n requirements: EscrowPaymentRequirements,\n state: ExchangeState,\n): VerifyExchangeExpected {\n return {\n state,\n seller: requirements.offer.creator,\n exchangeToken: requirements.asset,\n price: requirements.amount,\n };\n}\n","// Convenience handlers for the post-commit actions — `redeem`,\n// `complete`, and the four dispute transitions. Each is a thin\n// wrapper over the facilitator's `/perform-action` endpoint:\n// forward the buyer- or seller-signed payload, verify the resulting\n// exchange snapshot reaches the action's `ACTION_POST_STATE`, emit\n// fresh `nextActions`.\n\nimport { ExchangeState } from \"@bosonprotocol/x402-actions\";\nimport type { Address } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport { ACTION_POST_STATE, type ExchangeActionId } from \"@bosonprotocol/x402-core/state-machine\";\nimport { decodeSignedPayload } from \"@bosonprotocol/x402-evm\";\nimport type { Hex } from \"viem\";\n\nimport { emitNextActions } from \"./next-actions.js\";\nimport { handlerErr, handlerOk, type HandlerResult, type HandlerWarning } from \"./types.js\";\nimport type { FacilitatorClient } from \"../facilitator/client.js\";\nimport { FacilitatorHttpError } from \"../facilitator/errors.js\";\nimport type {\n FulfillmentRecoveryEntry,\n RedeemFulfillmentChannel,\n X402bServerConfig,\n} from \"../config.js\";\nimport {\n verifyExchange,\n type ExchangeReader,\n type VerifyExchangeExpected,\n} from \"../onchain/verify-exchange.js\";\n\n/** Per-action inputs accepted by every post-commit convenience handler. */\nexport interface PerformActionInput {\n exchangeId: string;\n /** ABI-encoded `BosonMetaTx` tuple — see `encodeSignedPayload` in `@bosonprotocol/x402-facilitator`. */\n signedPayload: Hex;\n}\n\n/**\n * Redeem-time variant of `PerformActionInput`. Carries the buyer's\n * `fulfillment` selection for Flow A — `data` is the delivery target\n * the redeem-time channel adapter persists. Required when the\n * original 402 advertised `fulfillment.required = true`; omitted\n * otherwise.\n */\nexport interface RedeemHandlerInput extends PerformActionInput {\n fulfillment?: { option: string; data: Record<string, unknown> | null };\n}\n\nexport interface PerformActionContext {\n config: X402bServerConfig;\n facilitator: FacilitatorClient;\n exchangeReader: ExchangeReader;\n}\n\nexport interface RedeemHandlerContext extends PerformActionContext {\n exchangeFulfillmentOptionStore: Map<string, readonly string[]>;\n fulfillmentRecoveryStore: Map<string, FulfillmentRecoveryEntry>;\n}\n\nexport interface PerformActionOk {\n txHash: string;\n warnings?: HandlerWarning[];\n}\n\n/**\n * Generic exchange-keyed post-commit handler — wired from each of the\n * per-action wrappers below. Entity-keyed actions (e.g. `withdrawFunds`)\n * have their own handler in `./withdraw-funds.ts`.\n */\nexport async function handlePerformAction(\n action: ExchangeActionId,\n input: PerformActionInput,\n ctx: PerformActionContext,\n): Promise<HandlerResult<PerformActionOk>> {\n const reference = await ctx.exchangeReader.read(input.exchangeId);\n if (reference === null) {\n return handlerErr(\n 502,\n \"STATE_VERIFY_EXCHANGE_NOT_FOUND\",\n \"pre-action exchange reference could not be read\",\n { action, exchangeId: input.exchangeId },\n );\n }\n\n let result: Awaited<ReturnType<FacilitatorClient[\"performAction\"]>>;\n try {\n result = await ctx.facilitator.performAction({\n network: ctx.config.network,\n escrowAddress: ctx.config.escrow,\n exchangeId: input.exchangeId,\n action,\n signedPayload: input.signedPayload,\n });\n } catch (e) {\n if (e instanceof FacilitatorHttpError) {\n return handlerErr(502, \"FACILITATOR_UNREACHABLE\", e.message, {\n code: e.code,\n status: e.status,\n facilitatorCode: e.facilitatorCode,\n });\n }\n throw e;\n }\n\n if (!result.ok) {\n return handlerErr(502, \"FACILITATOR_REJECTED\", result.reason, {\n facilitatorCode: result.code,\n });\n }\n\n const postState = ACTION_POST_STATE[action];\n const expected: VerifyExchangeExpected = {\n state: postState.exchange,\n ...(postState.dispute !== undefined ? { disputeState: postState.dispute } : {}),\n seller: reference.seller,\n exchangeToken: reference.exchangeToken,\n price: reference.price,\n };\n const verifyResult = await verifyExchange(ctx.exchangeReader, input.exchangeId, expected);\n if (!verifyResult.ok) {\n return handlerErr(\n 502,\n `STATE_VERIFY_${verifyResult.code}`,\n \"post-action state verification failed\",\n {\n action,\n exchangeId: input.exchangeId,\n txHash: result.txHash,\n field: verifyResult.field,\n expected: verifyResult.expected,\n got: verifyResult.got,\n },\n );\n }\n\n const nextActions =\n postState.exchange === ExchangeState.DISPUTED && postState.dispute !== undefined\n ? emitNextActions(\n {\n exchangeId: input.exchangeId,\n exchangeState: ExchangeState.DISPUTED,\n disputeState: postState.dispute,\n },\n ctx.config.channelRegistry,\n ctx.config.facilitator.url,\n )\n : emitNextActions(\n {\n exchangeId: input.exchangeId,\n exchangeState: postState.exchange as Exclude<\n ExchangeState,\n typeof ExchangeState.DISPUTED\n >,\n },\n ctx.config.channelRegistry,\n ctx.config.facilitator.url,\n );\n\n return handlerOk({ txHash: result.txHash, nextActions });\n}\n\n/**\n * Redeem handler. Validates the buyer's `fulfillment` selection (if\n * present) against the offer's advertised option set and the host's\n * channel registry, runs the channel's `validate` up-front, then\n * forwards to the facilitator. The corresponding\n * `onCommit(exchangeId, data)` upsert is deferred until *after* the\n * facilitator + state verification confirm the exchange reached\n * `REDEEMED`, so a failed redeem leaves the stored delivery target\n * unchanged. The voucher NFT is transferable; whichever wallet signs\n * `boson-redeem` supplies the delivery data — it's the redeemer's\n * choice end-to-end.\n */\nexport async function handleRedeem(\n input: RedeemHandlerInput,\n ctx: RedeemHandlerContext,\n): Promise<HandlerResult<PerformActionOk>> {\n let redeemer: Address;\n try {\n redeemer = decodeSignedPayload(input.signedPayload).from as Address;\n } catch (e) {\n return handlerErr(\n 400,\n \"SIGNED_PAYLOAD_DECODE_FAILED\",\n e instanceof Error ? e.message : \"signedPayload could not be decoded\",\n );\n }\n\n let resolvedChannel: RedeemFulfillmentChannel | undefined;\n if (input.fulfillment !== undefined) {\n const advertisedOptions = ctx.exchangeFulfillmentOptionStore.get(input.exchangeId);\n if (advertisedOptions !== undefined && !advertisedOptions.includes(input.fulfillment.option)) {\n return handlerErr(\n 400,\n \"FULFILLMENT_OPTION_NOT_ADVERTISED\",\n `fulfillment.option '${input.fulfillment.option}' was not advertised for this exchange`,\n { option: input.fulfillment.option, advertised: advertisedOptions },\n );\n }\n\n const channels = ctx.config.fulfillmentChannels;\n if (channels === undefined) {\n return handlerErr(\n 400,\n \"FULFILLMENT_CHANNELS_NOT_CONFIGURED\",\n \"server received redeem-time fulfillment data but has no fulfillmentChannels registered\",\n );\n }\n const channel = channels.find((c) => c.id === input.fulfillment!.option);\n if (channel === undefined) {\n return handlerErr(\n 400,\n \"FULFILLMENT_OPTION_UNKNOWN\",\n `fulfillment.option '${input.fulfillment.option}' is not registered with the server`,\n { option: input.fulfillment.option, registered: channels.map((c) => c.id) },\n );\n }\n // Host-supplied `validate` callbacks are arbitrary code — treat a\n // thrown error the same as `{ ok: false }` so a buggy / strict\n // adapter surfaces as a 400 the buyer can correct, not a 500.\n let validation: ReturnType<RedeemFulfillmentChannel[\"validate\"]>;\n try {\n validation = channel.validate(input.fulfillment.data);\n } catch (e) {\n return handlerErr(400, \"FULFILLMENT_DATA_INVALID\", errorMessage(e), {\n option: input.fulfillment.option,\n });\n }\n if (!validation.ok) {\n return handlerErr(400, \"FULFILLMENT_DATA_INVALID\", validation.reason, {\n option: input.fulfillment.option,\n });\n }\n resolvedChannel = channel;\n }\n\n const result = await handlePerformAction(\"boson-redeem\", input, ctx);\n if (!result.ok) return result;\n\n // Redeem confirmed REDEEMED on-chain — only now is it safe to\n // upsert the channel's delivery-target store. Record a pending\n // update first so a failing channel write leaves the host with an\n // explicit recovery item instead of losing the buyer's target.\n let warning: HandlerWarning | undefined;\n if (resolvedChannel !== undefined && input.fulfillment !== undefined) {\n const pending: FulfillmentRecoveryEntry = {\n exchangeId: input.exchangeId,\n option: input.fulfillment.option,\n data: input.fulfillment.data,\n redeemer,\n recordedAt: Date.now(),\n };\n ctx.fulfillmentRecoveryStore.set(input.exchangeId, pending);\n try {\n await resolvedChannel.onCommit(input.exchangeId, input.fulfillment.data);\n ctx.fulfillmentRecoveryStore.delete(input.exchangeId);\n } catch (e) {\n const reason = errorMessage(e);\n ctx.fulfillmentRecoveryStore.set(input.exchangeId, { ...pending, error: reason });\n warning = {\n code: \"FULFILLMENT_UPDATE_DEFERRED\",\n reason:\n \"redeem succeeded on-chain, but the server could not persist the fulfillment update\",\n details: {\n exchangeId: input.exchangeId,\n option: input.fulfillment.option,\n error: reason,\n },\n };\n }\n }\n\n // The exchange is REDEEMED even if the fulfillment write is deferred;\n // the per-exchange option-policy entry is no longer consulted.\n ctx.exchangeFulfillmentOptionStore.delete(input.exchangeId);\n\n if (warning !== undefined) {\n return {\n ...result,\n body: {\n ...result.body,\n warnings: [...(result.body.warnings ?? []), warning],\n },\n };\n }\n\n return result;\n}\n\nfunction errorMessage(e: unknown): string {\n return e instanceof Error ? e.message : String(e);\n}\n\n/** Per-action sugar — preserves the action id at the type level. */\nexport const handleComplete = (input: PerformActionInput, ctx: PerformActionContext) =>\n handlePerformAction(\"boson-completeExchange\", input, ctx);\nexport const handleDisputeRaise = (input: PerformActionInput, ctx: PerformActionContext) =>\n handlePerformAction(\"boson-raiseDispute\", input, ctx);\nexport const handleDisputeResolve = (input: PerformActionInput, ctx: PerformActionContext) =>\n handlePerformAction(\"boson-resolveDispute\", input, ctx);\nexport const handleDisputeRetract = (input: PerformActionInput, ctx: PerformActionContext) =>\n handlePerformAction(\"boson-retractDispute\", input, ctx);\nexport const handleDisputeEscalate = (input: PerformActionInput, ctx: PerformActionContext) =>\n handlePerformAction(\"boson-escalateDispute\", input, ctx);\n","// Shared input-shape regexes for the entity-keyed handlers\n// (`handleWithdrawFunds`, `handleGetAvailableFunds`, the express\n// adapter routes). Centralised here so the wire-level validation stays\n// consistent across endpoints — drift between two copies is exactly\n// the kind of bug that lets a malformed request slip through one\n// route's check but trip a deeper layer with a less precise error.\n//\n// `DECIMAL_UINT` and `ADDRESS` are sourced from `@bosonprotocol/x402-core`'s\n// `schemes/escrow` validators (the JSON-Schema-aligned canonical\n// definitions); re-exported under the local `_RE` alias to keep the\n// existing call sites stable.\n\nimport { ADDRESS, DECIMAL_UINT } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\n/** Boson account `entityId` — uint256 in decimal-string form, no leading zeros. */\nexport const DECIMAL_UINT_RE = DECIMAL_UINT;\n\n/** 20-byte EVM address, 0x-prefixed, any letter case (we normalise downstream). */\nexport const ADDRESS_RE = ADDRESS;\n\n/**\n * Hex-string check for `signedPayload`. Requires `0x` followed by an\n * *even* number of hex digits so the body decodes to whole bytes —\n * odd-length payloads like `0xabc` would surface as\n * `signedPayload decode failed: …` deep in the facilitator pipeline,\n * which is a less precise 502 than the adapter-level 400 this regex\n * catches. Stricter than core's `HEX_BYTES` (which permits odd\n * lengths) so we keep this one local.\n */\nexport const HEX_BYTES_RE = /^0x([0-9a-fA-F]{2})*$/;\n","// Resolve an EVM address to a Boson Protocol `entityId` (seller or\n// buyer) via the core-sdk subgraph helpers.\n//\n// `coreSdk.getSellersByAddress(addr)` matches any of the four seller\n// roles (admin / assistant / clerk / treasury); `coreSdk.getBuyers({\n// buyersFilter: { wallet: addr.toLowerCase() } })` covers buyer-side.\n// There is no single-call helper that returns \"the entityId for this\n// wallet\"; we call both in parallel and disambiguate.\n//\n// Both branches can also legitimately return *multiple* entities for\n// one address — one wallet can be the admin of several Boson sellers,\n// for example. When that happens we refuse to guess: the caller must\n// re-issue with an explicit `entityId` so the withdraw signature\n// commits to a single account.\n\nimport type { CoreSdkReadAdapter } from \"../onchain/core-sdk-read.js\";\n\nexport interface ResolveEntityInput {\n address: string;\n role?: \"buyer\" | \"seller\";\n}\n\nexport interface ResolveEntityOk {\n ok: true;\n entityId: string;\n role: \"buyer\" | \"seller\";\n}\n\nexport type ResolveEntityError =\n | { ok: false; code: \"NOT_FOUND\"; reason: string }\n | {\n ok: false;\n code: \"AMBIGUOUS\";\n reason: string;\n /** Seller ids matching the address (one or many). Absent when no sellers matched. */\n sellerIds?: string[];\n /** Buyer ids matching the address (one or many). Absent when no buyers matched. */\n buyerIds?: string[];\n }\n | { ok: false; code: \"SUBGRAPH_FAILURE\"; reason: string };\n\nexport type ResolveEntityResult = ResolveEntityOk | ResolveEntityError;\n\nexport async function resolveEntityId(\n coreSdk: CoreSdkReadAdapter,\n input: ResolveEntityInput,\n): Promise<ResolveEntityResult> {\n const address = input.address.toLowerCase();\n\n let sellers: { id: string }[] = [];\n let buyers: { id: string }[] = [];\n try {\n [sellers, buyers] = await Promise.all([\n input.role === \"buyer\" ? Promise.resolve([]) : coreSdk.getSellersByAddress(address),\n input.role === \"seller\"\n ? Promise.resolve([])\n : coreSdk.getBuyers({ buyersFilter: { wallet: address } }),\n ]);\n } catch (e) {\n return {\n ok: false,\n code: \"SUBGRAPH_FAILURE\",\n reason: e instanceof Error ? e.message : \"subgraph lookup failed\",\n };\n }\n\n const sellerIds = sellers.map((s) => s.id);\n const buyerIds = buyers.map((b) => b.id);\n\n if (input.role === \"seller\") {\n if (sellerIds.length === 0) {\n return {\n ok: false,\n code: \"NOT_FOUND\",\n reason: `no seller entity found for address ${address}`,\n };\n }\n if (sellerIds.length > 1) {\n return {\n ok: false,\n code: \"AMBIGUOUS\",\n reason: `address ${address} resolves to multiple seller entities (ids ${sellerIds.join(\", \")}); pass entityId to disambiguate`,\n sellerIds,\n };\n }\n return { ok: true, entityId: sellerIds[0]!, role: \"seller\" };\n }\n if (input.role === \"buyer\") {\n if (buyerIds.length === 0) {\n return {\n ok: false,\n code: \"NOT_FOUND\",\n reason: `no buyer entity found for address ${address}`,\n };\n }\n if (buyerIds.length > 1) {\n return {\n ok: false,\n code: \"AMBIGUOUS\",\n reason: `address ${address} resolves to multiple buyer entities (ids ${buyerIds.join(\", \")}); pass entityId to disambiguate`,\n buyerIds,\n };\n }\n return { ok: true, entityId: buyerIds[0]!, role: \"buyer\" };\n }\n\n // role unspecified — exactly-one rule across both sides.\n const totalMatches = sellerIds.length + buyerIds.length;\n if (totalMatches === 0) {\n return {\n ok: false,\n code: \"NOT_FOUND\",\n reason: `no seller or buyer entity found for address ${address}`,\n };\n }\n if (totalMatches > 1) {\n return {\n ok: false,\n code: \"AMBIGUOUS\",\n reason: `address ${address} resolves to ${describeMatches(sellerIds, buyerIds)}; pass role and/or entityId to disambiguate`,\n ...(sellerIds.length > 0 ? { sellerIds } : {}),\n ...(buyerIds.length > 0 ? { buyerIds } : {}),\n };\n }\n if (sellerIds.length === 1) return { ok: true, entityId: sellerIds[0]!, role: \"seller\" };\n return { ok: true, entityId: buyerIds[0]!, role: \"buyer\" };\n}\n\nfunction describeMatches(sellerIds: string[], buyerIds: string[]): string {\n const parts: string[] = [];\n if (sellerIds.length > 0) {\n parts.push(\n sellerIds.length === 1\n ? `seller (id ${sellerIds[0]})`\n : `${sellerIds.length} sellers (ids ${sellerIds.join(\", \")})`,\n );\n }\n if (buyerIds.length > 0) {\n parts.push(\n buyerIds.length === 1\n ? `buyer (id ${buyerIds[0]})`\n : `${buyerIds.length} buyers (ids ${buyerIds.join(\", \")})`,\n );\n }\n return parts.join(\" and \");\n}\n","// Convenience handler for the entity-keyed `boson-withdrawFunds`\n// action. The buyer or seller signs an EIP-712 meta-tx for\n// `withdrawFunds(uint256 entityId, address[] tokenList, uint256[] tokenAmounts)`;\n// the server forwards the signed payload to the facilitator and\n// returns the resulting tx hash.\n//\n// Unlike the exchange-keyed `handlePerformAction`, this handler:\n// - takes an `entityId` (or an `address` + optional `role`) instead\n// of an `exchangeId`,\n// - skips the post-action `exchangeReader.read` + `verifyExchange`\n// step (the action doesn't transition the exchange state machine),\n// - returns just `{ txHash, entityId, role? }` — no `nextActions`\n// envelope (withdraw is deliberately absent from `next[]`).\n\nimport type { Address } from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Hex } from \"viem\";\n\nimport type { X402bServerConfig } from \"../config.js\";\nimport type { FacilitatorClient } from \"../facilitator/client.js\";\nimport { FacilitatorHttpError } from \"../facilitator/errors.js\";\nimport type { CoreSdkReadAdapter } from \"../onchain/core-sdk-read.js\";\nimport { ADDRESS_RE, DECIMAL_UINT_RE } from \"./entity-input-validators.js\";\nimport { resolveEntityId } from \"./resolve-entity.js\";\nimport { handlerErr, plainHandlerOk, type PlainHandlerResult } from \"./types.js\";\n\nexport interface WithdrawFundsBaseInput {\n /** ABI-encoded `BosonMetaTx` tuple — see `encodeSignedPayload` in `@bosonprotocol/x402-evm/codec`. */\n signedPayload: Hex;\n}\n\nexport type WithdrawFundsInput = WithdrawFundsBaseInput &\n ({ entityId: string } | { address: string; role?: \"buyer\" | \"seller\" });\n\nexport interface WithdrawFundsContext {\n config: X402bServerConfig;\n facilitator: FacilitatorClient;\n coreSdkRead: CoreSdkReadAdapter;\n}\n\nexport interface WithdrawFundsOk {\n txHash: string;\n entityId: string;\n role?: \"buyer\" | \"seller\";\n}\n\nexport async function handleWithdrawFunds(\n input: WithdrawFundsInput,\n ctx: WithdrawFundsContext,\n): Promise<PlainHandlerResult<WithdrawFundsOk>> {\n let entityId: string;\n let role: \"buyer\" | \"seller\" | undefined;\n\n if (\"entityId\" in input) {\n if (!DECIMAL_UINT_RE.test(input.entityId)) {\n return handlerErr(\n 400,\n \"INVALID_ENTITY_ID\",\n `entityId must be a decimal uint256 string, got \"${input.entityId}\"`,\n );\n }\n entityId = input.entityId;\n } else {\n if (!ADDRESS_RE.test(input.address)) {\n return handlerErr(\n 400,\n \"INVALID_ADDRESS\",\n `address must be a 20-byte 0x-prefixed hex string, got \"${input.address}\"`,\n );\n }\n const resolved = await resolveEntityId(ctx.coreSdkRead, {\n address: input.address,\n ...(input.role !== undefined ? { role: input.role } : {}),\n });\n if (!resolved.ok) {\n const status =\n resolved.code === \"NOT_FOUND\" ? 404 : resolved.code === \"AMBIGUOUS\" ? 409 : 502;\n const details =\n resolved.code === \"AMBIGUOUS\"\n ? {\n ...(resolved.sellerIds !== undefined ? { sellerIds: resolved.sellerIds } : {}),\n ...(resolved.buyerIds !== undefined ? { buyerIds: resolved.buyerIds } : {}),\n }\n : undefined;\n return handlerErr(status, resolved.code, resolved.reason, details);\n }\n entityId = resolved.entityId;\n role = resolved.role;\n }\n\n let result: Awaited<ReturnType<FacilitatorClient[\"performAction\"]>>;\n try {\n result = await ctx.facilitator.performAction({\n network: ctx.config.network,\n escrowAddress: ctx.config.escrow as Address,\n entityId,\n action: \"boson-withdrawFunds\",\n signedPayload: input.signedPayload,\n });\n } catch (e) {\n if (e instanceof FacilitatorHttpError) {\n return handlerErr(502, \"FACILITATOR_UNREACHABLE\", e.message, {\n code: e.code,\n status: e.status,\n facilitatorCode: e.facilitatorCode,\n });\n }\n throw e;\n }\n\n if (!result.ok) {\n return handlerErr(502, \"FACILITATOR_REJECTED\", result.reason, {\n facilitatorCode: result.code,\n });\n }\n\n return plainHandlerOk<WithdrawFundsOk>({\n txHash: result.txHash,\n entityId,\n ...(role !== undefined ? { role } : {}),\n });\n}\n","// Read-only handler returning a Boson entity's currently available\n// funds. Backed by `coreSdk.getFunds` against the protocol subgraph.\n//\n// Accepts either a raw `entityId` (the protocol's own numeric id) or an\n// EVM `address` (with optional `role` to disambiguate when the address\n// is registered as both a seller and a buyer).\n\nimport type { Address } from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport type { CoreSdkReadAdapter } from \"../onchain/core-sdk-read.js\";\nimport { ADDRESS_RE, DECIMAL_UINT_RE } from \"./entity-input-validators.js\";\nimport { handlerErr, plainHandlerOk, type PlainHandlerResult } from \"./types.js\";\nimport { resolveEntityId } from \"./resolve-entity.js\";\n\nexport interface AvailableFundsEntry {\n tokenAddress: Address;\n tokenSymbol: string;\n tokenName: string;\n decimals: number;\n availableAmount: string;\n}\n\nexport interface AvailableFundsBody {\n entityId: string;\n /** Present when the caller looked up by `address`; omitted when looked up by `entityId`. */\n role?: \"buyer\" | \"seller\";\n funds: AvailableFundsEntry[];\n}\n\nexport type AvailableFundsQuery =\n | { entityId: string }\n | { address: string; role?: \"buyer\" | \"seller\" };\n\nexport interface AvailableFundsContext {\n coreSdkRead: CoreSdkReadAdapter;\n}\n\nexport async function handleGetAvailableFunds(\n query: AvailableFundsQuery,\n ctx: AvailableFundsContext,\n): Promise<PlainHandlerResult<AvailableFundsBody>> {\n let entityId: string;\n let role: \"buyer\" | \"seller\" | undefined;\n\n if (\"entityId\" in query) {\n if (!DECIMAL_UINT_RE.test(query.entityId)) {\n return handlerErr(\n 400,\n \"INVALID_ENTITY_ID\",\n `entityId must be a decimal uint256 string, got \"${query.entityId}\"`,\n );\n }\n entityId = query.entityId;\n } else {\n if (!ADDRESS_RE.test(query.address)) {\n return handlerErr(\n 400,\n \"INVALID_ADDRESS\",\n `address must be a 20-byte 0x-prefixed hex string, got \"${query.address}\"`,\n );\n }\n const resolved = await resolveEntityId(ctx.coreSdkRead, {\n address: query.address,\n ...(query.role !== undefined ? { role: query.role } : {}),\n });\n if (!resolved.ok) {\n const status =\n resolved.code === \"NOT_FOUND\" ? 404 : resolved.code === \"AMBIGUOUS\" ? 409 : 502;\n return handlerErr(status, resolved.code, resolved.reason, omitErrorMetadata(resolved));\n }\n entityId = resolved.entityId;\n role = resolved.role;\n }\n\n let raw;\n try {\n raw = await ctx.coreSdkRead.getFunds({ fundsFilter: { accountId: entityId } });\n } catch (e) {\n return handlerErr(\n 502,\n \"SUBGRAPH_FAILURE\",\n e instanceof Error ? e.message : \"subgraph getFunds lookup failed\",\n );\n }\n\n const funds: AvailableFundsEntry[] = raw.map((entry) => ({\n tokenAddress: entry.token.address as Address,\n tokenSymbol: entry.token.symbol,\n tokenName: entry.token.name,\n decimals: Number(entry.token.decimals),\n availableAmount: entry.availableAmount,\n }));\n\n return plainHandlerOk<AvailableFundsBody>({\n entityId,\n ...(role !== undefined ? { role } : {}),\n funds,\n });\n}\n\nfunction omitErrorMetadata(resolved: {\n code: string;\n sellerIds?: string[];\n buyerIds?: string[];\n}): Record<string, string[]> | undefined {\n if (resolved.code !== \"AMBIGUOUS\") return undefined;\n const details: Record<string, string[]> = {};\n if (resolved.sellerIds !== undefined) details.sellerIds = resolved.sellerIds;\n if (resolved.buyerIds !== undefined) details.buyerIds = resolved.buyerIds;\n return Object.keys(details).length > 0 ? details : undefined;\n}\n"]}
@@ -0,0 +1,4 @@
1
+ export { createFacilitatorClient } from '../chunk-EAKQ4EFZ.js';
2
+ export { FacilitatorHttpError } from '../chunk-PU5Y7FZG.js';
3
+ //# sourceMappingURL=index.js.map
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,6 @@
1
+ export { ADDRESS_RE, DECIMAL_UINT_RE, HEX_BYTES_RE, emitNextActions, handleCommit, handleCommitAndRedeem, handleComplete, handleDisputeEscalate, handleDisputeRaise, handleDisputeResolve, handleDisputeRetract, handleGetAvailableFunds, handlePerformAction, handleRedeem, handleWithdrawFunds, handlerErr, handlerOk, plainHandlerOk, resolveEntityId } from '../chunk-Y5HFLCAT.js';
2
+ import '../chunk-PU5Y7FZG.js';
3
+ import '../chunk-4NQ3VKC3.js';
4
+ import '../chunk-CGVXQX5V.js';
5
+ //# sourceMappingURL=index.js.map
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,261 @@
1
+ import { buildPaymentRequirements, signFullOffer } from './chunk-GBPU373M.js';
2
+ export { buildPaymentRequirements, signFullOffer } from './chunk-GBPU373M.js';
3
+ import { createFacilitatorClient } from './chunk-EAKQ4EFZ.js';
4
+ export { createFacilitatorClient } from './chunk-EAKQ4EFZ.js';
5
+ import { handleGetAvailableFunds, handleWithdrawFunds, handleDisputeEscalate, handleDisputeRetract, handleDisputeResolve, handleDisputeRaise, handleComplete, handleRedeem, handleCommitAndRedeem, handleCommit, stampFacilitatorEndpoints } from './chunk-Y5HFLCAT.js';
6
+ export { ADDRESS_RE, DECIMAL_UINT_RE, HEX_BYTES_RE, emitNextActions, handleCommit, handleCommitAndRedeem, handleComplete, handleDisputeEscalate, handleDisputeRaise, handleDisputeResolve, handleDisputeRetract, handleGetAvailableFunds, handlePerformAction, handleRedeem, handleWithdrawFunds, handlerErr, handlerOk, plainHandlerOk, resolveEntityId } from './chunk-Y5HFLCAT.js';
7
+ export { FacilitatorHttpError } from './chunk-PU5Y7FZG.js';
8
+ import './chunk-WU7QJ7YP.js';
9
+ export { verifyExchange, verifyExchangeSnapshot } from './chunk-4NQ3VKC3.js';
10
+ import './chunk-DJMCSCBE.js';
11
+ export { decodeXPaymentHeader, validatePaymentPayload } from './chunk-CGVXQX5V.js';
12
+ import { CoreSDK } from '@bosonprotocol/core-sdk';
13
+ import { channelRegistryZodSchema } from '@bosonprotocol/x402-actions';
14
+ import { addressSchema, hexSchema, evmNetworkSchema } from '@bosonprotocol/x402-core/schemes/escrow';
15
+ import { z } from 'zod';
16
+
17
+ // src/onchain/web3lib-read-stub.ts
18
+ var TAG = "x402-server:read";
19
+ function unreachable(method) {
20
+ return new Error(
21
+ `${TAG}: stub Web3LibAdapter.${method}() should never be called from the read-only CoreSDK instance. If you see this, a non-subgraph code path leaked through.`
22
+ );
23
+ }
24
+ function createReadOnlyWeb3LibStub() {
25
+ return {
26
+ uuid: `${TAG}:stub`,
27
+ getSignerAddress: () => Promise.reject(unreachable("getSignerAddress")),
28
+ isSignerContract: () => Promise.reject(unreachable("isSignerContract")),
29
+ getChainId: () => Promise.reject(unreachable("getChainId")),
30
+ getBalance: () => Promise.reject(unreachable("getBalance")),
31
+ estimateGas: () => Promise.reject(unreachable("estimateGas")),
32
+ sendTransaction: () => Promise.reject(unreachable("sendTransaction")),
33
+ call: () => Promise.reject(unreachable("call")),
34
+ send: () => Promise.reject(unreachable("send")),
35
+ getTransactionReceipt: () => Promise.reject(unreachable("getTransactionReceipt")),
36
+ getCurrentTimeMs: () => Promise.reject(unreachable("getCurrentTimeMs"))
37
+ };
38
+ }
39
+ var httpUrlSchema = z.string().url().refine((url) => url.startsWith("http://") || url.startsWith("https://"), {
40
+ message: "must be an http(s) URL"
41
+ });
42
+ var sellerSignerSchema = z.object({
43
+ address: addressSchema,
44
+ // `SellerSigner.signTypedData` is typed `Promise<Hex>` in the TS
45
+ // interface — tighten the zod return wrapper to match so a signer
46
+ // that resolves to a non-hex string fails loudly at call time
47
+ // rather than silently producing a bad `BosonOfferRef.sellerSig`.
48
+ signTypedData: z.function().args(z.unknown()).returns(z.promise(hexSchema))
49
+ }).passthrough();
50
+ var exchangeReaderShallowSchema = z.object({
51
+ read: z.function().args(z.string()).returns(z.unknown())
52
+ }).passthrough();
53
+ var coreSdkReadShallowSchema = z.object({
54
+ getFunds: z.function().args(z.unknown()).returns(z.unknown()),
55
+ getSellersByAddress: z.function().args(z.unknown()).returns(z.unknown()),
56
+ getBuyers: z.function().args(z.unknown()).returns(z.unknown())
57
+ }).passthrough();
58
+ var fulfillmentChannelShallowSchema = z.object({
59
+ id: z.string().min(1),
60
+ validate: z.function(),
61
+ onCommit: z.function()
62
+ }).passthrough();
63
+ var x402bServerConfigSchema = z.object({
64
+ network: evmNetworkSchema,
65
+ chainId: z.number().int().positive(),
66
+ escrow: addressSchema,
67
+ signer: sellerSignerSchema,
68
+ facilitator: z.object({
69
+ url: httpUrlSchema
70
+ }).strict(),
71
+ channelRegistry: channelRegistryZodSchema,
72
+ exchangeReader: exchangeReaderShallowSchema.optional(),
73
+ subgraphUrl: httpUrlSchema.optional(),
74
+ coreSdkRead: coreSdkReadShallowSchema.optional(),
75
+ exchangeFulfillmentOptionStore: z.instanceof(Map).optional(),
76
+ fulfillmentRecoveryStore: z.instanceof(Map).optional(),
77
+ fulfillmentChannels: z.array(fulfillmentChannelShallowSchema).superRefine((channels, ctx) => {
78
+ const seen = /* @__PURE__ */ new Set();
79
+ const duplicates = /* @__PURE__ */ new Set();
80
+ for (const c of channels) {
81
+ if (seen.has(c.id)) duplicates.add(c.id);
82
+ seen.add(c.id);
83
+ }
84
+ if (duplicates.size > 0) {
85
+ ctx.addIssue({
86
+ code: z.ZodIssueCode.custom,
87
+ message: `fulfillmentChannels has duplicate id(s): ${[...duplicates].join(", ")}`
88
+ });
89
+ }
90
+ }).optional()
91
+ }).strict().superRefine((cfg, ctx) => {
92
+ const networkChainId = Number(cfg.network.split(":")[1]);
93
+ if (networkChainId !== cfg.chainId) {
94
+ ctx.addIssue({
95
+ code: z.ZodIssueCode.custom,
96
+ path: ["chainId"],
97
+ message: `chainId (${cfg.chainId}) must match network (${cfg.network})`
98
+ });
99
+ }
100
+ });
101
+ function assertChannelRegistryEscrowMatch(config) {
102
+ if (config.escrow.toLowerCase() !== config.channelRegistry.escrow.toLowerCase()) {
103
+ throw new Error(
104
+ `x402-server config: escrow (${config.escrow}) does not match channelRegistry.escrow (${config.channelRegistry.escrow})`
105
+ );
106
+ }
107
+ }
108
+
109
+ // src/onchain/core-sdk-read.ts
110
+ function asCoreSdkReadAdapter(coreSdk) {
111
+ return coreSdk;
112
+ }
113
+
114
+ // src/server.ts
115
+ function withFacilitatorEndpoints(requirements, facilitatorUrl) {
116
+ return {
117
+ ...requirements,
118
+ actions: {
119
+ ...requirements.actions,
120
+ next: stampFacilitatorEndpoints(requirements.actions.next, facilitatorUrl)
121
+ }
122
+ };
123
+ }
124
+ function createX402bServer(config) {
125
+ const validated = x402bServerConfigSchema.parse(config);
126
+ assertChannelRegistryEscrowMatch(validated);
127
+ const facilitator = createFacilitatorClient({ url: validated.facilitator.url });
128
+ const exchangeFulfillmentOptionStore = validated.exchangeFulfillmentOptionStore ?? /* @__PURE__ */ new Map();
129
+ const fulfillmentRecoveryStore = validated.fulfillmentRecoveryStore ?? /* @__PURE__ */ new Map();
130
+ validated.exchangeFulfillmentOptionStore = exchangeFulfillmentOptionStore;
131
+ validated.fulfillmentRecoveryStore = fulfillmentRecoveryStore;
132
+ const signOffer = (unsigned) => signFullOffer({
133
+ fullOffer: unsigned,
134
+ signer: validated.signer,
135
+ escrow: validated.escrow,
136
+ chainId: validated.chainId
137
+ });
138
+ const requireReader = async (action) => {
139
+ if (validated.exchangeReader === void 0) {
140
+ throw new Error(
141
+ `x402-server: handlers.${action}() requires \`exchangeReader\` in config (post-settle state verification step).`
142
+ );
143
+ }
144
+ return validated.exchangeReader;
145
+ };
146
+ let cachedCoreSdkRead;
147
+ const requireCoreSdkRead = (action) => {
148
+ if (validated.coreSdkRead !== void 0) return validated.coreSdkRead;
149
+ if (cachedCoreSdkRead !== void 0) return cachedCoreSdkRead;
150
+ if (validated.subgraphUrl === void 0) {
151
+ throw new Error(
152
+ `x402-server: handlers.${action}() requires either \`coreSdkRead\` or \`subgraphUrl\` in config (subgraph read step).`
153
+ );
154
+ }
155
+ cachedCoreSdkRead = asCoreSdkReadAdapter(
156
+ new CoreSDK({
157
+ web3Lib: createReadOnlyWeb3LibStub(),
158
+ subgraphUrl: validated.subgraphUrl,
159
+ protocolDiamond: validated.escrow,
160
+ chainId: validated.chainId
161
+ })
162
+ );
163
+ return cachedCoreSdkRead;
164
+ };
165
+ return {
166
+ config: validated,
167
+ facilitator,
168
+ signOffer,
169
+ async buildPaymentRequirements(input) {
170
+ const offer = "unsigned" in input.offer ? await signOffer(input.offer.unsigned) : input.offer;
171
+ const requirements = buildPaymentRequirements({
172
+ offer,
173
+ asset: input.offer && "unsigned" in input.offer ? input.asset : input.asset,
174
+ amount: input.amount,
175
+ tokenAuthStrategies: input.tokenAuthStrategies,
176
+ recipientId: input.recipientId,
177
+ maxTimeoutSeconds: input.maxTimeoutSeconds,
178
+ ...input.fulfillment !== void 0 ? { fulfillment: input.fulfillment } : {},
179
+ network: validated.network,
180
+ escrow: validated.escrow,
181
+ channelRegistry: validated.channelRegistry
182
+ });
183
+ return withFacilitatorEndpoints(requirements, validated.facilitator.url);
184
+ },
185
+ handlers: {
186
+ commit: async (input) => handleCommit(input, {
187
+ config: validated,
188
+ facilitator,
189
+ exchangeReader: await requireReader("commit"),
190
+ fulfillmentRecoveryStore,
191
+ exchangeFulfillmentOptionStore
192
+ }),
193
+ commitAndRedeem: async (input) => handleCommitAndRedeem(input, {
194
+ config: validated,
195
+ facilitator,
196
+ exchangeReader: await requireReader("commitAndRedeem"),
197
+ fulfillmentRecoveryStore,
198
+ exchangeFulfillmentOptionStore
199
+ }),
200
+ redeem: async (input) => handleRedeem(input, {
201
+ config: validated,
202
+ facilitator,
203
+ exchangeReader: await requireReader("redeem"),
204
+ exchangeFulfillmentOptionStore,
205
+ fulfillmentRecoveryStore
206
+ }),
207
+ complete: async (input) => handleComplete(input, {
208
+ config: validated,
209
+ facilitator,
210
+ exchangeReader: await requireReader("complete")
211
+ }),
212
+ disputeRaise: async (input) => handleDisputeRaise(input, {
213
+ config: validated,
214
+ facilitator,
215
+ exchangeReader: await requireReader("disputeRaise")
216
+ }),
217
+ disputeResolve: async (input) => handleDisputeResolve(input, {
218
+ config: validated,
219
+ facilitator,
220
+ exchangeReader: await requireReader("disputeResolve")
221
+ }),
222
+ disputeRetract: async (input) => handleDisputeRetract(input, {
223
+ config: validated,
224
+ facilitator,
225
+ exchangeReader: await requireReader("disputeRetract")
226
+ }),
227
+ disputeEscalate: async (input) => handleDisputeEscalate(input, {
228
+ config: validated,
229
+ facilitator,
230
+ exchangeReader: await requireReader("disputeEscalate")
231
+ }),
232
+ withdrawFunds: async (input) => handleWithdrawFunds(input, {
233
+ config: validated,
234
+ facilitator,
235
+ coreSdkRead: requireCoreSdkRead("withdrawFunds")
236
+ }),
237
+ getAvailableFunds: async (query) => handleGetAvailableFunds(query, {
238
+ coreSdkRead: requireCoreSdkRead("getAvailableFunds")
239
+ })
240
+ }
241
+ };
242
+ }
243
+
244
+ // src/internal/x-payment-response.ts
245
+ function encodeXPaymentResponse(body) {
246
+ const json = JSON.stringify(body);
247
+ if (typeof Buffer !== "undefined") {
248
+ return Buffer.from(json, "utf8").toString("base64");
249
+ }
250
+ const bytes = new TextEncoder().encode(json);
251
+ let binary = "";
252
+ for (let i = 0; i < bytes.length; i++) {
253
+ binary += String.fromCharCode(bytes[i]);
254
+ }
255
+ return btoa(binary);
256
+ }
257
+ var X_PAYMENT_RESPONSE_HEADER = "X-PAYMENT-RESPONSE";
258
+
259
+ export { X_PAYMENT_RESPONSE_HEADER, asCoreSdkReadAdapter, assertChannelRegistryEscrowMatch, createX402bServer, encodeXPaymentResponse, x402bServerConfigSchema };
260
+ //# sourceMappingURL=index.js.map
261
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/onchain/web3lib-read-stub.ts","../../src/config.ts","../../src/onchain/core-sdk-read.ts","../../src/server.ts","../../src/internal/x-payment-response.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AASA,IAAM,GAAA,GAAM,kBAAA;AAEZ,SAAS,YAAY,MAAA,EAAuB;AAC1C,EAAA,OAAO,IAAI,KAAA;AAAA,IACT,CAAA,EAAG,GAAG,CAAA,sBAAA,EAAyB,MAAM,CAAA,wHAAA;AAAA,GAEvC;AACF;AAEO,SAAS,yBAAA,GAA4C;AAC1D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,GAAG,GAAG,CAAA,KAAA,CAAA;AAAA,IACZ,kBAAkB,MAAM,OAAA,CAAQ,MAAA,CAAO,WAAA,CAAY,kBAAkB,CAAC,CAAA;AAAA,I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A,EAAe,OAAO,KAAA,KACpB,mBAAA,CAAoB,KAAA,EAAO;AAAA,QACzB,MAAA,EAAQ,SAAA;AAAA,QACR,WAAA;AAAA,QACA,WAAA,EAAa,mBAAmB,eAAe;AAAA,OAChD,CAAA;AAAA,MACH,iBAAA,EAAmB,OAAO,KAAA,KACxB,uBAAA,CAAwB,KAAA,EAAO;AAAA,QAC7B,WAAA,EAAa,mBAAmB,mBAAmB;AAAA,OACpD;AAAA;AACL,GACF;AACF;;;AC1OO,SAAS,uBAAuB,IAAA,EAAuB;AAC5D,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,SAAA,CAAU,IAAI,CAAA;AAChC,EAAA,IAAI,OAAO,WAAW,WAAA,EAAa;AACjC,IAAA,OAAO,OAAO,IAAA,CAAK,IAAA,EAAM,MAAM,CAAA,CAAE,SAAS,QAAQ,CAAA;AAAA,EACpD;AAGA,EAAA,MAAM,KAAA,GAAQ,IAAI,WAAA,EAAY,CAAE,OAAO,IAAI,CAAA;AAC3C,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AACrC,IAAA,MAAA,IAAU,MAAA,CAAO,YAAA,CAAa,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,KAAK,MAAM,CAAA;AACpB;AAGO,IAAM,yBAAA,GAA4B","file":"index.js","sourcesContent":["// Minimal throwing `Web3LibAdapter` for the server's read-only\n// `CoreSDK` instance. The funds-subgraph and accounts-subgraph helpers\n// (`getFunds`, `getSellersByAddress`, `getBuyers`) never touch the\n// adapter at runtime, but `new CoreSDK({...})` requires one in its\n// constructor. Each method throws so any future leak into a non-read\n// path is loud rather than silent.\n\nimport type { Web3LibAdapter } from \"@bosonprotocol/common\";\n\nconst TAG = \"x402-server:read\";\n\nfunction unreachable(method: string): Error {\n return new Error(\n `${TAG}: stub Web3LibAdapter.${method}() should never be called from the read-only ` +\n `CoreSDK instance. If you see this, a non-subgraph code path leaked through.`,\n );\n}\n\nexport function createReadOnlyWeb3LibStub(): Web3LibAdapter {\n return {\n uuid: `${TAG}:stub`,\n getSignerAddress: () => Promise.reject(unreachable(\"getSignerAddress\")),\n isSignerContract: () => Promise.reject(unreachable(\"isSignerContract\")),\n getChainId: () => Promise.reject(unreachable(\"getChainId\")),\n getBalance: () => Promise.reject(unreachable(\"getBalance\")),\n estimateGas: () => Promise.reject(unreachable(\"estimateGas\")),\n sendTransaction: () => Promise.reject(unreachable(\"sendTransaction\")),\n call: () => Promise.reject(unreachable(\"call\")),\n send: () => Promise.reject(unreachable(\"send\")),\n getTransactionReceipt: () => Promise.reject(unreachable(\"getTransactionReceipt\")),\n getCurrentTimeMs: () => Promise.reject(unreachable(\"getCurrentTimeMs\")),\n };\n}\n","// X402bServerConfig — the per-server context passed to\n// `createX402bServer`. The config holds everything that doesn't vary\n// per request: the network + escrow address, the seller's signer, the\n// facilitator URL (for both the future HTTP client and the public\n// advertisement embedded in `nextActions[].endpoints.facilitator`),\n// and the channel registry consumed by `deriveNextActions`.\n//\n// Per-offer values (price, asset, fulfillment, etc.) come in through\n// the per-request `buildPaymentRequirements` call instead — see\n// `./challenge/build-requirements.ts`.\n\nimport { channelRegistryZodSchema, type ChannelRegistry } from \"@bosonprotocol/x402-actions\";\nimport {\n addressSchema,\n evmNetworkSchema,\n hexSchema,\n type Address,\n type EvmNetwork,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\nimport type { Hex } from \"viem\";\nimport { z } from \"zod\";\n\nimport type { CoreSdkReadAdapter } from \"./onchain/core-sdk-read.js\";\nimport type { ExchangeReader } from \"./onchain/verify-exchange.js\";\n\n/**\n * Minimal signing surface needed by `signFullOffer`. Structurally\n * compatible with viem's `Account` (in particular `LocalAccount` from\n * `privateKeyToAccount`), but kept narrow so consumers can plug in\n * HSM- / KMS- / ERC-1271-backed signers without depending on viem's\n * internal account types.\n */\nexport interface SellerSigner {\n /** Address that the EIP-712 signature must recover to (`creator` in `BosonOfferRef`). */\n readonly address: Address;\n /** EIP-712 typed-data signer. Accepts the same shape viem's `signTypedData` does. */\n signTypedData: (params: {\n domain: Record<string, unknown>;\n types: Record<string, readonly { name: string; type: string }[]>;\n primaryType: string;\n message: Record<string, unknown>;\n }) => Promise<Hex>;\n}\n\n/**\n * Per-server configuration. Validated by `x402bServerConfigSchema` at\n * `createX402bServer` time so bad config fails fast at boot rather than\n * later inside a 402 response.\n */\nexport interface X402bServerConfig {\n /** CAIP-2 EVM network the server advertises (e.g. `eip155:8453`). */\n network: EvmNetwork;\n /** EVM chain id matching `network` — passed straight to the EIP-712 builder's salt. */\n chainId: number;\n /** Address of the Boson Diamond — the EIP-712 `verifyingContract` and the wire-level `escrowAddress`. */\n escrow: Address;\n /** Seller signer (signs the FullOffer EIP-712 typed-data). */\n signer: SellerSigner;\n /** Facilitator service the server forwards meta-tx envelopes to. The URL is also advertised in `nextActions[].endpoints.facilitator`. */\n facilitator: { url: string };\n /** Per-seller channel + endpoint registry consumed by `deriveNextActions`. */\n channelRegistry: ChannelRegistry;\n /**\n * Reader the convenience handlers use to verify the post-settle /\n * post-perform-action exchange state. Required at runtime when any\n * write handler is invoked; the `signOffer` / `buildPaymentRequirements`\n * read-only paths don't touch it. See `./onchain/verify-exchange.ts`\n * for the interface.\n */\n exchangeReader?: ExchangeReader;\n /**\n * URL of the Boson Protocol subgraph for this network. Used by the\n * read-only `available-funds` handler and the address→entityId\n * resolver shared with `withdraw-funds`. Optional at config time\n * (legacy commit/redeem handlers don't need it); required at runtime\n * by `handlers.withdrawFunds` / `handlers.getAvailableFunds`.\n */\n subgraphUrl?: string;\n /**\n * Pre-built read-only core-sdk client. If omitted, the server\n * constructs one internally from `subgraphUrl` + `escrow` + `chainId`\n * with a throwing `Web3LibAdapter` stub. Provide your own for tests\n * or when you want to share a single core-sdk instance with the\n * rest of your service.\n */\n coreSdkRead?: CoreSdkReadAdapter;\n /**\n * Server-side store of the fulfillment option ids advertised for\n * each Flow A exchange (keyed by `exchangeId`). Populated from the\n * original `PaymentRequirements` after commit verification and read\n * at redeem time so the buyer's redeem-time fulfillment choice\n * cannot switch to a channel the offer never advertised.\n *\n * Optional in the config: when omitted, `createX402bServer` wires up\n * an in-memory `Map`. Hosts running multiple instances should plug\n * in their own cross-process `Map`-shaped backing store.\n */\n exchangeFulfillmentOptionStore?: Map<string, readonly string[]>;\n /**\n * Pending fulfillment updates that reached REDEEMED on-chain but\n * failed the server-side `channel.onCommit(...)` upsert. The commit\n * handler records Flow B updates here before attempting the channel\n * write; the redeem handler does the same for Flow A. Both delete the\n * record on success and leave it behind with the error message on\n * failure so the host can replay/reconcile out of band.\n */\n fulfillmentRecoveryStore?: Map<string, FulfillmentRecoveryEntry>;\n /**\n * Fulfillment channels the server accepts at redeem time when the\n * client re-submits delivery data. Structurally a subset of\n * `@bosonprotocol/x402-fulfillment`'s `FulfillmentChannel` — only\n * `id`, `validate`, and `onCommit` are read here, so existing\n * channel instances pass through directly. Required iff a host\n * wants to accept redeem-time fulfillment updates; absent means\n * redeem requests carrying `fulfillment` are rejected with\n * `FULFILLMENT_CHANNELS_NOT_CONFIGURED`.\n */\n fulfillmentChannels?: readonly RedeemFulfillmentChannel[];\n}\n\n/**\n * Minimal structural slice of `FulfillmentChannel` the redeem\n * handler needs. Kept inline so `@bosonprotocol/x402-server` does\n * not depend on `@bosonprotocol/x402-fulfillment` (avoids a hard\n * coupling between the resource-server SDK and a specific channel\n * package); any real channel implementation is type-compatible.\n */\nexport interface RedeemFulfillmentChannel {\n readonly id: string;\n validate(data: Record<string, unknown> | null): { ok: true } | { ok: false; reason: string };\n onCommit(exchangeId: string, data: Record<string, unknown> | null): Promise<void>;\n}\n\nexport interface FulfillmentRecoveryEntry {\n exchangeId: string;\n option: string;\n data: Record<string, unknown> | null;\n redeemer: Address;\n recordedAt: number;\n error?: string;\n}\n\nconst httpUrlSchema = z\n .string()\n .url()\n .refine((url) => url.startsWith(\"http://\") || url.startsWith(\"https://\"), {\n message: \"must be an http(s) URL\",\n });\n\nconst sellerSignerSchema = z\n .object({\n address: addressSchema,\n // `SellerSigner.signTypedData` is typed `Promise<Hex>` in the TS\n // interface — tighten the zod return wrapper to match so a signer\n // that resolves to a non-hex string fails loudly at call time\n // rather than silently producing a bad `BosonOfferRef.sellerSig`.\n signTypedData: z.function().args(z.unknown()).returns(z.promise(hexSchema)),\n })\n .passthrough();\n\nconst exchangeReaderShallowSchema = z\n .object({\n read: z.function().args(z.string()).returns(z.unknown()),\n })\n .passthrough();\n\nconst coreSdkReadShallowSchema = z\n .object({\n getFunds: z.function().args(z.unknown()).returns(z.unknown()),\n getSellersByAddress: z.function().args(z.unknown()).returns(z.unknown()),\n getBuyers: z.function().args(z.unknown()).returns(z.unknown()),\n })\n .passthrough();\n\nconst fulfillmentChannelShallowSchema = z\n .object({\n id: z.string().min(1),\n validate: z.function(),\n onCommit: z.function(),\n })\n .passthrough();\n\n/**\n * zod validator for `X402bServerConfig`. Shallow on the signer +\n * exchange reader (viem account types bring their own structural\n * validators; the user-supplied reader impl is structurally typed);\n * strict on the scalar fields we own here, and on the channel\n * registry via `@bosonprotocol/x402-actions`.\n */\nexport const x402bServerConfigSchema = z\n .object({\n network: evmNetworkSchema,\n chainId: z.number().int().positive(),\n escrow: addressSchema,\n signer: sellerSignerSchema,\n facilitator: z\n .object({\n url: httpUrlSchema,\n })\n .strict(),\n channelRegistry: channelRegistryZodSchema,\n exchangeReader: exchangeReaderShallowSchema.optional(),\n subgraphUrl: httpUrlSchema.optional(),\n coreSdkRead: coreSdkReadShallowSchema.optional(),\n exchangeFulfillmentOptionStore: z.instanceof(Map).optional(),\n fulfillmentRecoveryStore: z.instanceof(Map).optional(),\n fulfillmentChannels: z\n .array(fulfillmentChannelShallowSchema)\n .superRefine((channels, ctx) => {\n // Duplicate ids would let one channel silently shadow another\n // (the redeem handler picks via `find(c => c.id === option)`).\n const seen = new Set<string>();\n const duplicates = new Set<string>();\n for (const c of channels) {\n if (seen.has(c.id)) duplicates.add(c.id);\n seen.add(c.id);\n }\n if (duplicates.size > 0) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `fulfillmentChannels has duplicate id(s): ${[...duplicates].join(\", \")}`,\n });\n }\n })\n .optional(),\n })\n .strict()\n .superRefine((cfg, ctx) => {\n // CAIP-2 `eip155:<chainId>` carries the chainId; assert it matches\n // the explicit `chainId` field so the EIP-712 salt and the\n // wire-level network advertisement agree. Catches the easy\n // copy-paste mistake of pairing `eip155:8453` with `chainId: 1`.\n const networkChainId = Number(cfg.network.split(\":\")[1]);\n if (networkChainId !== cfg.chainId) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: [\"chainId\"],\n message: `chainId (${cfg.chainId}) must match network (${cfg.network})`,\n });\n }\n });\n\n/**\n * Cross-field invariant: `config.escrow` and\n * `config.channelRegistry.escrow` must agree — the Diamond address is\n * the same on both sides. Run this after `x402bServerConfigSchema.parse`.\n */\nexport function assertChannelRegistryEscrowMatch(config: X402bServerConfig): void {\n if (config.escrow.toLowerCase() !== config.channelRegistry.escrow.toLowerCase()) {\n throw new Error(\n `x402-server config: escrow (${config.escrow}) does not match channelRegistry.escrow (${config.channelRegistry.escrow})`,\n );\n }\n}\n","// Minimal read-only adapter over `@bosonprotocol/core-sdk` used by the\n// `withdraw-funds` and `available-funds` handlers.\n//\n// The full `CoreSDK` type pulls in a lot of surface area (every facet,\n// every signing helper) — none of which the read paths need. Narrowing\n// it to a structural interface keeps the server's dependency\n// footprint small for consumers that just want to expose the read\n// endpoints (and lets tests pass a hand-rolled stub without\n// constructing a real CoreSDK).\n\nimport type { CoreSDK } from \"@bosonprotocol/core-sdk\";\n\n/** Funds entity returned by `coreSdk.getFunds` — narrowed to the fields the handler reshapes. */\nexport interface CoreSdkFundsEntity {\n id?: string;\n accountId: string;\n availableAmount: string;\n token: {\n address: string;\n decimals: string;\n symbol: string;\n name: string;\n };\n}\n\n/** Seller entity returned by `coreSdk.getSellersByAddress` — only the id is consumed. */\nexport interface CoreSdkSellerEntity {\n id: string;\n}\n\n/** Buyer entity returned by `coreSdk.getBuyers` — only the id is consumed. */\nexport interface CoreSdkBuyerEntity {\n id: string;\n}\n\n/**\n * The subset of `CoreSDK` the read-only handlers actually use. Both the\n * real `CoreSDK` and a hand-rolled stub for tests satisfy this shape.\n */\nexport interface CoreSdkReadAdapter {\n getFunds(queryVars: { fundsFilter: { accountId: string } }): Promise<CoreSdkFundsEntity[]>;\n getSellersByAddress(address: string): Promise<CoreSdkSellerEntity[]>;\n getBuyers(queryVars: { buyersFilter: { wallet: string } }): Promise<CoreSdkBuyerEntity[]>;\n}\n\n/**\n * Cast a full `CoreSDK` to the narrowed adapter shape. Structural-only;\n * does not capture or wrap anything.\n */\nexport function asCoreSdkReadAdapter(coreSdk: CoreSDK): CoreSdkReadAdapter {\n return coreSdk as unknown as CoreSdkReadAdapter;\n}\n","// `createX402bServer` — the per-server factory. Wires the 402\n// challenge builder + FullOffer signer (PR 1), and the convenience\n// handlers (commit, commit-and-redeem, redeem, complete, dispute/*,\n// withdraw-funds, available-funds) over the facilitator HTTP client +\n// configured `ExchangeReader` and read-only core-sdk client.\n\nimport { CoreSDK } from \"@bosonprotocol/core-sdk\";\nimport type { UnsignedFullOffer } from \"@bosonprotocol/x402-core/eip712\";\nimport type {\n BosonOfferRef,\n EscrowPaymentRequirements,\n} from \"@bosonprotocol/x402-core/schemes/escrow\";\n\nimport { createReadOnlyWeb3LibStub } from \"./onchain/web3lib-read-stub.js\";\n\nimport { buildPaymentRequirements } from \"./challenge/build-requirements.js\";\nimport { signFullOffer } from \"./challenge/sign-full-offer.js\";\nimport {\n assertChannelRegistryEscrowMatch,\n x402bServerConfigSchema,\n type FulfillmentRecoveryEntry,\n type X402bServerConfig,\n} from \"./config.js\";\nimport { createFacilitatorClient, type FacilitatorClient } from \"./facilitator/client.js\";\nimport {\n handleCommit,\n handleCommitAndRedeem,\n handleComplete,\n handleDisputeEscalate,\n handleDisputeRaise,\n handleDisputeResolve,\n handleDisputeRetract,\n handleGetAvailableFunds,\n handleRedeem,\n handleWithdrawFunds,\n type AvailableFundsBody,\n type AvailableFundsQuery,\n type CommitHandlerInput,\n type CommitOk,\n type HandlerResult,\n type PerformActionInput,\n type PerformActionOk,\n type PlainHandlerResult,\n type RedeemHandlerInput,\n type WithdrawFundsInput,\n type WithdrawFundsOk,\n} from \"./handlers/index.js\";\nimport { stampFacilitatorEndpoints } from \"./internal/facilitator-endpoints.js\";\nimport { asCoreSdkReadAdapter, type CoreSdkReadAdapter } from \"./onchain/core-sdk-read.js\";\nimport type { ExchangeReader } from \"./onchain/verify-exchange.js\";\n\n/** Per-offer inputs for `server.buildPaymentRequirements` — everything the offer-level args carry, minus the per-server context the factory already holds. */\nexport interface BuildRequirementsInput {\n /** Already-signed offer reference, or `{ unsigned }` to have the server sign it. */\n offer: BosonOfferRef | { unsigned: UnsignedFullOffer };\n asset: string;\n amount: string;\n tokenAuthStrategies: readonly (\"none\" | \"erc3009\" | \"permit\" | \"permit2\")[];\n recipientId: string;\n maxTimeoutSeconds: number;\n fulfillment?: import(\"@bosonprotocol/x402-core/schemes/escrow\").FulfillmentRequirements;\n}\n\nexport interface X402bServer {\n readonly config: X402bServerConfig;\n readonly facilitator: FacilitatorClient;\n\n /** Sign an unsigned FullOffer with the configured seller signer. */\n signOffer(unsigned: UnsignedFullOffer): Promise<BosonOfferRef>;\n /** Build a 402 `EscrowPaymentRequirements`. */\n buildPaymentRequirements(input: BuildRequirementsInput): Promise<EscrowPaymentRequirements>;\n\n /** Convenience handlers — pure, framework-agnostic. The express adapter (PR 5) maps them to routes. */\n readonly handlers: {\n commit(input: CommitHandlerInput): Promise<HandlerResult<CommitOk>>;\n commitAndRedeem(input: CommitHandlerInput): Promise<HandlerResult<CommitOk>>;\n redeem(input: RedeemHandlerInput): Promise<HandlerResult<PerformActionOk>>;\n complete(input: PerformActionInput): Promise<HandlerResult<PerformActionOk>>;\n disputeRaise(input: PerformActionInput): Promise<HandlerResult<PerformActionOk>>;\n disputeResolve(input: PerformActionInput): Promise<HandlerResult<PerformActionOk>>;\n disputeRetract(input: PerformActionInput): Promise<HandlerResult<PerformActionOk>>;\n disputeEscalate(input: PerformActionInput): Promise<HandlerResult<PerformActionOk>>;\n withdrawFunds(input: WithdrawFundsInput): Promise<PlainHandlerResult<WithdrawFundsOk>>;\n getAvailableFunds(query: AvailableFundsQuery): Promise<PlainHandlerResult<AvailableFundsBody>>;\n };\n}\n\nfunction withFacilitatorEndpoints(\n requirements: EscrowPaymentRequirements,\n facilitatorUrl: string,\n): EscrowPaymentRequirements {\n return {\n ...requirements,\n actions: {\n ...requirements.actions,\n next: stampFacilitatorEndpoints(requirements.actions.next, facilitatorUrl),\n },\n };\n}\n\n/**\n * Validate a config and return a `X402bServer` whose methods are\n * bound to the validated context. Throws synchronously (`ZodError`)\n * on bad config or (`Error`) on the escrow / channel-registry escrow\n * mismatch.\n */\nexport function createX402bServer(config: X402bServerConfig): X402bServer {\n const validated = x402bServerConfigSchema.parse(config) as X402bServerConfig;\n assertChannelRegistryEscrowMatch(validated);\n\n const facilitator = createFacilitatorClient({ url: validated.facilitator.url });\n // Default to a fresh in-memory store when the host doesn't supply\n // one. Single shared reference for the lifetime of this server — so\n // commit-time writes and redeem-time reads observe the same Map.\n const exchangeFulfillmentOptionStore: Map<string, readonly string[]> =\n validated.exchangeFulfillmentOptionStore ?? new Map();\n const fulfillmentRecoveryStore: Map<string, FulfillmentRecoveryEntry> =\n validated.fulfillmentRecoveryStore ?? new Map();\n validated.exchangeFulfillmentOptionStore = exchangeFulfillmentOptionStore;\n validated.fulfillmentRecoveryStore = fulfillmentRecoveryStore;\n\n const signOffer = (unsigned: UnsignedFullOffer): Promise<BosonOfferRef> =>\n signFullOffer({\n fullOffer: unsigned,\n signer: validated.signer,\n escrow: validated.escrow,\n chainId: validated.chainId,\n });\n\n const requireReader = async (action: string): Promise<ExchangeReader> => {\n if (validated.exchangeReader === undefined) {\n throw new Error(\n `x402-server: handlers.${action}() requires \\`exchangeReader\\` in config (post-settle state verification step).`,\n );\n }\n return validated.exchangeReader;\n };\n\n // Lazy-memoised read-only core-sdk. The construction itself is cheap\n // but happens on every `handlers.withdrawFunds()` /\n // `handlers.getAvailableFunds()` call — caching the adapter keeps the\n // hot path allocation-free and shares one subgraph client across\n // requests. `validated.coreSdkRead`, when supplied by the host, is\n // already shared.\n let cachedCoreSdkRead: CoreSdkReadAdapter | undefined;\n const requireCoreSdkRead = (action: string): CoreSdkReadAdapter => {\n if (validated.coreSdkRead !== undefined) return validated.coreSdkRead;\n if (cachedCoreSdkRead !== undefined) return cachedCoreSdkRead;\n if (validated.subgraphUrl === undefined) {\n throw new Error(\n `x402-server: handlers.${action}() requires either \\`coreSdkRead\\` or \\`subgraphUrl\\` in config (subgraph read step).`,\n );\n }\n cachedCoreSdkRead = asCoreSdkReadAdapter(\n new CoreSDK({\n web3Lib: createReadOnlyWeb3LibStub(),\n subgraphUrl: validated.subgraphUrl,\n protocolDiamond: validated.escrow,\n chainId: validated.chainId,\n }),\n );\n return cachedCoreSdkRead;\n };\n\n return {\n config: validated,\n facilitator,\n signOffer,\n async buildPaymentRequirements(input) {\n const offer = \"unsigned\" in input.offer ? await signOffer(input.offer.unsigned) : input.offer;\n const requirements = buildPaymentRequirements({\n offer,\n asset: input.offer && \"unsigned\" in input.offer ? input.asset : input.asset,\n amount: input.amount,\n tokenAuthStrategies: input.tokenAuthStrategies,\n recipientId: input.recipientId,\n maxTimeoutSeconds: input.maxTimeoutSeconds,\n ...(input.fulfillment !== undefined ? { fulfillment: input.fulfillment } : {}),\n network: validated.network,\n escrow: validated.escrow,\n channelRegistry: validated.channelRegistry,\n });\n return withFacilitatorEndpoints(requirements, validated.facilitator.url);\n },\n handlers: {\n commit: async (input) =>\n handleCommit(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"commit\"),\n fulfillmentRecoveryStore,\n exchangeFulfillmentOptionStore,\n }),\n commitAndRedeem: async (input) =>\n handleCommitAndRedeem(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"commitAndRedeem\"),\n fulfillmentRecoveryStore,\n exchangeFulfillmentOptionStore,\n }),\n redeem: async (input) =>\n handleRedeem(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"redeem\"),\n exchangeFulfillmentOptionStore,\n fulfillmentRecoveryStore,\n }),\n complete: async (input) =>\n handleComplete(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"complete\"),\n }),\n disputeRaise: async (input) =>\n handleDisputeRaise(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"disputeRaise\"),\n }),\n disputeResolve: async (input) =>\n handleDisputeResolve(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"disputeResolve\"),\n }),\n disputeRetract: async (input) =>\n handleDisputeRetract(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"disputeRetract\"),\n }),\n disputeEscalate: async (input) =>\n handleDisputeEscalate(input, {\n config: validated,\n facilitator,\n exchangeReader: await requireReader(\"disputeEscalate\"),\n }),\n withdrawFunds: async (input) =>\n handleWithdrawFunds(input, {\n config: validated,\n facilitator,\n coreSdkRead: requireCoreSdkRead(\"withdrawFunds\"),\n }),\n getAvailableFunds: async (query) =>\n handleGetAvailableFunds(query, {\n coreSdkRead: requireCoreSdkRead(\"getAvailableFunds\"),\n }),\n },\n };\n}\n","// Encoder for the `X-PAYMENT-RESPONSE` header. The base x402 spec uses\n// base64-of-JSON for `X-PAYMENT-RESPONSE`, and the buyer SDK's\n// `parsePaymentResponse` ([client/src/response.ts]) decodes it the\n// same way. This helper is the inverse — give it the success body and\n// it produces the header value.\n//\n// The header is best-effort metadata that lets the client read\n// `exchangeId` (and any future scheme-specific fields) without parsing\n// the full JSON body. We pass the body through verbatim so the wire\n// shape is identical to the response body; consumers stay free to\n// branch on either.\n\n/**\n * Base64-encode the success-response body for the `X-PAYMENT-RESPONSE`\n * header. The companion decoder lives in\n * `@bosonprotocol/x402-client`'s `parsePaymentResponse`.\n */\nexport function encodeXPaymentResponse(body: unknown): string {\n const json = JSON.stringify(body);\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(json, \"utf8\").toString(\"base64\");\n }\n // Node ships `Buffer`; the browser fallback exists for completeness so\n // a non-Node integrator (Workers, Deno) can reuse this helper.\n const bytes = new TextEncoder().encode(json);\n let binary = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/** Canonical header name — exported so adapters share one spelling. */\nexport const X_PAYMENT_RESPONSE_HEADER = \"X-PAYMENT-RESPONSE\" as const;\n"]}
@@ -0,0 +1,4 @@
1
+ import '../chunk-WU7QJ7YP.js';
2
+ export { verifyExchange, verifyExchangeSnapshot } from '../chunk-4NQ3VKC3.js';
3
+ //# sourceMappingURL=index.js.map
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,4 @@
1
+ import '../chunk-DJMCSCBE.js';
2
+ export { decodeXPaymentHeader, validatePaymentPayload } from '../chunk-CGVXQX5V.js';
3
+ //# sourceMappingURL=index.js.map
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
package/package.json ADDED
@@ -0,0 +1,88 @@
1
+ {
2
+ "name": "@bosonprotocol/x402-server",
3
+ "version": "0.1.0-alpha-0",
4
+ "license": "Apache-2.0",
5
+ "description": "Framework-agnostic x402 resource-server SDK for the Boson Protocol escrow scheme — 402 challenge builder and FullOffer signer hook.",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/bosonprotocol/x402B.git",
9
+ "directory": "typescript/packages/server"
10
+ },
11
+ "homepage": "https://github.com/bosonprotocol/x402B/tree/main/typescript/packages/server",
12
+ "bugs": {
13
+ "url": "https://github.com/bosonprotocol/x402B/issues"
14
+ },
15
+ "keywords": [
16
+ "x402",
17
+ "boson-protocol",
18
+ "escrow",
19
+ "server",
20
+ "sdk",
21
+ "402"
22
+ ],
23
+ "main": "./dist/cjs/index.js",
24
+ "module": "./dist/esm/index.js",
25
+ "types": "./dist/cjs/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/cjs/index.d.ts",
29
+ "import": "./dist/esm/index.js",
30
+ "require": "./dist/cjs/index.js"
31
+ },
32
+ "./challenge": {
33
+ "types": "./dist/cjs/challenge/index.d.ts",
34
+ "import": "./dist/esm/challenge/index.js",
35
+ "require": "./dist/cjs/challenge/index.js"
36
+ },
37
+ "./validate": {
38
+ "types": "./dist/cjs/validate/index.d.ts",
39
+ "import": "./dist/esm/validate/index.js",
40
+ "require": "./dist/cjs/validate/index.js"
41
+ },
42
+ "./facilitator": {
43
+ "types": "./dist/cjs/facilitator/index.d.ts",
44
+ "import": "./dist/esm/facilitator/index.js",
45
+ "require": "./dist/cjs/facilitator/index.js"
46
+ },
47
+ "./handlers": {
48
+ "types": "./dist/cjs/handlers/index.d.ts",
49
+ "import": "./dist/esm/handlers/index.js",
50
+ "require": "./dist/cjs/handlers/index.js"
51
+ },
52
+ "./onchain": {
53
+ "types": "./dist/cjs/onchain/index.d.ts",
54
+ "import": "./dist/esm/onchain/index.js",
55
+ "require": "./dist/cjs/onchain/index.js"
56
+ }
57
+ },
58
+ "files": [
59
+ "dist",
60
+ "README.md",
61
+ "LICENSE"
62
+ ],
63
+ "publishConfig": {
64
+ "access": "public"
65
+ },
66
+ "dependencies": {
67
+ "@bosonprotocol/common": "1.33.0-alpha.7",
68
+ "@bosonprotocol/core-sdk": "1.48.0-alpha.6",
69
+ "viem": "^2.39.3",
70
+ "zod": "^3.24.2",
71
+ "@bosonprotocol/x402-core": "^0.1.0-alpha-0",
72
+ "@bosonprotocol/x402-facilitator": "^0.1.0-alpha-0",
73
+ "@bosonprotocol/x402-actions": "^0.1.0-alpha-0",
74
+ "@bosonprotocol/x402-evm": "^0.1.0-alpha-0"
75
+ },
76
+ "devDependencies": {
77
+ "@types/node": "^20.17.10",
78
+ "tsup": "^8.3.5",
79
+ "typescript": "^5.7.2",
80
+ "vitest": "^2.1.8"
81
+ },
82
+ "scripts": {
83
+ "build": "tsup && node scripts/postbuild.mjs",
84
+ "test": "vitest run",
85
+ "lint": "eslint src test --max-warnings 0",
86
+ "clean": "rm -rf dist .turbo"
87
+ }
88
+ }