@bosonprotocol/x402-server 0.2.0 → 0.3.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.
- package/dist/cjs/challenge/index.d.ts +2 -1
- package/dist/cjs/client-B2yejopi.d.ts +88 -0
- package/dist/cjs/{config-CBr9qMps.d.ts → config-hnCiZiXF.d.ts} +241 -22
- package/dist/cjs/facilitator/index.d.ts +1 -1
- package/dist/cjs/facilitator/index.js +120 -8
- package/dist/cjs/facilitator/index.js.map +1 -1
- package/dist/cjs/handlers/index.d.ts +8 -264
- package/dist/cjs/handlers/index.js +147 -18
- package/dist/cjs/handlers/index.js.map +1 -1
- package/dist/cjs/index-COmLTH-U.d.ts +292 -0
- package/dist/cjs/index.d.ts +91 -7
- package/dist/cjs/index.js +559 -73
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/chunk-OMJEQEOF.js +223 -0
- package/dist/esm/chunk-OMJEQEOF.js.map +1 -0
- package/dist/esm/{chunk-PU5Y7FZG.js → chunk-RAESVNQG.js} +15 -3
- package/dist/esm/chunk-RAESVNQG.js.map +1 -0
- package/dist/esm/{chunk-Y5HFLCAT.js → chunk-SHYOIKYU.js} +138 -21
- package/dist/esm/chunk-SHYOIKYU.js.map +1 -0
- package/dist/esm/facilitator/index.js +2 -2
- package/dist/esm/handlers/index.js +2 -2
- package/dist/esm/index.js +306 -53
- package/dist/esm/index.js.map +1 -1
- package/package.json +3 -3
- package/dist/cjs/client-tnrpqVMW.d.ts +0 -36
- package/dist/esm/chunk-EAKQ4EFZ.js +0 -124
- package/dist/esm/chunk-EAKQ4EFZ.js.map +0 -1
- package/dist/esm/chunk-PU5Y7FZG.js.map +0 -1
- package/dist/esm/chunk-Y5HFLCAT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
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,CAAA,EAAG,IAAI,CAAA,uBAAA,EAA0B,kBAAA,CAAmB,QAAQ,CAAC,CAAA,CAAA;AACtE;AASO,SAAS,yBAAA,CACd,MACA,cAAA,EACc;AACd,EAAA,OAAO,IAAA,CAAK,GAAA,CAAI,CAAC,KAAA,KAAU;AACzB,IAAA,IAAI,CAAC,KAAA,CAAM,QAAA,CAAS,QAAA,CAAS,aAAa,CAAA,EAAG;AAC3C,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,IAAI,KAAA,CAAM,SAAA,EAAW,WAAA,KAAgB,MAAA,EAAW;AAC9C,MAAA,OAAO,KAAA;AAAA,IACT;AACA,IAAA,OAAO;AAAA,MACL,GAAG,KAAA;AAAA,MACH,SAAA,EAAW;AAAA,QACT,GAAG,KAAA,CAAM,SAAA;AAAA,QACT,WAAA,EAAa,sBAAA,CAAuB,KAAA,CAAM,EAAA,EAAI,cAAc;AAAA;AAC9D,KACF;AAAA,EACF,CAAC,CAAA;AACH;;;AClBO,SAAS,eAAA,CACd,KAAA,EACA,QAAA,EACA,cAAA,EACmB;AACnB,EAAA,MAAM,OAAA,GACJ,KAAA,CAAM,aAAA,KAAkB,aAAA,CAAc,QA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L,GAAA;AAAA,MACA,kBAAA;AAAA,MACA,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU;AAAA,KACnC;AAAA,EACF;AAEA,EAAA,MAAM,KAAA,GAA+B,GAAA,CAAI,GAAA,CAAI,CAAC,KAAA,MAAW;AAAA,IACvD,YAAA,EAAc,MAAM,KAAA,CAAM,OAAA;AAAA,IAC1B,WAAA,EAAa,MAAM,KAAA,CAAM,MAAA;AAAA,IACzB,SAAA,EAAW,MAAM,KAAA,CAAM,IAAA;AAAA,IACvB,QAAA,EAAU,MAAA,CAAO,KAAA,CAAM,KAAA,CAAM,QAAQ,CAAA;AAAA,IACrC,iBAAiB,KAAA,CAAM;AAAA,GACzB,CAAE,CAAA;AAEF,EAAA,OAAO,cAAA,CAAmC;AAAA,IACxC,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"]}
|