@stridge/pay-sdk 0.1.0-alpha.0 → 0.1.0-alpha.1
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/_internal/coordinator.cjs +16 -8
- package/dist/cjs/_internal/coordinator.cjs.map +1 -1
- package/dist/cjs/_internal/coordinator.d.cts +12 -9
- package/dist/cjs/{guards-CYx283Oo.d.cts → guards-CQWGp5eP.d.cts} +12 -2
- package/dist/cjs/{guards-VkTvdL1L.cjs → guards-r1nnLHLD.cjs} +23 -1
- package/dist/cjs/guards-r1nnLHLD.cjs.map +1 -0
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.d.cts +1 -1
- package/dist/esm/_internal/coordinator.d.ts +12 -9
- package/dist/esm/_internal/coordinator.js +15 -9
- package/dist/esm/_internal/coordinator.js.map +1 -1
- package/dist/esm/{guards-CYx283Oo.d.ts → guards-CQWGp5eP.d.ts} +12 -2
- package/dist/esm/{guards-Cb0lVKgT.js → guards-CukG42GQ.js} +12 -2
- package/dist/esm/guards-CukG42GQ.js.map +1 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/package.json +1 -1
- package/dist/cjs/guards-VkTvdL1L.cjs.map +0 -1
- package/dist/esm/guards-Cb0lVKgT.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"coordinator.js","names":["value","COMPRESSED_PUBLIC_KEY_HEX","defaultSleep","sleep","defaultSleep","sleep"],"sources":["../../../src/client/constants.ts","../../../src/errors/CsrfStoreError.ts","../../../src/shared/isJsonObject.ts","../../../src/errors/SuaError.ts","../../../src/errors/SuaNetworkError.ts","../../../src/errors/guards.ts","../../../src/errors/json.ts","../../../src/errors/SuaReason.ts","../../../src/errors/parseSuaError.ts","../../../src/models/Route/entities/RouteStateDto.ts","../../../src/client/endpoints.ts","../../../src/models/PayIn/entities/PayInDripDto.ts","../../../src/models/PayIn/entities/PayInLegStateDto.ts","../../../src/models/PayIn/entities/PayInMechanismDto.ts","../../../src/models/PayIn/entities/PayInPhaseDto.ts","../../../src/models/PayIn/entities/PayInShapeDto.ts","../../../src/models/PayIn/entities/PayInStateDto.ts","../../../src/models/PayIn/entities/PayInStepSchemeDto.ts","../../../src/models/PayIn/entities/PayInStepStatusDto.ts","../../../src/models/PayIn/entities/PayInUnspendableDto.ts","../../../src/models/Route/entities/RouteStepRoleDto.ts","../../../src/payIn/constants.ts","../../../src/payIn/caip.ts","../../../src/shared/patterns.ts","../../../src/client/guards.ts","../../../src/client/serverTime.ts","../../../src/client/createCoordinatorClient.ts","../../../src/encoding/base64.ts","../../../src/encoding/hex.ts","../../../src/crypto/der.ts","../../../src/crypto/subtle.ts","../../../src/crypto/types.ts","../../../src/crypto/sign.ts","../../../src/crypto/credential.ts","../../../src/crypto/keypair.ts","../../../src/crypto/stamp.ts","../../../src/crypto/relayRequest.ts","../../../src/payIn/units.ts","../../../src/payIn/steps.ts","../../../src/polling/sleep.ts","../../../src/polling/waitForActiveWallet.ts","../../../src/polling/waitForRound.ts","../../../src/relay/buildSignRawPayloadBody.ts","../../../src/relay/constants.ts","../../../src/relay/buildPersonalSignBody.ts","../../../src/relay/decodeRelayResponse.ts","../../../src/relay/settleRelay.ts","../../../src/relay/toEvmSignature.ts","../../../src/time/constants.ts","../../../src/time/createServerClock.ts"],"sourcesContent":["/**\n * The path prefix of the sign-in routes and every route that needs a session.\n */\nexport const WALLET_API_PREFIX = \"/wallet/v1\";\n\n/**\n * The path prefix of the guest routes: the guest, its saved accounts and its checkout.\n */\nexport const PAY_API_PREFIX = \"/pay/v1\";\n\n/**\n * Every path prefix the client calls under `baseUrl`, and so every prefix a hub proxy forwards.\n */\nexport const HUB_API_PREFIXES: readonly string[] = [WALLET_API_PREFIX, PAY_API_PREFIX];\n\n/**\n * The CSRF double-submit header. Sent with the stored `csrf_token` on every `POST`, `PUT` and `DELETE`.\n */\nexport const CSRF_HEADER = \"X-CSRF-Token\";\n\n/**\n * The app attribution header. Sent with the client's `appId` on `POST /wallet/v1/credentials/session`, `GET\n * /wallet/v1/account` and `POST /wallet/v1/relay` (the routes that require it, `internal/hub/router.go`), on the linked\n * wallet routes (`POST /wallet/v1/external-accounts`, `PATCH /wallet/v1/external-accounts/{id}`), on every\n * `/wallet/v1/routes` route, on the guest routes, on the wallet offer answer and on every pay-in route. Attribution is\n * never authority: the Coordinator does not check it against `Origin`.\n */\nexport const APP_HEADER = \"X-Stridge-App\";\n\n/**\n * The idempotency header, required on route open and pay-in confirm. Repeating an open key returns its first route.\n * Repeating a confirm key with the same body returns its pay-in; a different body is IDEMPOTENCY_KEY_REUSED.\n * The Coordinator scopes the key to the identity.\n */\nexport const IDEMPOTENCY_HEADER = \"Idempotency-Key\";\n\n/**\n * The longest `Idempotency-Key` the Coordinator takes, in characters.\n */\nexport const MAX_IDEMPOTENCY_KEY_LENGTH = 128;\n\n/**\n * The most routes one `GET /wallet/v1/routes` answer holds, and the largest `limit` the client sends.\n */\nexport const MAX_ROUTE_LIST_LIMIT = 100;\n\n/**\n * The CAIP-2 chain every route leaves from, Tempo (the Coordinator's `routing/domain.SourceChain`): the only\n * `chain_id` a route step may name. A route answer with a step on any other chain is unusable.\n */\nexport const ROUTE_SOURCE_CHAIN_ID = \"eip155:4217\";\n\n/**\n * The response header the hub proxy repeats the Coordinator's `Date` in, so the client can read the Coordinator's\n * clock even where the hosting platform rewrites `Date` with its own. The client reads it before `Date`.\n */\nexport const UPSTREAM_DATE_HEADER = \"X-Stridge-Upstream-Date\";\n\n/**\n * The longest `name` a pay-in quote's `wallet` descriptor takes, in characters (pay-in guide §4.2); a longer one is\n * `400 WALLET_MALFORMED`. The client sends the name as given, so cut it to this length first.\n */\nexport const MAX_EXTERNAL_WALLET_NAME_LENGTH = 64;\n\n/**\n * The most chains a pay-in quote's `wallet.capabilities` names (pay-in guide §4.2); more is `400 WALLET_MALFORMED`.\n * The client sends the chains as given.\n */\nexport const MAX_WALLET_CAPABILITY_CHAINS = 64;\n\n/**\n * The canonical Permit2 contract, at the same address on every EVM chain: the only spender a pay-in's approvals name,\n * whether the wallet sends one (K7) or signs one (K3 to K5), and the verifying contract of a Permit2 transfer (K2).\n * Never a Stridge contract.\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\";\n\n/**\n * Relay's depository, at the same address on every EVM chain it serves: the only `to` of a coin send (mechanism `W`),\n * which deposits the wallet's native coin there through `depositNative`. Never a Stridge contract.\n */\nexport const RELAY_DEPOSITORY_ADDRESS = \"0x4cD00E387622C35bDDB9b4c962C136462338BC31\";\n\n/**\n * The selector of Relay's `depositNative(address depositor, bytes32 id)`, lowercase with its `0x`: the call of every\n * coin send.\n */\nexport const DEPOSIT_NATIVE_SELECTOR = \"0x49290c1c\";\n","import type { VerifyRoundResponseDto } from \"#/models\";\n\n/**\n * The verify succeeded but `csrf.set` threw or rejected (for example `sessionStorage` refusing a write with\n * `QuotaExceededError` or `SecurityError`). Thrown by `CoordinatorClient.verifyRound` in that case.\n *\n * The session is already open: the Coordinator set its cookie in the same answer, and no route re-issues the token.\n * So the answer is never discarded. `answer` holds it in full, `csrf_token` and `credential` included: keep the token\n * (retry the store, or hold it in memory) and carry on with the credential, or the session stays locked until its\n * absolute expiry.\n */\nexport class CsrfStoreError extends Error {\n /**\n * The verify answer, unchanged.\n */\n readonly answer: VerifyRoundResponseDto;\n\n /**\n * The value `csrf.set` threw or rejected with.\n */\n readonly cause: unknown;\n\n /**\n * Wraps the store failure. The message is always `The csrf_token could not be stored`.\n */\n constructor(answer: VerifyRoundResponseDto, cause: unknown) {\n super(\"The csrf_token could not be stored\");\n this.name = \"CsrfStoreError\";\n this.answer = answer;\n this.cause = cause;\n Object.setPrototypeOf(this, CsrfStoreError.prototype);\n }\n}\n","/**\n * Reports whether `value` is a non-null, non-array object: the shape a parsed JSON object has. Unlike the protocol\n * guards' stricter check, class instances pass. Internal: not exported from the package index.\n */\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { ErrorKindDto } from \"#/models\";\n\nimport type { SuaReason } from \"./SuaReason\";\n\n/**\n * A `SuaError`'s kind: the Coordinator's envelope `error.type`, including `ambiguous` (the relay's `202`). A failure\n * response with no readable envelope (a proxy's HTML page, an empty body) is `internal`.\n */\nexport type SuaErrorKind = ErrorKindDto;\n\n/**\n * The fields a {@link SuaError} is built from.\n */\nexport interface SuaErrorInit {\n /**\n * The HTTP status the Coordinator answered (for example `401`, or `202` for an ambiguous relay).\n */\n status: number;\n\n /**\n * The envelope's kind.\n */\n code: SuaErrorKind;\n\n /**\n * The envelope's stable code (`error.code`), normalised onto the closed {@link SuaReason} set.\n */\n reason: SuaReason;\n\n /**\n * Whole seconds to wait, from a `Retry-After` header. `undefined` when the response carried none.\n */\n retryAfterSeconds?: number;\n\n /**\n * The envelope's `request_id` (`req_…`), when it carried one.\n */\n requestId?: string;\n\n /**\n * The envelope's `param`, the request field the refusal is about, when it named one.\n */\n param?: string;\n\n /**\n * The response body: the parsed JSON when it parsed, the raw text otherwise, `undefined` when empty. For logs and\n * diagnostics only; branch on `status`, `code` and `reason`.\n */\n body?: unknown;\n}\n\n/**\n * A request got an HTTP answer that is not a usable success. Thrown by every `CoordinatorClient` method for any\n * response whose body is the error envelope, for any non-2xx response, and for a `2xx` whose body is unusable (empty,\n * not JSON, not an object, or an unexpected `204`), which has code `internal` and its `2xx` status.\n *\n * With the envelope it is the Coordinator's own answer: a refusal, or an outcome it could not assert (`code:\n * \"ambiguous\"`). Without one (`body` is not an `ErrorEnvelopeDto`) it most likely came from a hop in front of the\n * Coordinator, a proxy's `502` for example, and says nothing about whether the request reached it. `settleRelay`\n * reads a relay's `2xx` and `5xx` as unknown for that reason.\n *\n * Client transitions key on `status` plus `reason` (guide §11); `code` is the coarser kind. The fields map from the\n * envelope (`toSuaError`) as follows; the SDK keeps its own names, so `code` here is not the envelope's `code`:\n *\n * | `SuaError` | Envelope | Example |\n * |---|---|---|\n * | `code` | `error.type` | `\"rejected\"` |\n * | `reason` | `error.code`, when it is a published code; `\"\"` for a bare kind | `\"SESSION_EXPIRED\"` |\n * | `requestId` | `error.request_id` | `\"req_01J8Z…\"` |\n * | `param` | `error.param` | `\"limit\"` |\n */\nexport class SuaError extends Error {\n /**\n * The HTTP status.\n */\n readonly status: number;\n\n /**\n * The envelope's kind.\n */\n readonly code: SuaErrorKind;\n\n /**\n * The envelope's stable code (`error.code`), or `\"\"`.\n */\n readonly reason: SuaReason;\n\n /**\n * Whole seconds from `Retry-After`, when the response carried one (every rate-limit `429` does).\n */\n readonly retryAfterSeconds: number | undefined;\n\n /**\n * The Coordinator's id for the request (`req_…`), when the envelope carried one. Quote it in bug reports.\n */\n readonly requestId: string | undefined;\n\n /**\n * The request field the refusal is about, when the envelope named one.\n */\n readonly param: string | undefined;\n\n /**\n * The response body, for diagnostics.\n */\n readonly body: unknown;\n\n /**\n * Builds the error. The message reads `Coordinator answered <status> <code>`, followed by ` (<reason>)` when the\n * reason is not empty.\n */\n constructor(init: SuaErrorInit) {\n super(`Coordinator answered ${init.status} ${init.code}${init.reason ? ` (${init.reason})` : \"\"}`);\n this.name = \"SuaError\";\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.retryAfterSeconds = init.retryAfterSeconds;\n this.requestId = init.requestId;\n this.param = init.param;\n this.body = init.body;\n Object.setPrototypeOf(this, SuaError.prototype);\n }\n}\n","/**\n * The request got no HTTP answer: `fetch` rejected for a reason other than the caller's abort (DNS, TLS, a dropped\n * connection, a CORS refusal). Thrown by every `CoordinatorClient` method in that case.\n *\n * On a state-changing call the request may still have reached the Coordinator, so the outcome is unknown: never\n * re-send a registration or a relay automatically. `settleRelay` reads it as an unknown outcome.\n */\nexport class SuaNetworkError extends Error {\n /**\n * The value `fetch` rejected with.\n */\n readonly cause: unknown;\n\n /**\n * Wraps the rejection. The message is always `Network request failed`.\n */\n constructor(cause: unknown) {\n super(\"Network request failed\");\n this.name = \"SuaNetworkError\";\n this.cause = cause;\n Object.setPrototypeOf(this, SuaNetworkError.prototype);\n }\n}\n","import type { ErrorEnvelopeDto } from \"#/models\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\n\nimport { CsrfStoreError } from \"./CsrfStoreError\";\nimport { SuaError } from \"./SuaError\";\nimport { SuaNetworkError } from \"./SuaNetworkError\";\n\nimport type { SuaReason } from \"./SuaReason\";\n\n/**\n * Reports whether `value` is shaped like the Coordinator's error envelope: a non-null, non-array object whose `error`\n * is a non-null, non-array object with a string `code`. Neither the value of `code` nor `type` (of any type, or\n * absent) is checked here: `toSuaError` normalises both, so a malformed kind still reads as a refusal rather than as\n * a success body. Extra keys are allowed.\n *\n * This is how the client tells an error body from a success body on a `2xx` (the relay's `202` is an envelope; the\n * round's `202` and the registration's `202` are not).\n */\nexport function isErrorEnvelopeDto(value: unknown): value is ErrorEnvelopeDto {\n if (!isJsonObject(value)) {\n return false;\n }\n\n const error = value.error;\n\n return isJsonObject(error) && typeof error.code === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link SuaError}, optionally with a given reason.\n *\n * True when `value instanceof SuaError`, or, for a copy of the class from a second bundle, when it is an `Error`\n * whose `name` is `\"SuaError\"` and which has a numeric `status` and string `code` and `reason`. With `reason`\n * given, the error's `reason` must also equal it (`isSuaError(error, \"CREDENTIAL_EXPIRED\")`).\n */\nexport function isSuaError(value: unknown, reason?: SuaReason): value is SuaError {\n if (!(value instanceof SuaError) && !isSuaErrorCopy(value)) {\n return false;\n }\n\n return reason === undefined || value.reason === reason;\n}\n\n/**\n * Reports whether `value` is a {@link SuaNetworkError}: `instanceof`, or an `Error` whose `name` is\n * `\"SuaNetworkError\"`.\n */\nexport function isSuaNetworkError(value: unknown): value is SuaNetworkError {\n return value instanceof SuaNetworkError || (value instanceof Error && value.name === \"SuaNetworkError\");\n}\n\n/**\n * Reports whether `value` is a {@link CsrfStoreError}: `instanceof`, or an `Error` whose `name` is `\"CsrfStoreError\"`\n * and which carries an `answer` object.\n */\nexport function isCsrfStoreError(value: unknown): value is CsrfStoreError {\n if (value instanceof CsrfStoreError) {\n return true;\n }\n\n return (\n value instanceof Error && value.name === \"CsrfStoreError\" && isJsonObject((value as Error & { answer?: unknown }).answer)\n );\n}\n\n/**\n * The duck-typed half of {@link isSuaError}: a `SuaError` built by another copy of the class.\n */\nfunction isSuaErrorCopy(value: unknown): value is SuaError {\n if (!(value instanceof Error) || value.name !== \"SuaError\") {\n return false;\n }\n\n const fields = value as Error & Record<string, unknown>;\n\n return typeof fields.status === \"number\" && typeof fields.code === \"string\" && typeof fields.reason === \"string\";\n}\n","/**\n * A response body read as text and parsed once: `empty` for `\"\"`, `json` when it parsed, `text` when it did not.\n */\nexport type ParsedBody = { kind: \"empty\" } | { kind: \"json\"; value: unknown } | { kind: \"text\"; text: string };\n\n/**\n * Parses a response body read as text. Never throws.\n */\nexport function parseBody(text: string): ParsedBody {\n if (text === \"\") {\n return { kind: \"empty\" };\n }\n\n try {\n return { kind: \"json\", value: JSON.parse(text) as unknown };\n } catch {\n return { kind: \"text\", text };\n }\n}\n","/**\n * Every reason code a hub API route the client calls can name, as the Coordinator's `pkg/errs` code list publishes them\n * (guide §11 lists most of them). `\"\"` is the refusal that names no reason.\n */\nexport const SUA_REASONS = [\n \"SESSION_MISSING\",\n \"CHECKOUT_RULE_NOT_FOUND\",\n \"SESSION_EXPIRED\",\n \"SESSION_REVOKED\",\n \"CREDENTIAL_EXPIRED\",\n \"APP_SUSPENDED\",\n \"ROUND_NOT_YOURS\",\n \"INVALID_CHALLENGE_CODE\",\n \"CHALLENGE_EXHAUSTED\",\n \"WALLET_NOT_ACTIVE\",\n \"PROVIDER_DRAINING\",\n \"ACCOUNT_EJECTED\",\n \"LOGIN_NOT_PERMITTED\",\n \"IDEMPOTENCY_KEY_MISSING\",\n \"IDEMPOTENCY_KEY_REUSED\",\n \"ASSET_NOT_LISTED\",\n \"AMOUNT_MALFORMED\",\n \"DESTINATION_MALFORMED\",\n \"DESTINATION_REQUIRED\",\n \"ROUTING_UNAVAILABLE\",\n \"ROUTE_NOT_OFFERED\",\n \"ROUTE_UNAVAILABLE\",\n \"ROUTE_NOT_FOUND\",\n \"ROUTE_SOURCE_ALREADY_REPORTED\",\n \"ROUTE_TX_CLAIMED\",\n \"ROUTE_NOT_REPORTABLE\",\n \"ROUTE_TX_MISMATCH\",\n \"PAYMENT_IN_FLIGHT\",\n \"INVALID_ADDRESS\",\n \"WALLET_MALFORMED\",\n \"WALLET_WOUND_DOWN\",\n \"AMOUNT_BELOW_MINIMUM\",\n \"INSUFFICIENT_ROUTABLE_BALANCE\",\n \"QUOTE_EXPIRED\",\n \"BALANCES_STALE\",\n \"ROUTE_STATE_CONFLICT\",\n \"ROUTE_BUSY\",\n \"SIGNATURE_BATCH_INVALID\",\n \"INTERNAL\",\n \"WALLET_BRAND_UNKNOWN\",\n \"WALLET_BRAND_MISMATCH\",\n \"EXTERNAL_ACCOUNT_LIMIT\",\n \"EXTERNAL_ACCOUNT_REMOVED\",\n \"RATE_LIMITED\",\n \"APP_NOT_FOUND\",\n \"GUEST_UNKNOWN\",\n \"GUEST_HANDOFF_INVALID\",\n \"GUEST_ALREADY_MERGED\",\n \"GUEST_OFFER_CHANGED\",\n \"\",\n] as const;\n\n/**\n * A refusal's reason, closed over {@link SUA_REASONS}. Any other string the Coordinator sends is read as `\"\"`; the raw\n * envelope stays on `SuaError.body`.\n *\n * What each one means for the client:\n *\n * - `SESSION_EXPIRED` (401) — no or expired session, **or** a missing or wrong `X-CSRF-Token`. If `GET\n * /wallet/v1/session` then answers `200`, the `csrf_token` is lost (\"session locked\"); otherwise there is no session.\n * - `SESSION_REVOKED` (401) — signed out elsewhere: clear the keypair and the token.\n * - `CREDENTIAL_EXPIRED` (401, relay only) — the keypair lapsed (expiry ≤ now + 5 s): renew, then re-confirm and\n * re-sign with a new `signedAtMs`.\n * - `APP_SUSPENDED` (403) — the `app_id` is unknown, malformed or inactive: a configuration error, never retried.\n * - `ROUND_NOT_YOURS` (403) — a renewal round verified without its session or `csrf_token`: the token is lost.\n * - `INVALID_CHALLENGE_CODE` (400) — a wrong code (the round survives, retype), or an unknown, expired or spent\n * round (on registration: start a new round).\n * - `CHALLENGE_EXHAUSTED` (429) — five wrong codes: the round is burned, start again.\n * - `WALLET_NOT_ACTIVE` (409) — the wallet is still provisioning: poll `GET /wallet/v1/account`, then retry (a\n * registration before the credential's `expires_at`, a route open under the same key).\n * - `PROVIDER_DRAINING` (409) and `ACCOUNT_EJECTED` (403) — SigningRouter state: show an error.\n * - `RATE_LIMITED` (429, verify and relay only) — Stridge's provider budget is spent; read `Retry-After`. The hub's own\n * rate limits stay reasonless (`\"\"`).\n * - `APP_NOT_FOUND` (404) — `GET /wallet/v1/apps/{id}` names no app.\n * - `\"\"` — any refusal without a published reason. Notably a rate-limit `429` (read `Retry-After`), a `403` from\n * SigningRouter's own rate limit or an enclave refusal (new round after backoff), a `500`, and the relay's `202`\n * ambiguous answer.\n *\n * Pay-ins also name `WALLET_MALFORMED`, `INSUFFICIENT_ROUTABLE_BALANCE`, `QUOTE_EXPIRED`,\n * `BALANCES_STALE`, `ROUTE_STATE_CONFLICT`, `ROUTE_BUSY` and `SIGNATURE_BATCH_INVALID`.\n * `AMOUNT_BELOW_MINIMUM` (422, smart-route quote) means the request is too small for these sources.\n * `error.minimum_amount`, when present, is the threshold in requested-asset base units.\n * `DESTINATION_REQUIRED` (400) is a guest quote sent without `destination`: a guest only checks out, so it is a client\n * bug, never retried.\n * `WALLET_WOUND_DOWN` is permanent, never a wallet-provisioning retry. A reasonless `500` retains its\n * HTTP status and never proves a confirm or adjust did nothing.\n *\n * The route reasons (`/wallet/v1/routes`, `pkg/errs/codes.go`):\n *\n * - `IDEMPOTENCY_KEY_MISSING` (400, open and pay-in confirm) — no `Idempotency-Key` arrived. The client never sends either without\n * one, so a proxy dropped the header: a configuration error.\n * - `IDEMPOTENCY_KEY_REUSED` (409) — on an open, core holds the key for another account. On a pay-in confirm, the key\n * names another body. Retry only with the same body and key; use a new key only for a new quote.\n * - `ASSET_NOT_LISTED` (400) — the source or destination asset is not in the token registry.\n * - `AMOUNT_MALFORMED` (400) — the amount is not a canonical positive decimal string of base units.\n * - `DESTINATION_MALFORMED` (400) — `destination.address` is not an EVM address.\n * - `ROUTING_UNAVAILABLE` (409) — core's routing is unreachable or failing (transient: retry later, an open under the\n * same key), or the app has no routing tenant in core (a configuration error).\n * - `ROUTE_NOT_OFFERED` (422) — the pair is never routed: the source is not on Tempo or the destination is not on an\n * EVM chain.\n * - `ROUTE_UNAVAILABLE` (422) — no provider routes this pair or amount right now: offer another destination or amount.\n * - `ROUTE_NOT_FOUND` (404) — no such route, or another account's.\n * - `ROUTE_SOURCE_ALREADY_REPORTED` (409) — the route already has a different source transaction.\n * - `ROUTE_TX_CLAIMED` (409) — the transaction is already another route's source.\n * - `ROUTE_NOT_REPORTABLE` (409) — the route's state no longer takes a source report.\n * - `ROUTE_TX_MISMATCH` (422) — the chain shows the transaction from another wallet or to another contract.\n * - `PAYMENT_IN_FLIGHT` (409, a route open and a pay-in quote or confirm) — another route of the tenant for the same\n * `payment_ref` may still move funds: follow that payment, never pay again.\n *\n * The external wallet and guest reasons (`pkg/errs/codes.go`):\n *\n * - `INVALID_ADDRESS` (400) — the address is not valid for its `chain_kind`.\n * - `WALLET_BRAND_UNKNOWN` (400) — the brand slug is not in the registry.\n * - `WALLET_BRAND_MISMATCH` (400) — the brand does not support the connector or the chain kind.\n * - `EXTERNAL_ACCOUNT_LIMIT` (409) — the account or the guest already keeps 20 wallets, or the wallets a wallet offer\n * answer accepts do not fit in the account (nothing changed).\n * - `EXTERNAL_ACCOUNT_REMOVED` (409) — the address was removed and stays removed unless the user explicitly saves it\n * again with `reconnect: true`.\n * - `GUEST_OFFER_CHANGED` (409, the wallet offer answer only) — the offer holds a wallet the answer's `shown` does not\n * name: nothing changed; read the session and ask again.\n * - `GUEST_UNKNOWN` (401, guest routes only) — the guest cookie names no live guest, or the guest token is missing or\n * wrong. Never a session refusal: it says nothing about the session.\n * - `GUEST_HANDOFF_INVALID` (400) and `GUEST_ALREADY_MERGED` (409) — the handoff and merge routes, which the hub does\n * not call.\n */\nexport type SuaReason = (typeof SUA_REASONS)[number];\n","import type { ErrorBodyDto, ErrorKindDto } from \"#/models\";\n\nimport { isErrorEnvelopeDto } from \"./guards\";\nimport { parseBody } from \"./json\";\nimport { SuaError, type SuaErrorKind } from \"./SuaError\";\nimport { SUA_REASONS, type SuaReason } from \"./SuaReason\";\n\n/**\n * A failure response whose body has already been read, for {@link toSuaError}. The client reads each body once, so\n * it hands the parts over rather than the `Response`.\n */\nexport interface SuaErrorResponse {\n /**\n * The HTTP status.\n */\n status: number;\n\n /**\n * The raw `Retry-After` header value, or `null` when absent.\n */\n retryAfter: string | null;\n\n /**\n * The raw body text, `\"\"` when empty.\n */\n body: string;\n}\n\n/**\n * The six envelope kinds the Coordinator names (`pkg/errs/errs.go`).\n */\nconst ERROR_KINDS: readonly ErrorKindDto[] = [\"invalid\", \"not_found\", \"conflict\", \"rejected\", \"ambiguous\", \"internal\"];\n\n/**\n * The obsolete asctime HTTP-date form (`Sun Nov 6 08:49:37 1994`), RFC 9110 §5.6.7.\n */\nconst ASCTIME_DATE = /^[A-Za-z]{3} [A-Za-z]{3} [ \\d]\\d \\d{2}:\\d{2}:\\d{2} \\d{4}$/;\n\n/**\n * Builds a {@link SuaError} from a failure response that was already read.\n *\n * 1. `body` is parsed as JSON when it is not empty; a parse failure keeps the raw text.\n * 2. When the parsed value is an error envelope (`isErrorEnvelopeDto`):\n * - `code` is `error.type` when it is one of the six `ErrorKindDto` values, and `\"internal\"` otherwise;\n * - `reason` is `error.code` when it is one of `SUA_REASONS`, and `\"\"` otherwise (the bare kind a refusal with no\n * stable code carries, such as a rate-limit `429`'s `\"rejected\"`, or a code the SDK does not list);\n * - `requestId` is `error.request_id` and `param` is `error.param`, each when it is a non-empty string.\n * 3. Otherwise (no envelope: empty body, HTML, another JSON shape) `code` is `\"internal\"` and `reason` is `\"\"`,\n * whatever the status.\n * 4. `retryAfterSeconds` is `parseRetryAfter(retryAfter)`.\n * 5. `SuaError.body` is the parsed JSON, else the raw text, else `undefined` for an empty body.\n *\n * Never throws.\n */\nexport function toSuaError(response: SuaErrorResponse): SuaError {\n const parsed = parseBody(response.body);\n let code: SuaErrorKind = \"internal\";\n let reason: SuaReason = \"\";\n let requestId: string | undefined;\n let param: string | undefined;\n let body: unknown;\n\n if (parsed.kind === \"json\") {\n body = parsed.value;\n if (isErrorEnvelopeDto(parsed.value)) {\n const error: Partial<Record<keyof ErrorBodyDto, unknown>> = parsed.value.error;\n code = toErrorKind(error.type);\n reason = toReason(error.code);\n requestId = toNonEmptyString(error.request_id);\n param = toNonEmptyString(error.param);\n }\n } else if (parsed.kind === \"text\") {\n body = parsed.text;\n }\n\n return new SuaError({\n status: response.status,\n code,\n reason,\n retryAfterSeconds: parseRetryAfter(response.retryAfter),\n requestId,\n param,\n body,\n });\n}\n\n/**\n * Reads a failure `Response` into a {@link SuaError}: reads `response.text()` once (a read failure counts as an empty\n * body), takes `Retry-After` from `response.headers`, and delegates to {@link toSuaError}.\n *\n * Consumes the body. Never rejects.\n */\nexport async function parseSuaError(response: Response): Promise<SuaError> {\n let body = \"\";\n try {\n body = await response.text();\n } catch {\n body = \"\";\n }\n\n let retryAfter: string | null = null;\n try {\n retryAfter = response.headers.get(\"Retry-After\");\n } catch {\n retryAfter = null;\n }\n\n return toSuaError({ status: response.status, retryAfter, body });\n}\n\n/**\n * Reads a `Retry-After` header value (RFC 9110 §10.2.3) into whole seconds to wait.\n *\n * - A non-negative integer of decimal digits (`\"30\"`, surrounding whitespace allowed) is returned as that number.\n * This is the only form the Coordinator sends (`ceil` of the bucket window, at least 1).\n * - An HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`) is returned as `max(0, ceil((date - nowMs) / 1000))`.\n * - `null`, `\"\"`, a negative or fractional number, or anything unparseable returns `undefined`.\n *\n * @param value The raw header value.\n * @param nowMs The current time in ms since the epoch, for the HTTP-date form. Defaults to `Date.now()`.\n */\nexport function parseRetryAfter(value: string | null, nowMs?: number): number | undefined {\n if (value === null) {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = Number(trimmed);\n\n return Number.isSafeInteger(seconds) ? seconds : undefined;\n }\n\n /**\n * Every HTTP-date form (IMF-fixdate, RFC 850, asctime) starts with a day name. Requiring it keeps `Date.parse`'s\n * lenient reading of strings such as `\"-1\"` or `\"1.5\"` out.\n */\n if (!/^[A-Za-z]{3,9},?\\s/.test(trimmed)) {\n return undefined;\n }\n\n /**\n * The asctime form carries no zone but is UTC by definition; `Date.parse` would read it as local time.\n */\n const dateMs = Date.parse(ASCTIME_DATE.test(trimmed) ? `${trimmed} GMT` : trimmed);\n if (Number.isNaN(dateMs)) {\n return undefined;\n }\n\n return Math.max(0, Math.ceil((dateMs - (nowMs ?? Date.now())) / 1000));\n}\n\n/**\n * Narrows an envelope's `type` onto {@link ErrorKindDto}, reading an absent or unknown kind as `internal`.\n */\nfunction toErrorKind(type: unknown): SuaErrorKind {\n return ERROR_KINDS.find((kind) => kind === type) ?? \"internal\";\n}\n\n/**\n * Narrows an envelope's `code` onto {@link SuaReason}, reading a bare kind, an absent or an unlisted code as `\"\"`.\n */\nfunction toReason(code: unknown): SuaReason {\n return SUA_REASONS.find((known) => known === code) ?? \"\";\n}\n\n/**\n * Returns `value` when it is a non-empty string, else `undefined`.\n */\nfunction toNonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n","/**\n * Every state a route can be in, in the order a route moves through them, as the Coordinator lists core's route\n * states (`internal/routing/domain/routes.go` `States`). `GET /wallet/v1/routes?status=…` refuses any other name.\n */\nexport const ROUTE_STATES = [\n \"planned\",\n \"expired\",\n \"submitted\",\n \"awaiting_destination\",\n \"stalled\",\n \"completed\",\n \"refunded\",\n \"failed\",\n \"unresolved\",\n] as const;\n\n/**\n * A route state this client knows (`apidoc.Route.status`), one of {@link ROUTE_STATES}. A route's own `status` may also\n * be one core added after this client was built; such a state means the funds are in flight, never failed or done.\n *\n * - `planned` — opened: its steps are ready to sign and no source transaction is reported yet.\n * - `expired` — still `planned` when `expires_at` passed. A late source report is still followed.\n * - `submitted` — the source transaction is reported and core follows it.\n * - `awaiting_destination` — the source side is done; the funds are on their way to the destination.\n * - `stalled` — taking longer than expected. **Never a failure**: the funds are in flight.\n * - `completed` — delivered; `actual_output` and `destination_tx` name what arrived.\n * - `refunded` — the funds went back to the source address.\n * - `failed` — the route failed.\n * - `unresolved` — core cannot tell the outcome yet. **Never a failure**: the funds are in flight.\n */\nexport type RouteStateDto = (typeof ROUTE_STATES)[number];\n","import type { paths } from \"#/generated/hub\";\n\n/**\n * A path template the Coordinator's hub API document (`src/generated/openapi.json`) defines.\n */\ntype HubPath = keyof paths;\n\n/**\n * The HTTP verbs the client sends, as the document spells them.\n */\ntype HubVerb = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\n/**\n * The verbs the document defines on one path. A verb the path does not take is `never` there.\n */\ntype HubVerbOf<P extends HubPath> = {\n [V in HubVerb]: [NonNullable<paths[P][V]>] extends [never] ? never : V;\n}[HubVerb];\n\n/**\n * One endpoint: a verb and a path template the document pairs. A wrong path or verb fails to compile.\n */\ntype HubEndpoint = { [P in HubPath]: readonly [HubVerbOf<P>, P] }[HubPath];\n\n/**\n * Every hub endpoint the client calls, keyed by the client method that calls it. The single place a path is spelled;\n * the `satisfies` check holds each verb and path to the generated document.\n */\nconst HUB_ENDPOINTS = {\n resolveGuestCheckout: [\"post\", \"/pay/v1/checkouts/resolve\"],\n resolveCheckout: [\"post\", \"/wallet/v1/checkouts/resolve\"],\n listGuestAssets: [\"get\", \"/pay/v1/assets\"],\n listAssets: [\"get\", \"/wallet/v1/assets\"],\n startRound: [\"post\", \"/wallet/v1/auth-rounds\"],\n getRound: [\"get\", \"/wallet/v1/auth-rounds/{id}\"],\n verifyRound: [\"post\", \"/wallet/v1/auth-rounds/{id}/verify\"],\n registerKeypair: [\"post\", \"/wallet/v1/credentials/session\"],\n getSession: [\"get\", \"/wallet/v1/session\"],\n signOut: [\"delete\", \"/wallet/v1/session\"],\n getWallet: [\"get\", \"/wallet/v1/account\"],\n relay: [\"post\", \"/wallet/v1/relay\"],\n saveExternalAccount: [\"post\", \"/wallet/v1/external-accounts\"],\n markExternalAccountUsed: [\"patch\", \"/wallet/v1/external-accounts/{id}\"],\n removeExternalAccount: [\"delete\", \"/wallet/v1/external-accounts/{id}\"],\n answerWalletOffer: [\"patch\", \"/wallet/v1/session\"],\n quoteRoute: [\"post\", \"/wallet/v1/routes/quotes\"],\n openRoute: [\"post\", \"/wallet/v1/routes\"],\n getRoute: [\"get\", \"/wallet/v1/routes/{id}\"],\n listRoutes: [\"get\", \"/wallet/v1/routes\"],\n reportRouteSource: [\"post\", \"/wallet/v1/routes/{id}/source\"],\n getExternalBalances: [\"get\", \"/wallet/v1/balances\"],\n warmExternalBalances: [\"post\", \"/wallet/v1/balances\"],\n quoteTopUp: [\"post\", \"/wallet/v1/smart-routes\"],\n quoteCheckout: [\"post\", \"/wallet/v1/smart-routes\"],\n getPayIn: [\"get\", \"/wallet/v1/smart-routes/{id}\"],\n confirmPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/confirm\"],\n adjustPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/adjust\"],\n cancelPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/cancel\"],\n createGuestHandoff: [\"post\", \"/pay/v1/handoffs\"],\n mergeGuestSession: [\"post\", \"/pay/v1/session/merge\"],\n openGuest: [\"post\", \"/pay/v1/session\"],\n saveGuestWallet: [\"post\", \"/pay/v1/external-accounts\"],\n removeGuestWallet: [\"delete\", \"/pay/v1/external-accounts/{id}\"],\n markGuestWalletUsed: [\"patch\", \"/pay/v1/external-accounts/{id}\"],\n getGuestExternalBalances: [\"get\", \"/pay/v1/balances\"],\n warmGuestExternalBalances: [\"post\", \"/pay/v1/balances\"],\n quoteGuestPayIn: [\"post\", \"/pay/v1/smart-routes\"],\n getGuestPayIn: [\"get\", \"/pay/v1/smart-routes/{id}\"],\n confirmGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/confirm\"],\n adjustGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/adjust\"],\n cancelGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/cancel\"],\n} as const satisfies Record<string, HubEndpoint>;\n\n/**\n * The name of a hub endpoint the client calls.\n */\nexport type HubEndpointName = keyof typeof HUB_ENDPOINTS;\n\n/**\n * The upper-case verb a request sends.\n */\nexport type HubMethod = Uppercase<HubVerb>;\n\n/**\n * The verb and the path (after `baseUrl`) of one call.\n */\nexport interface HubTarget {\n /**\n * The HTTP verb.\n */\n method: HubMethod;\n\n /**\n * The path, the id already encoded, and the query string when the call takes one.\n */\n path: string;\n}\n\n/**\n * Builds one call's verb and path from its endpoint. `id` replaces the template's `{id}` and must already be encoded;\n * `query` is appended as given (`\"\"` or `?a=b`).\n */\nexport function hubTarget(name: HubEndpointName, id?: string, query = \"\"): HubTarget {\n const [verb, template] = HUB_ENDPOINTS[name];\n const path = id === undefined ? template : template.replace(\"{id}\", id);\n\n return { method: verb.toUpperCase() as HubMethod, path: `${path}${query}` };\n}\n","/**\n * Every state of the gas Stridge sends a wallet for an `R` leg (pay-in guide §5.3.2, §6.2), in order.\n */\nexport const PAY_IN_DRIP_STATES = [\"held\", \"sending\", \"landed\"] as const;\n\n/**\n * An `R` leg's `drip`, one of {@link PAY_IN_DRIP_STATES}: `held` until every other step is done, then `sending`, then\n * `landed` once the gas is in the wallet and the approval can be sent.\n */\nexport type PayInDripDto = (typeof PAY_IN_DRIP_STATES)[number];\n","/**\n * Every state a pay-in leg can be in (pay-in guide §7.2), as core names them, grouped as the guide shows them.\n */\nexport const PAY_IN_LEG_STATES = [\n \"planned\",\n \"needs_signature\",\n \"needs_approval\",\n \"approving\",\n \"submitting\",\n \"submitted\",\n \"in_flight\",\n \"refunding\",\n \"voiding\",\n \"filled\",\n \"refunded\",\n \"voided\",\n \"dropped\",\n \"needs_support\",\n \"written_off\",\n] as const;\n\n/**\n * A pay-in leg state this client knows, one of {@link PAY_IN_LEG_STATES}. A leg's own `status` may also be one core\n * added after this client was built; such a state means the funds may be moving, never failed.\n *\n * - `planned`, `needs_signature` — waiting for a signature.\n * - `needs_approval` (a wallet-sent approval is offered, or the drip is on its way), `approving` (its hash is\n * reported, core verifies it) — waiting for the approval.\n * - `submitting`, `submitted`, `in_flight` — in progress.\n * - `refunding`, `voiding` — in progress, returning funds.\n * - `filled` — arrived (`actual_output`).\n * - `refunded` — returned to the wallet (`refund_tx`, `refund_amount`).\n * - `voided`, `dropped` — not used: no funds moved, or they were returned.\n * - `needs_support`, `written_off` — Stridge is looking into it. **Never a failure.**\n */\nexport type PayInLegStateDto = (typeof PAY_IN_LEG_STATES)[number];\n","/**\n * Every mechanism a pay-in leg can pull funds with (pay-in guide §6), as core names them.\n */\nexport const PAY_IN_MECHANISMS = [\"P\", \"C\", \"B\", \"G\", \"N\", \"R\", \"S\", \"D\", \"W\", \"T\", \"X\", \"Y\", \"U\", \"V\"] as const;\n\n/**\n * How a pay-in leg pulls funds, one of {@link PAY_IN_MECHANISMS}. A leg's or a holding's `mechanism` may also be one\n * core added after this client was built.\n *\n * - `P` — an EIP-3009 transfer authorization: one `eip712` signature (K1); Stridge submits it and pays the gas.\n * - `C` — a Permit2 transfer for a token that already allows Permit2: one `eip712` signature (K2).\n * - `B` — a signed approval of Permit2 (K3, K4 or K5) that Stridge sends, then a Permit2 transfer (K2): two `eip712`\n * signatures at quote time.\n * - `G` — the wallet sends `approve(Permit2)` (K7) paying its gas from the token, then signs a Permit2 transfer (K2).\n * - `N` — the wallet sends `approve(Permit2)` (K7) paying its own gas, then signs a Permit2 transfer (K2).\n * - `R` — as `N`, after Stridge sends the wallet exactly one approval's gas (the drip).\n * - `S` — a sponsored Solana transaction the wallet signs and core broadcasts (K8); Stridge's fee payer pays its fee.\n * - `D` — a Calibur batch from an account already delegated through EIP-7702: one `eip712` signature (K6).\n * - `W` — a coin send: after confirm, the wallet sends its native coin to Relay's depository itself, paying its own\n * gas (K7, `depositNative`). Its leg has no step in the quote.\n * - `T` — a same-chain Tempo holding, catalog information rather than a supported pull mechanism.\n * - `X` — the checkout's own asset on its own chain: after confirm, the wallet sends it straight to the destination\n * itself, paying its own gas. Its transfer step appears and is answered as `W`'s is.\n * - `Y` — `X` with the gas paid by the wallet's gas station.\n * - `U` — `X` once Stridge sent the wallet exactly that transfer's gas (the drip); its step appears once the drip landed.\n * - `V` — the checkout's own asset on its own chain, already approved for Permit2: one `eip712` signature, a plain\n * Permit2 `PermitTransferFrom` (K2) to Stridge's relayer, which sends it to the destination and pays the gas.\n *\n * `X`, `Y`, `U` and `V` show only in a holding's `payable_mechanisms`, never in its `mechanisms`.\n */\nexport type PayInMechanismDto = (typeof PAY_IN_MECHANISMS)[number];\n","/**\n * Every phase a pay-in reports (pay-in guide §5.3), as core names them.\n */\nexport const PAY_IN_PHASES = [\"executing\", \"winding_down\"] as const;\n\n/**\n * A pay-in's `phase`, one of {@link PAY_IN_PHASES}.\n *\n * - `executing` — running.\n * - `winding_down` — stopping after a failure or a cancel while some legs are still live: keep polling until the state\n * is terminal.\n */\nexport type PayInPhaseDto = (typeof PAY_IN_PHASES)[number];\n","/**\n * Every shape a pay-in plan takes (pay-in guide §5.3), as core names them.\n */\nexport const PAY_IN_SHAPES = [\"single_leg\", \"multi_leg\"] as const;\n\n/**\n * A pay-in's `shape`, one of {@link PAY_IN_SHAPES}: one leg, or several legs across wallets and chains.\n */\nexport type PayInShapeDto = (typeof PAY_IN_SHAPES)[number];\n","/**\n * Every state a pay-in can be in (pay-in guide §7.1), as core names them.\n */\nexport const PAY_IN_STATES = [\n \"requires_confirmation\",\n \"requires_action\",\n \"processing\",\n \"on_hold\",\n \"completed\",\n \"failed\",\n \"canceled\",\n \"expired\",\n] as const;\n\n/**\n * The states a pay-in never leaves: polling stops at them.\n */\nexport const PAY_IN_TERMINAL_STATES = [\"completed\", \"failed\", \"canceled\", \"expired\"] as const;\n\n/**\n * A pay-in state this client knows, one of {@link PAY_IN_STATES}. A pay-in's own `status` may also be one core added\n * after this client was built; such a state means the funds may be moving, never failed or done.\n *\n * - `requires_confirmation` — quoted: sign every step and confirm before `expires_at`.\n * - `requires_action` — core needs a step from a wallet: do `required_steps[0]`, then adjust.\n * - `processing` — funds are moving, or core waits on a chain, a bridge or the drip. **Never a failure.**\n * - `on_hold` — a leg needs Stridge's support and nothing else is moving: Stridge's to resolve. **Never a failure.**\n * - `completed` — done; `delivered` is what reached the SUA account, which may be less than `amount`.\n * - `failed` — it could not complete; legs that moved funds are refunded (`refund_tx`, `refund_amount`).\n * - `canceled` — stopped (`cancellation_reason`).\n * - `expired` — never confirmed in time.\n */\nexport type PayInStateDto = (typeof PAY_IN_STATES)[number];\n\n/**\n * A terminal pay-in state, one of {@link PAY_IN_TERMINAL_STATES}.\n */\nexport type PayInTerminalStateDto = (typeof PAY_IN_TERMINAL_STATES)[number];\n","/**\n * Every scheme core issues to external wallets (pay-in guide §8). The step model also defines\n * `eip7702_authorization` and `tempo_transaction`, which core never issues to an external wallet.\n */\nexport const PAY_IN_STEP_SCHEMES = [\"eip712\", \"evm_transaction\", \"solana_transaction\"] as const;\n\n/**\n * A pay-in step's `scheme`, one of {@link PAY_IN_STEP_SCHEMES}: which wallet call the step takes.\n *\n * - `eip712` — `eth_signTypedData_v4` over the payload, unchanged (K1 to K6).\n * - `evm_transaction` — `eth_sendTransaction` with exactly the payload's fields; the wallet sends it (K7).\n * - `solana_transaction` — a sponsored Solana message; parsing does not enable signing.\n *\n * A step whose scheme is not one of them is never signed: cancel the pay-in and report it.\n */\nexport type PayInStepSchemeDto = (typeof PAY_IN_STEP_SCHEMES)[number];\n","/**\n * Every status a pay-in step can have (pay-in guide §7.3), as core names them.\n */\nexport const PAY_IN_STEP_STATUSES = [\n \"unsigned\",\n \"signed\",\n \"submitted\",\n \"invalid\",\n \"expired\",\n \"refused\",\n \"superseded\",\n \"dead\",\n] as const;\n\n/**\n * A pay-in step's `status`, one of {@link PAY_IN_STEP_STATUSES}. Only the steps `required_steps` names, and a quote's\n * `steps` at confirm, are acted on, whatever their status says.\n *\n * - `unsigned` — waiting for the wallet.\n * - `signed` — the signature was received.\n * - `submitted` — sent on chain (a wallet-sent approval, or an approval core sent); may carry `tx_hash`.\n * - `invalid` — the signature did not verify for the leg's source address (`reason`); a replacement follows in\n * `required_steps`.\n * - `expired` — not done before the step's `expires_at`.\n * - `refused` — the chain or the provider refused it (`reason`).\n * - `superseded` — a newer step replaced it before it was used.\n * - `dead` — the pay-in or its leg ended before it was used.\n */\nexport type PayInStepStatusDto = (typeof PAY_IN_STEP_STATUSES)[number];\n","/**\n * Every reason a holding goes unused (pay-in guide §5.3.1), as core names them.\n */\nexport const PAY_IN_UNSPENDABLE_REASONS = [\n \"route_unverifiable\",\n \"native_coin\",\n \"smart_account\",\n \"no_free_route\",\n \"drip_refused\",\n \"approval_required\",\n \"over_sponsor_cap\",\n] as const;\n\n/**\n * Why a holding goes unused, one of {@link PAY_IN_UNSPENDABLE_REASONS}.\n *\n * - `route_unverifiable` — the route could not be verified.\n * - `native_coin` — native coins (ETH, BNB, SOL, …) are never pulled.\n * - `smart_account` — the address is a smart-contract account on that chain.\n * - `no_free_route` — no gas-free mechanism exists for this token from this wallet.\n * - `drip_refused` — it needs a wallet-sent approval and Stridge cannot fund its gas now.\n * - `approval_required` — it needs a wallet-sent approval on a chain where core cannot plan one.\n * - `over_sponsor_cap` — using it would exceed the sponsored-gas allowance.\n */\nexport type PayInUnspendableReasonDto = (typeof PAY_IN_UNSPENDABLE_REASONS)[number];\n\n/**\n * A holding a pay-in plan does not use, and why (pay-in guide §5.3.1). Shown so a large balance that was not used is\n * not a mystery.\n */\nexport interface PayInUnspendableDto {\n /**\n * The holding's CAIP-19 asset.\n */\n asset: string;\n\n /**\n * The holding's amount, in its base units, as a decimal string. It may exceed 2^53.\n */\n amount: string;\n\n /**\n * Why it goes unused: one of `PAY_IN_UNSPENDABLE_REASONS`, or one core added later.\n */\n reason: PayInUnspendableReasonDto | (string & {});\n}\n","/**\n * Every role a route step can have, as core names them. The client refuses a route answer with any other role, so a\n * step it cannot name never reaches a signature.\n */\nexport const ROUTE_STEP_ROLES = [\"approve\", \"provider\", \"transfer\"] as const;\n\n/**\n * A route step's `role` (`apidoc.RouteStep.role`), closed over {@link ROUTE_STEP_ROLES}.\n *\n * - `approve` — an exact-amount ERC-20 approval of the source asset for the provider call that follows it.\n * - `provider` — the provider's call that moves the funds. Its hash is the one to report.\n * - `transfer` — a plain transfer, the only step of a route core settles itself. Its hash is the one to report.\n */\nexport type RouteStepRoleDto = (typeof ROUTE_STEP_ROLES)[number];\n","/**\n * The CAIP-2 namespace of EVM chains (`eip155:1`, `eip155:56`, Tempo's `eip155:4217`): its reference is the decimal\n * chain id.\n */\nexport const EVM_CAIP_NAMESPACE = \"eip155\";\n\n/**\n * The most decimals a token amount may have: an ERC-20 token's `decimals` is a `uint8`. An external holding naming\n * more is unusable, and the base-unit helpers refuse more.\n */\nexport const MAX_TOKEN_DECIMALS = 255;\n\n/**\n * Every kind of pay-in step (pay-in guide §6.1), told apart by the step's `scheme` and, for `eip712`, the payload's\n * `primaryType`. The kit never builds one; it recognises them to choose the wallet call and the copy, and never signs a\n * step whose kind it cannot name.\n *\n * - `K1` — an EIP-3009 transfer authorization (`ReceiveWithAuthorization`), mechanism\n * `P`.\n * - `K2` — a Permit2 transfer (`PermitBatchWitnessTransferFrom`, or `PermitWitnessTransferFrom`): mechanism `C`, and\n * the second step of `B`, `G`, `N` and `R`; or a plain `PermitTransferFrom` with no witness: mechanism `V`.\n * - `K3` — an EIP-2612 `Permit` (`owner, spender, value, nonce, deadline`) approving Permit2, the first step of `B`.\n * - `K4` — a DAI-style `Permit` (`holder, spender, nonce, expiry, allowed`) approving Permit2, the first step of `B`.\n * - `K5` — a Polygon `MetaTransaction` whose call approves Permit2, the first step of `B`.\n * - `K6` — a Calibur `SignedBatchedCall`, mechanism `D`.\n * - `K7` — a transaction the wallet sends itself (`evm_transaction`): `approve(Permit2, max)` for mechanisms `G`, `N`\n * and `R`, or a coin send (`depositNative` to Relay's depository) for mechanism `W`.\n * - `K8` — a sponsored Solana transaction, signed by the user and broadcast by Core.\n */\nexport const PAY_IN_STEP_KINDS = [\"K1\", \"K2\", \"K3\", \"K4\", \"K5\", \"K6\", \"K7\", \"K8\"] as const;\n","import { EVM_CAIP_NAMESPACE } from \"./constants\";\n\nimport type { Caip19Parts, Caip2Parts } from \"./types\";\n\n/**\n * A CAIP-2 chain id: a namespace of 3 to 8 lowercase letters, digits or hyphens, `:`, then a reference of 1 to 32\n * letters, digits, hyphens or underscores.\n */\nconst CAIP2_PATTERN = /^([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32})$/;\n\n/**\n * A CAIP-19 asset id: a CAIP-2 chain id, `/`, an asset namespace of 3 to 8 lowercase letters, digits or hyphens, `:`,\n * then an asset reference of 1 to 128 letters, digits, hyphens, dots or `%`. No token id: pay-ins move fungible\n * assets only.\n */\nconst CAIP19_PATTERN = /^(([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32}))\\/([-a-z0-9]{3,8}):([-.%a-zA-Z0-9]{1,128})$/;\n\n/**\n * An `eip155` reference: a decimal chain id without a leading zero.\n */\nconst EVM_CHAIN_REFERENCE_PATTERN = /^[1-9][0-9]*$/;\n\n/**\n * Splits a CAIP-2 chain id into its namespace and reference, or `null` when `chain` is not one. Pure.\n *\n * @example parseCaip2(\"eip155:56\") → { namespace: \"eip155\", reference: \"56\" }\n * @example parseCaip2(\"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\") → { namespace: \"solana\", reference: \"5eykt4Us…KqZKvdp\" }\n */\nexport function parseCaip2(chain: string): Caip2Parts | null {\n if (typeof chain !== \"string\") {\n return null;\n }\n const match = CAIP2_PATTERN.exec(chain);\n if (match === null) {\n return null;\n }\n\n return { namespace: match[1], reference: match[2] };\n}\n\n/**\n * Splits a CAIP-19 asset id into its chain and asset parts, or `null` when `asset` is not one. An asset id with a\n * token id (`…/erc721:0x…/1`) is not a pay-in asset and reads as `null`. Pure.\n *\n * @example parseCaip19(\"eip155:1/slip44:60\") → { chain: \"eip155:1\", namespace: \"eip155\", reference: \"1\",\n * assetNamespace: \"slip44\", assetReference: \"60\" }\n */\nexport function parseCaip19(asset: string): Caip19Parts | null {\n if (typeof asset !== \"string\") {\n return null;\n }\n const match = CAIP19_PATTERN.exec(asset);\n if (match === null) {\n return null;\n }\n\n return {\n chain: match[1],\n namespace: match[2],\n reference: match[3],\n assetNamespace: match[4],\n assetReference: match[5],\n };\n}\n\n/**\n * The hex chain id of an EVM CAIP-2 chain, lowercase and without leading zeros: what `wallet_switchEthereumChain` takes\n * and what keys `wallet_getCapabilities`. `null` when `chain` is not an `eip155` chain with a decimal chain id. Pure.\n *\n * @example evmChainHex(\"eip155:56\") === \"0x38\"\n * @example evmChainHex(\"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\") === null\n */\nexport function evmChainHex(chain: string): string | null {\n const reference = evmChainReference(chain);\n\n return reference === null ? null : `0x${BigInt(reference).toString(16)}`;\n}\n\n/**\n * The numeric chain id of an EVM CAIP-2 chain, as viem and wagmi take it. `null` when `chain` is not an `eip155` chain\n * with a decimal chain id, or when the id is too large to be a safe integer. Pure.\n *\n * @example evmChainNumber(\"eip155:4217\") === 4217\n */\nexport function evmChainNumber(chain: string): number | null {\n const reference = evmChainReference(chain);\n if (reference === null) {\n return null;\n }\n const chainId = Number(reference);\n\n return Number.isSafeInteger(chainId) ? chainId : null;\n}\n\n/**\n * The decimal chain id of an EVM CAIP-2 chain, or `null` when `chain` is not one.\n */\nfunction evmChainReference(chain: string): string | null {\n const parts = parseCaip2(chain);\n if (parts === null || parts.namespace !== EVM_CAIP_NAMESPACE || !EVM_CHAIN_REFERENCE_PATTERN.test(parts.reference)) {\n return null;\n }\n\n return parts.reference;\n}\n","/**\n * EVM calldata: `0x` and whole bytes of hex, either case (`0x` alone for none), as core writes it with\n * `hexutil.Encode`. A route step's `data` and a pay-in approval's `data` both match it. Internal: not exported from\n * the package index.\n */\nexport const CALLDATA_PATTERN = /^0x(?:[0-9a-fA-F]{2})*$/;\n\n/**\n * A decimal integer without leading zeros, as core writes a route step's native value in wei and every pay-in amount\n * in base units (kept as a string: it may exceed 2^53). Internal: not exported from the package index.\n */\nexport const DECIMAL_INTEGER_PATTERN = /^(?:0|[1-9][0-9]*)$/;\n","import {\n type CheckoutResolutionDto,\n type AssetDto,\n type AssetListDto,\n type ExternalBalanceReadDto,\n type ExternalBalancesDto,\n type ExternalHoldingDto,\n PAY_IN_STATES,\n type PayInDestinationDto,\n type PayInDto,\n type PayInLegDto,\n type PayInStateDto,\n type PayInStepDto,\n type PayInUnspendableDto,\n ROUTE_STATES,\n ROUTE_STEP_ROLES,\n type RouteDto,\n type RouteEndDto,\n type RouteFeesDto,\n type RouteListDto,\n type RouteQuoteDto,\n type RouteStateDto,\n type RouteStepCallDto,\n type RouteStepDto,\n} from \"#/models\";\nimport { evmChainHex } from \"#/payIn/caip\";\nimport { MAX_TOKEN_DECIMALS } from \"#/payIn/constants\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport { CALLDATA_PATTERN, DECIMAL_INTEGER_PATTERN } from \"#/shared/patterns\";\n\nimport { ROUTE_SOURCE_CHAIN_ID } from \"./constants\";\n\n/**\n * Reports whether `value` is shaped like a {@link RouteQuoteDto}: a JSON object whose `estimated_output`,\n * `minimum_output`, `expires_at` and `provider` are strings, whose `eta_seconds` is a safe integer, and whose `fees`\n * is an object with a string `platform` and `provider`. Its `trade_type` and `source_amount` are each a string,\n * `null` or absent.\n *\n * It checks shapes, not values: an amount is not checked to be digits, nor an instant to parse. Extra keys are\n * allowed, at every level, as on every Coordinator answer (`isErrorEnvelopeDto` allows them too), so a field the\n * Coordinator adds later never breaks the client.\n */\nexport function isRouteQuoteDto(value: unknown): value is RouteQuoteDto {\n return (\n isJsonObject(value) &&\n typeof value.estimated_output === \"string\" &&\n typeof value.minimum_output === \"string\" &&\n isOptionalString(value.trade_type) &&\n isOptionalString(value.source_amount) &&\n isRouteFeesDto(value.fees) &&\n Number.isSafeInteger(value.eta_seconds) &&\n typeof value.expires_at === \"string\" &&\n typeof value.provider === \"string\"\n );\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteDto}: {@link isRouteQuoteDto}, plus a non-empty string\n * `id`, a non-empty string `status`, a `steps` array whose every entry is a step the client can sign, an\n * `actual_output`, `destination_tx`, `source_tx`, `error`, `submitted_at` and `source_confirmed_at` that are each a\n * string, `null`, or absent, an `amount`, `created_at` and `updated_at` that are each a string or absent, and a\n * `source` and `destination` that are each a {@link RouteEndDto} (a string `asset` and `address`) or absent.\n *\n * The echoed fields are optional, so an answer from a Coordinator that predates them still reads; a present one of\n * the wrong shape fails the check. Whether an echo matches the request is the caller's to check.\n *\n * A step the client can sign has a `role` from `ROUTE_STEP_ROLES` and an `evm` call whose `chain_id` is\n * {@link ROUTE_SOURCE_CHAIN_ID}, whose `to` matches `EVM_ADDRESS_PATTERN`, whose `data` is `0x` and whole bytes of\n * hex, and whose `value` is a decimal integer. The steps are what the account signs, so their values are checked,\n * not only their shapes: an unknown role, another chain or a malformed call fails the check, and a step the client\n * cannot name never reaches a signature.\n *\n * A state outside `ROUTE_STATES` passes: core may add states, and a route whose funds are moving must still read.\n * Tell a known state with {@link isRouteStateDto}, and treat any other as in flight, never as failed or done. Extra\n * keys are allowed, as in {@link isRouteQuoteDto}, inside `evm` too; build a transaction from the four checked fields\n * only.\n */\nexport function isRouteDto(value: unknown): value is RouteDto {\n return isRouteWith(value, isRouteStepDto);\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteListDto}: a JSON object whose `data` is an array of routes and\n * whose `has_more` is a boolean. Each route is checked as in {@link isRouteDto}, except that a step's `chain_id` may\n * name any chain: the list also holds the routes that carried a pay-in's legs, whose steps run on the connected\n * wallet's chain, and a list is history, never something to sign. One malformed route fails the whole list; a route\n * in a state this client does not know does not. Extra keys are allowed, as in {@link isRouteQuoteDto}.\n *\n * Sign only the steps of a route read again through `getRoute`, whose answer {@link isRouteDto} holds to Tempo.\n */\nexport function isRouteListDto(value: unknown): value is RouteListDto {\n return (\n isJsonObject(value) &&\n Array.isArray(value.data) &&\n value.data.every((route) => isRouteWith(route, isListedRouteStepDto)) &&\n typeof value.has_more === \"boolean\"\n );\n}\n\n/**\n * Reports whether `value` is a route whose every step passes `isStep`, with the fields {@link isRouteDto} names.\n */\nfunction isRouteWith(value: unknown, isStep: (step: unknown) => boolean): value is RouteDto {\n return (\n isJsonObject(value) &&\n isRouteQuoteDto(value) &&\n isNonEmptyString(value.id) &&\n isNonEmptyString(value.status) &&\n Array.isArray(value.steps) &&\n value.steps.every(isStep) &&\n isOptionalString(value.actual_output) &&\n isOptionalString(value.destination_tx) &&\n isOptionalString(value.source_tx) &&\n isOptionalString(value.error) &&\n isOptionalString(value.refund_amount) &&\n isOptionalString(value.refund_tx) &&\n isOptionalString(value.submitted_at) &&\n isOptionalString(value.source_confirmed_at) &&\n isAbsentOrString(value.amount) &&\n isAbsentOrString(value.created_at) &&\n isAbsentOrString(value.updated_at) &&\n (value.source === undefined || isRouteEndDto(value.source)) &&\n (value.destination === undefined || isRouteEndDto(value.destination))\n );\n}\n\n/**\n * Reports whether `value` is one of the route states this client knows, `ROUTE_STATES`. A route's `status` that is\n * not one of them is a state core added later: the funds are in flight.\n */\nexport function isRouteStateDto(value: unknown): value is RouteStateDto {\n return isMember(ROUTE_STATES, value);\n}\n\n/**\n * Reports whether `value` is shaped like an {@link ExternalBalancesDto}: a JSON object whose `holdings` is an array of\n * holdings, whose `id` is a string, `null` or absent, whose `as_of` is `null`, absent or an object of\n * `{ block, at }` reads (a safe-integer `block` and a string `at`), and whose `missing` is `null`, absent or an array\n * of strings.\n *\n * A holding has a string `chain`, `asset` and `symbol`, a `decimals` that is an integer from 0 to 255, an `amount` that\n * is a decimal integer without leading zeros (kept as a string: it may exceed 2^53), a `usd` that is a string, `null`\n * or absent, and a `mechanisms` array of strings. A mechanism this client does not know passes; the quote is\n * authoritative. An optional field that is `null` reads as absent: refusing it would cost a read and protect nothing.\n * Extra keys are allowed, at every level, as on every Coordinator answer.\n */\nexport function isExternalBalancesDto(value: unknown): value is ExternalBalancesDto {\n return (\n isJsonObject(value) &&\n isOptionalString(value.id) &&\n isOptionalString(value.spendable_usd) &&\n (isAbsent(value.unpriced) || isStringArray(value.unpriced)) &&\n (isAbsent(value.unread) || isStringArray(value.unread)) &&\n (isAbsent(value.as_of) || (isJsonObject(value.as_of) && Object.values(value.as_of).every(isExternalBalanceReadDto))) &&\n (isAbsent(value.missing) || isStringArray(value.missing)) &&\n Array.isArray(value.holdings) &&\n value.holdings.every(isExternalHoldingDto)\n );\n}\n\n/**\n * Reports whether `value` is shaped like a {@link PayInDto}, the answer of every pay-in call: a JSON object with a\n * non-empty string `id` and `status`; a `phase`, `failure_reason`, `cancellation_reason`, `deadline` and `snapshot_id`\n * that are each a string, `null` or absent; a `destination` with a string `asset` and `address`; a string `amount`,\n * `delivered`, `shape` and `expires_at`; a `poll_after_ms` that is a non-negative safe integer, `null` or absent; and\n * arrays of `legs`, `steps`, `required_steps` and `unspendable`, each entry well-formed, where every id in\n * `required_steps` names an entry of `steps`.\n *\n * A leg has a safe-integer `n`, a non-empty string `status` and `mechanism`, a string `source_asset`, `input_amount`\n * and `min_output`, and a `source_tx`, `actual_output`, `refund_tx`, `refund_amount`, `fail_reason` and `drip` that\n * are each a string, `null` or absent. An unspendable holding has a string `asset`, `amount` and `reason`.\n *\n * It checks shapes, never values, and a step's base fields only: a non-empty string `id`, `scheme` and `status`,\n * a safe-integer `leg`, a string `chain` and `expires_at`, and a `digest`, `reason` and `tx_hash` that are each a\n * string, `null` or absent. A step's `payload` is not checked at all. `steps` is the pay-in's whole history and core\n * may add schemes, so a step this client could never sign must not make a pay-in that is moving money unreadable.\n * Check a step by value before a wallet sees it.\n *\n * Only the fields the guide marks required are required: an optional field that is `null` reads as absent, so a\n * pay-in that is moving money never turns unreadable over one (the guide's own loop polls at `poll_after_ms ?? 2000`).\n * A state, leg state, step status, scheme, mechanism, phase, shape or drip outside this client's lists passes: core\n * may add them. Tell a known pay-in state with {@link isPayInStateDto}, and treat any other as in flight, never as\n * failed or done. Extra keys are allowed, at every level, as on every Coordinator answer.\n */\nexport function isPayInDto(value: unknown): value is PayInDto {\n return (\n isJsonObject(value) &&\n isNonEmptyString(value.id) &&\n isNonEmptyString(value.status) &&\n isOptionalString(value.phase) &&\n isOptionalString(value.failure_reason) &&\n isOptionalString(value.cancellation_reason) &&\n isPayInDestinationDto(value.destination) &&\n (isAbsent(value.payee) || (isJsonObject(value.payee) && typeof value.payee.name === \"string\")) &&\n typeof value.amount === \"string\" &&\n typeof value.delivered === \"string\" &&\n typeof value.shape === \"string\" &&\n typeof value.expires_at === \"string\" &&\n isOptionalString(value.deadline) &&\n isOptionalString(value.fee_usd) &&\n Array.isArray(value.legs) &&\n value.legs.every(isPayInLegDto) &&\n Array.isArray(value.steps) &&\n value.steps.every(isPayInStepDto) &&\n isStringArray(value.required_steps) &&\n namesListedSteps(value.required_steps, value.steps) &&\n Array.isArray(value.unspendable) &&\n value.unspendable.every(isPayInUnspendableDto) &&\n isOptionalString(value.snapshot_id) &&\n (isAbsent(value.poll_after_ms) || isSafeIntegerFrom(value.poll_after_ms, 0, Number.MAX_SAFE_INTEGER))\n );\n}\n\n/**\n * Reports whether `value` is one of the pay-in states this client knows, `PAY_IN_STATES`. A pay-in's `status` that is\n * not one of them is a state core added later: the funds may be moving.\n */\nexport function isPayInStateDto(value: unknown): value is PayInStateDto {\n return isMember(PAY_IN_STATES, value);\n}\n\n/**\n * Reports whether `value` is an {@link ExternalBalanceReadDto}: an object with a safe-integer `block` and a string\n * `at`.\n */\nfunction isExternalBalanceReadDto(value: unknown): value is ExternalBalanceReadDto {\n return isJsonObject(value) && Number.isSafeInteger(value.block) && typeof value.at === \"string\";\n}\n\n/**\n * Reports whether `value` is an {@link ExternalHoldingDto}, per {@link isExternalBalancesDto}.\n */\nfunction isExternalHoldingDto(value: unknown): value is ExternalHoldingDto {\n return (\n isJsonObject(value) &&\n typeof value.chain === \"string\" &&\n typeof value.asset === \"string\" &&\n typeof value.symbol === \"string\" &&\n isSafeIntegerFrom(value.decimals, 0, MAX_TOKEN_DECIMALS) &&\n typeof value.amount === \"string\" &&\n DECIMAL_INTEGER_PATTERN.test(value.amount) &&\n isOptionalString(value.usd) &&\n (isAbsent(value.spendable) || typeof value.spendable === \"boolean\") &&\n (isAbsent(value.payable_mechanisms) || isStringArray(value.payable_mechanisms)) &&\n isOptionalString(value.reason) &&\n isStringArray(value.mechanisms)\n );\n}\n\n/**\n * Reports whether `value` is a {@link PayInDestinationDto}: an object with a string `asset` and `address`.\n */\nfunction isPayInDestinationDto(value: unknown): value is PayInDestinationDto {\n return isJsonObject(value) && typeof value.asset === \"string\" && typeof value.address === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link PayInLegDto}, per {@link isPayInDto}.\n */\nfunction isPayInLegDto(value: unknown): value is PayInLegDto {\n return (\n isJsonObject(value) &&\n Number.isSafeInteger(value.n) &&\n isNonEmptyString(value.status) &&\n isNonEmptyString(value.mechanism) &&\n typeof value.source_asset === \"string\" &&\n typeof value.input_amount === \"string\" &&\n typeof value.min_output === \"string\" &&\n isOptionalString(value.fee_usd) &&\n isOptionalString(value.source_tx) &&\n isOptionalString(value.destination_tx) &&\n isOptionalString(value.actual_output) &&\n isOptionalString(value.refund_tx) &&\n isOptionalString(value.refund_amount) &&\n isOptionalString(value.fail_reason) &&\n isOptionalString(value.drip)\n );\n}\n\n/**\n * Reports whether `value` has a pay-in step's base fields, per {@link isPayInDto}. Its `payload` is not checked.\n */\nfunction isPayInStepDto(value: unknown): value is PayInStepDto {\n return (\n isJsonObject(value) &&\n isNonEmptyString(value.id) &&\n Number.isSafeInteger(value.leg) &&\n isNonEmptyString(value.scheme) &&\n typeof value.chain === \"string\" &&\n isOptionalString(value.digest) &&\n typeof value.expires_at === \"string\" &&\n isNonEmptyString(value.status) &&\n isOptionalString(value.reason) &&\n isOptionalString(value.tx_hash)\n );\n}\n\n/**\n * Reports whether `value` is a {@link PayInUnspendableDto}: an object with a string `asset`, `amount` and `reason`.\n */\nfunction isPayInUnspendableDto(value: unknown): value is PayInUnspendableDto {\n return (\n isJsonObject(value) &&\n typeof value.asset === \"string\" &&\n typeof value.amount === \"string\" &&\n typeof value.reason === \"string\"\n );\n}\n\n/**\n * Reports whether every id in `requiredSteps` is the `id` of an entry of `steps`, so the step to do next can\n * always be found.\n */\nfunction namesListedSteps(requiredSteps: readonly string[], steps: readonly PayInStepDto[]): boolean {\n const listed = new Set(steps.map((step) => step.id));\n\n return requiredSteps.every((stepId) => listed.has(stepId));\n}\n\n/**\n * Reports whether `value` is a {@link RouteFeesDto}: an object with a string `platform` and `provider`.\n */\nfunction isRouteFeesDto(value: unknown): value is RouteFeesDto {\n return isJsonObject(value) && typeof value.platform === \"string\" && typeof value.provider === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link RouteEndDto}: an object with a string `asset` and `address`. Extra keys are\n * allowed, as in {@link isRouteQuoteDto}.\n */\nfunction isRouteEndDto(value: unknown): value is RouteEndDto {\n return isJsonObject(value) && typeof value.asset === \"string\" && typeof value.address === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link RouteStepDto} the client can sign: a known `role` and a\n * {@link RouteStepCallDto} `evm`.\n */\nfunction isRouteStepDto(value: unknown): value is RouteStepDto {\n return isListedRouteStepDto(value) && value.evm.chain_id === ROUTE_SOURCE_CHAIN_ID;\n}\n\n/**\n * Reports whether `value` is a step of a listed route: a known `role` and an `evm` call shaped as in\n * {@link isRouteStepCallDto}, on any chain.\n */\nfunction isListedRouteStepDto(value: unknown): value is RouteStepDto {\n return isJsonObject(value) && isMember(ROUTE_STEP_ROLES, value.role) && isRouteStepCallDto(value.evm);\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteStepCallDto}: an object whose `chain_id` is a CAIP-2 EVM chain\n * (`eip155:` and digits), whose `to` is an EVM address, whose `data` is `0x` and whole bytes of hex, and whose `value`\n * is a decimal integer. Whether the chain is Tempo is {@link isRouteStepDto}'s check.\n */\nfunction isRouteStepCallDto(value: unknown): value is RouteStepCallDto {\n return (\n isJsonObject(value) &&\n typeof value.chain_id === \"string\" &&\n evmChainHex(value.chain_id) !== null &&\n typeof value.to === \"string\" &&\n EVM_ADDRESS_PATTERN.test(value.to) &&\n typeof value.data === \"string\" &&\n CALLDATA_PATTERN.test(value.data) &&\n typeof value.value === \"string\" &&\n DECIMAL_INTEGER_PATTERN.test(value.value)\n );\n}\n\n/**\n * Reports whether `value` is a string other than `\"\"`.\n */\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * Reports whether `value` is `null` or `undefined` (an absent key).\n */\nfunction isAbsent(value: unknown): value is null | undefined {\n return value === undefined || value === null;\n}\n\n/**\n * Reports whether `value` is a string, `null`, or `undefined` (an absent key).\n */\nfunction isOptionalString(value: unknown): value is string | null | undefined {\n return isAbsent(value) || typeof value === \"string\";\n}\n\n/**\n * Reports whether `value` is a string or `undefined` (an absent key), never `null`.\n */\nfunction isAbsentOrString(value: unknown): value is string | undefined {\n return value === undefined || typeof value === \"string\";\n}\n\n/**\n * Reports whether `value` is a safe integer from `min` to `max`, both included.\n */\nfunction isSafeIntegerFrom(value: unknown, min: number, max: number): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= min && value <= max;\n}\n\n/**\n * Reports whether `value` is an array of strings.\n */\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reports whether `value` is one of `members`.\n */\nfunction isMember<TMember extends string>(members: readonly TMember[], value: unknown): value is TMember {\n return members.some((member) => member === value);\n}\n\n/**\n * The registry list envelope before its entries are checked.\n */\nexport interface AssetListEnvelope {\n object: \"list\";\n data: unknown[];\n has_more: boolean;\n}\n\n/**\n * Checks the registry envelope and every entry, allowing absent or null logos.\n */\nexport function isAssetListDto(value: unknown): value is AssetListDto {\n return isAssetListEnvelope(value) && value.data.every(isAssetDto);\n}\n\n/**\n * Reports whether `value` is a registry list envelope: `object` `list`, a boolean `has_more`, and an array `data`\n * whose entries are not checked yet.\n */\nexport function isAssetListEnvelope(value: unknown): value is AssetListEnvelope {\n return isJsonObject(value) && value.object === \"list\" && typeof value.has_more === \"boolean\" && Array.isArray(value.data);\n}\n\n/**\n * Keeps only the envelope's entries that {@link isAssetDto} accepts. Spec C12: one bad row is dropped, and the rest\n * stays. A row's network name or logo that is malformed is dropped alone ({@link withValidNetworkFacts}): display facts\n * never decide whether a coin is listed.\n */\nexport function keepValidAssets(envelope: AssetListEnvelope): AssetListDto {\n return { object: \"list\", data: envelope.data.filter(isAssetDto).map(withValidNetworkFacts), has_more: envelope.has_more };\n}\n\n/**\n * `asset` without a `network_name` that is not a nonblank string or a `network_logo_url` that is not a string or null.\n * Returns `asset` itself when both are absent or valid.\n */\nfunction withValidNetworkFacts(asset: AssetDto): AssetDto {\n const nameValid =\n asset.network_name === undefined || (typeof asset.network_name === \"string\" && asset.network_name.trim() !== \"\");\n const logoValid = asset.network_logo_url === undefined || isOptionalString(asset.network_logo_url);\n if (nameValid && logoValid) return asset;\n const { network_name, network_logo_url, ...rest } = asset;\n return {\n ...rest,\n ...(nameValid && network_name !== undefined ? { network_name } : {}),\n ...(logoValid && network_logo_url !== undefined ? { network_logo_url } : {}),\n };\n}\n\n/**\n * Reports whether `value` is one {@link AssetDto} registry entry, allowing an absent or null logo.\n */\nfunction isAssetDto(value: unknown): value is AssetDto {\n return (\n isJsonObject(value) &&\n value.object === \"asset\" &&\n typeof value.asset === \"string\" &&\n typeof value.network === \"string\" &&\n typeof value.symbol === \"string\" &&\n isSafeIntegerFrom(value.decimals, 0, MAX_TOKEN_DECIMALS) &&\n isOptionalString(value.logo_url)\n );\n}\n\n/** Accept only coherent EVM checkout resolutions, with a nonzero destination. */\nexport function isCheckoutResolutionDto(value: unknown): value is CheckoutResolutionDto {\n if (\n !isJsonObject(value) ||\n value.object !== \"checkout_resolution\" ||\n typeof value.asset !== \"string\" ||\n !/^eip155:[1-9][0-9]*\\/(?:erc20:0x[0-9a-fA-F]{40}|slip44:[0-9]+)$/.test(value.asset) ||\n typeof value.address !== \"string\" ||\n !EVM_ADDRESS_PATTERN.test(value.address) ||\n /^0x0{40}$/i.test(value.address) ||\n !isNonEmptyString(value.symbol) ||\n typeof value.default !== \"boolean\" ||\n typeof value.registered !== \"boolean\" ||\n !(value.decimals === undefined || Number.isSafeInteger(value.decimals)) ||\n !isOptionalString(value.usd_price)\n )\n return false;\n if (!value.registered) return value.rule_id === null && value.payee === null && !value.default;\n return (\n typeof value.rule_id === \"string\" &&\n /^ckr_.+/.test(value.rule_id) &&\n isJsonObject(value.payee) &&\n isNonEmptyString(value.payee.name)\n );\n}\n","import type { ServerTimeSink } from \"#/time/types\";\n\nimport { UPSTREAM_DATE_HEADER } from \"./constants\";\n\n/**\n * The time a date header names, in ms since the epoch, or `null` when the header is absent or does not parse.\n */\nfunction parseDateHeader(value: string | null): number | null {\n if (value === null || value.trim() === \"\") {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * The server's time a response carries: `X-Stridge-Upstream-Date` (the hub proxy's copy of the Coordinator's `Date`)\n * when it parses, else `Date`, else `null`.\n */\nexport function readServerTimeMs(headers: Headers): number | null {\n return parseDateHeader(headers.get(UPSTREAM_DATE_HEADER)) ?? parseDateHeader(headers.get(\"Date\"));\n}\n\n/**\n * Hands `sink` the server time `headers` carry, with the device's send and receipt times. Does nothing without a sink\n * or without a parseable date, and swallows what the sink throws, so a sink never fails a call.\n */\nexport function reportServerTime(\n sink: ServerTimeSink | undefined,\n headers: Headers,\n sentAtMs: number,\n receivedAtMs: number,\n): void {\n if (sink === undefined) {\n return;\n }\n const serverTimeMs = readServerTimeMs(headers);\n if (serverTimeMs === null) {\n return;\n }\n try {\n sink({ serverTimeMs, sentAtMs, receivedAtMs });\n } catch {\n return;\n }\n}\n","import { CsrfStoreError } from \"#/errors/CsrfStoreError\";\nimport { isErrorEnvelopeDto } from \"#/errors/guards\";\nimport { parseBody } from \"#/errors/json\";\nimport { toSuaError } from \"#/errors/parseSuaError\";\nimport { SuaNetworkError } from \"#/errors/SuaNetworkError\";\nimport type {\n CheckoutResolutionDto,\n CheckoutResolveRequestDto,\n AdjustPayInRequestDto,\n CheckoutQuoteRequestDto,\n ConfirmPayInRequestDto,\n ExternalBalancesDto,\n ExternalBalancesRequestDto,\n PayInChainCapabilitiesDto,\n PayInDto,\n TopUpQuoteRequestDto,\n PayInStepSignatureDto,\n PayInStepTxHashDto,\n PayInWalletDescriptorDto,\n PayInWalletsDto,\n AnswerWalletOfferRequestDto,\n ExternalAccountDto,\n GuestCookieScopeDto,\n GuestHandoffDto,\n GuestMergeRequestDto,\n GuestDto,\n MarkExternalAccountUsedRequestDto,\n OpenGuestRequestDto,\n RegisterKeypairRequestDto,\n RegisterKeypairResultDto,\n RelayRequestDto,\n RelayResponseDto,\n RoundDto,\n RouteDto,\n RouteListDto,\n RouteQuoteDto,\n RouteRequestDto,\n RouteSourceRequestDto,\n SaveExternalAccountRequestDto,\n SessionDto,\n StartRoundRequestDto,\n StartRoundResponseDto,\n VerifyRoundRequestDto,\n VerifyRoundResponseDto,\n WalletDto,\n} from \"#/models\";\nimport { ROUTE_STATES } from \"#/models/Route/entities/RouteStateDto\";\nimport { GUEST_COOKIE_ACCESS_HEADER } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport type { ServerTimeSink } from \"#/time/types\";\n\nimport { APP_HEADER, CSRF_HEADER, IDEMPOTENCY_HEADER, MAX_IDEMPOTENCY_KEY_LENGTH, MAX_ROUTE_LIST_LIMIT } from \"./constants\";\nimport { hubTarget, type HubMethod } from \"./endpoints\";\nimport {\n isCheckoutResolutionDto,\n type AssetListEnvelope,\n isAssetListEnvelope,\n isExternalBalancesDto,\n isPayInDto,\n isRouteDto,\n isRouteListDto,\n isRouteQuoteDto,\n isRouteStateDto,\n keepValidAssets,\n} from \"./guards\";\nimport { reportServerTime } from \"./serverTime\";\n\nimport type {\n CoordinatorCallOptions,\n CoordinatorClient,\n CoordinatorClientOptions,\n CsrfAccessor,\n FetchLike,\n GuestCallOptions,\n GuestReadCallOptions,\n ListRoutesQuery,\n} from \"./types\";\n\n/**\n * Every request body the client sends: one request Dto per route that takes a body.\n */\ntype RequestBodyDto =\n | CheckoutResolveRequestDto\n | StartRoundRequestDto\n | VerifyRoundRequestDto\n | RegisterKeypairRequestDto\n | RelayRequestDto\n | SaveExternalAccountRequestDto\n | MarkExternalAccountUsedRequestDto\n | RouteRequestDto\n | RouteSourceRequestDto\n | GuestMergeRequestDto\n | OpenGuestRequestDto\n | AnswerWalletOfferRequestDto\n | ExternalBalancesRequestDto\n | TopUpQuoteRequestDto\n | ConfirmPayInRequestDto\n | AdjustPayInRequestDto;\n\n/**\n * The credentials one route sends. Every route states them, so a guest call can never carry the session token and the\n * offer answer can never carry the guest token.\n */\ntype RouteCredentials =\n /**\n * The cookies, and the stored session token as `X-CSRF-Token` on every `POST`, `PUT` and `DELETE`\n * (`omitCredentials` sends neither).\n */\n | { kind: \"session\" }\n /**\n * The cookies, and exactly this session token as `X-CSRF-Token`. The stored token is never read.\n */\n | { kind: \"pinned-session\"; token: string }\n /**\n * The cookies only. The stored token is never read.\n */\n | { kind: \"guest-open\" }\n /** The cookies and guest cookie scope only; reads never carry a CSRF token. */\n | { kind: \"guest-read\"; cookieAccess: GuestCookieScopeDto }\n /**\n * The cookies, the guest's token as `X-CSRF-Token` and its scope as `X-Stridge-Cookie-Access`. The stored session\n * token is never read.\n */\n | { kind: \"guest\"; token: string; cookieAccess: GuestCookieScopeDto };\n\n/**\n * The credentials of every session route.\n */\nconst SESSION: RouteCredentials = { kind: \"session\" };\n\n/**\n * The header names only the transport writes, from a route's {@link RouteCredentials}. A route header naming one is a\n * programming error.\n */\nconst CREDENTIAL_HEADERS: ReadonlySet<string> = new Set([CSRF_HEADER.toLowerCase(), GUEST_COOKIE_ACCESS_HEADER.toLowerCase()]);\n\n/**\n * A transaction hash as `POST /wallet/v1/routes/{id}/source` takes it: `0x` and 32 bytes of hex, either case.\n */\nconst TX_HASH_PATTERN = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * An idempotency key the client sends: visible ASCII only (`!` through `~`), so its length in characters is its\n * length in bytes, which is what the Coordinator bounds, and no header rule trims or refuses it.\n */\nconst IDEMPOTENCY_KEY_PATTERN = /^[\\x21-\\x7E]+$/;\n\n/**\n * One call to a hub API route, as the methods describe it to {@link Transport.send}.\n */\ninterface RouteCall {\n /**\n * The HTTP verb.\n */\n method: HubMethod;\n\n /**\n * The path after `baseUrl` (`/wallet/v1/…` or `/pay/v1/…`, from `hubTarget`), ids already encoded, with its query\n * string when the route takes one.\n */\n path: string;\n\n /**\n * The JSON body, built key by key by the method. Omitted for a call without a body.\n */\n body?: RequestBodyDto;\n\n /**\n * Whether the route requires `X-Stridge-App`.\n */\n sendsApp?: boolean;\n\n /**\n * Headers the route takes beyond the shared ones (`Idempotency-Key` on `openRoute`), already checked by the\n * method. Never one the transport sets itself.\n */\n headers?: Readonly<Record<string, string>>;\n\n /**\n * The credentials the route sends, written after every other header.\n */\n credentials: RouteCredentials;\n\n /**\n * The shape check a `2xx` answer must pass, beyond being a JSON object. A body that fails it is an unusable\n * answer. Omitted on the routes whose fields are not validated.\n */\n isAnswer?: (value: unknown) => boolean;\n\n /**\n * Whether the caller ignores the route's answer (sign-out, mark a linked wallet used, the deletes, the warms). On such a route any `2xx`\n * that is not the error envelope resolves `undefined`; on every other route a `204` is an unusable answer.\n */\n noContent?: boolean;\n\n /**\n * The caller's per-call options: its abort signal, and whether to send the request without credentials (session\n * routes only).\n */\n callOptions?: CoordinatorCallOptions;\n}\n\n/**\n * The validated options every method closes over.\n */\ninterface Transport {\n /**\n * Sends one call and reads its answer per the rules on {@link CoordinatorClient}.\n */\n send(call: RouteCall): Promise<unknown>;\n}\n\n/**\n * Creates the Coordinator client: one method per hub API route the hub uses, with the shared request and answer rules\n * documented on {@link CoordinatorClient}.\n *\n * Validates the options once, up front:\n *\n * - `baseUrl` must parse with `new URL(baseUrl)` as an absolute `http:` or `https:` URL with no query and no fragment.\n * Trailing slashes are removed; any path prefix is kept.\n * - `appId` must be a non-empty string. Its format is not checked (the Coordinator answers `403 APP_SUSPENDED` for a\n * bad one).\n * - `csrf` must have `get` and `set` functions.\n * - `fetch` defaults to `globalThis.fetch`, read now. It is always called as a plain function, never as a method\n * of the options object.\n * - `onServerTime`, when given, must be a function. It too is called as a plain function.\n *\n * Creating the client sends nothing.\n *\n * @throws {TypeError} when an option breaks one of those rules, or no `fetch` is available.\n */\nexport function createCoordinatorClient(options: CoordinatorClientOptions): CoordinatorClient {\n if (!isJsonObject(options)) {\n throw new TypeError(\"createCoordinatorClient: options must be an object\");\n }\n\n const baseUrl = normaliseBaseUrl(options.baseUrl);\n const appId = options.appId;\n if (typeof appId !== \"string\" || appId === \"\") {\n throw new TypeError(\"createCoordinatorClient: appId must be a non-empty string\");\n }\n\n const csrf = options.csrf;\n if (!isJsonObject(csrf) || typeof csrf.get !== \"function\" || typeof csrf.set !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: csrf must have get and set functions\");\n }\n\n const fetchFn: FetchLike | undefined = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: no fetch is available; pass options.fetch\");\n }\n\n const onServerTime = options.onServerTime;\n if (onServerTime !== undefined && typeof onServerTime !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: onServerTime must be a function\");\n }\n\n const transport = createTransport(baseUrl, appId, csrf, fetchFn, onServerTime);\n\n return {\n baseUrl,\n appId,\n\n async startRound(input, callOptions) {\n const body: StartRoundRequestDto = {};\n if (input.email !== undefined) {\n body.method = \"email\";\n body.email = input.email;\n }\n\n return (await transport.send({\n ...hubTarget(\"startRound\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as StartRoundResponseDto;\n },\n\n async getRound(roundId, callOptions) {\n return (await transport.send({\n ...hubTarget(\"getRound\", encodeURIComponent(roundId)),\n credentials: SESSION,\n\n callOptions,\n })) as RoundDto;\n },\n\n async verifyRound(roundId, request, callOptions) {\n const body: VerifyRoundRequestDto = { encrypted_otp_bundle: request.encrypted_otp_bundle };\n const answer = (await transport.send({\n ...hubTarget(\"verifyRound\", encodeURIComponent(roundId)),\n body,\n credentials: SESSION,\n\n callOptions,\n })) as VerifyRoundResponseDto;\n\n const token = answer.csrf_token;\n if (typeof token === \"string\" && token !== \"\") {\n try {\n await csrf.set(token);\n } catch (cause) {\n throw new CsrfStoreError(answer, cause);\n }\n }\n\n return answer;\n },\n\n async registerKeypair(request, callOptions) {\n const body: RegisterKeypairRequestDto = {\n round_id: request.round_id,\n stamped_body: request.stamped_body,\n attested_stamp: request.attested_stamp,\n };\n\n return (await transport.send({\n ...hubTarget(\"registerKeypair\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as RegisterKeypairResultDto;\n },\n\n async getSession(callOptions) {\n return (await transport.send({\n ...hubTarget(\"getSession\"),\n credentials: SESSION,\n\n callOptions,\n })) as SessionDto;\n },\n\n async getWallet(callOptions) {\n return (await transport.send({\n ...hubTarget(\"getWallet\"),\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as WalletDto;\n },\n\n async relay(request, callOptions) {\n const pinned = callOptions !== undefined && \"sessionCsrfToken\" in callOptions;\n const token: unknown = pinned ? callOptions.sessionCsrfToken : undefined;\n if (pinned && (typeof token !== \"string\" || token === \"\")) {\n throw new TypeError(\"relay: sessionCsrfToken must be a non-empty string\");\n }\n const body: RelayRequestDto = {\n body: request.body,\n stamp_header: {\n name: request.stamp_header.name,\n value: request.stamp_header.value,\n },\n purpose: request.purpose,\n };\n\n return (await transport.send({\n ...hubTarget(\"relay\"),\n body,\n sendsApp: true,\n credentials: typeof token === \"string\" ? { kind: \"pinned-session\", token } : SESSION,\n callOptions: pinned ? toSignalOnly(callOptions) : callOptions,\n })) as RelayResponseDto;\n },\n\n async signOut(callOptions) {\n await transport.send({\n ...hubTarget(\"signOut\"),\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async saveExternalAccount(request, callOptions) {\n const pinned = callOptions !== undefined && \"sessionCsrfToken\" in callOptions;\n const token: unknown = pinned ? callOptions.sessionCsrfToken : undefined;\n if (pinned && (typeof token !== \"string\" || token === \"\")) {\n throw new TypeError(\"saveExternalAccount: sessionCsrfToken must be a non-empty string\");\n }\n return (await transport.send({\n ...hubTarget(\"saveExternalAccount\"),\n body: buildSaveExternalAccountBody(request),\n sendsApp: true,\n credentials: typeof token === \"string\" ? { kind: \"pinned-session\", token } : SESSION,\n callOptions: pinned ? toSignalOnly(callOptions) : callOptions,\n })) as ExternalAccountDto;\n },\n\n async markExternalAccountUsed(walletId, request, callOptions) {\n const lastChainId = request?.last_chain_id;\n await transport.send({\n ...hubTarget(\"markExternalAccountUsed\", encodeURIComponent(walletId)),\n ...(lastChainId === undefined ? {} : { body: { last_chain_id: lastChainId } }),\n sendsApp: true,\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async removeExternalAccount(walletId, callOptions) {\n await transport.send({\n ...hubTarget(\"removeExternalAccount\", encodeURIComponent(walletId)),\n sendsApp: true,\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async quoteRoute(request, callOptions) {\n return (await transport.send({\n ...hubTarget(\"quoteRoute\"),\n body: buildRouteRequestBody(request),\n sendsApp: true,\n isAnswer: isRouteQuoteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteQuoteDto;\n },\n\n async openRoute(request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"openRoute\", callOptions?.idempotencyKey);\n\n return (await transport.send({\n ...hubTarget(\"openRoute\"),\n body: buildRouteOpenBody(request),\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async getRoute(routeId, callOptions) {\n return (await transport.send({\n ...hubTarget(\"getRoute\", encodePathId(\"getRoute\", \"routeId\", routeId)),\n sendsApp: true,\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async listAssets(callOptions) {\n return keepValidAssets(\n (await transport.send({\n ...hubTarget(\"listAssets\"),\n sendsApp: true,\n isAnswer: isAssetListEnvelope,\n credentials: SESSION,\n callOptions,\n })) as AssetListEnvelope,\n );\n },\n\n async listGuestAssets(callOptions) {\n return keepValidAssets(\n (await transport.send({\n ...hubTarget(\"listGuestAssets\"),\n sendsApp: true,\n isAnswer: isAssetListEnvelope,\n credentials: checkGuestReadCredentials(\"listGuestAssets\", callOptions),\n callOptions,\n })) as AssetListEnvelope,\n );\n },\n\n async listRoutes(query, callOptions) {\n return (await transport.send({\n ...hubTarget(\"listRoutes\", undefined, buildRouteListQuery(query)),\n sendsApp: true,\n isAnswer: isRouteListDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteListDto;\n },\n\n async reportRouteSource(routeId, request, callOptions) {\n const tx = request.tx;\n if (typeof tx !== \"string\" || !TX_HASH_PATTERN.test(tx)) {\n throw new TypeError(\"reportRouteSource: tx must be 0x followed by 64 hex digits\");\n }\n const body: RouteSourceRequestDto = { tx };\n\n return (await transport.send({\n ...hubTarget(\"reportRouteSource\", encodePathId(\"reportRouteSource\", \"routeId\", routeId)),\n body,\n sendsApp: true,\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async openGuest(request, callOptions) {\n const body: OpenGuestRequestDto = { cookie_access: request.cookie_access };\n\n return (await transport.send({\n ...hubTarget(\"openGuest\"),\n body,\n sendsApp: true,\n credentials: { kind: \"guest-open\" },\n callOptions: toSignalOnly(callOptions),\n })) as GuestDto;\n },\n\n async createGuestHandoff(options) {\n return (await transport.send({\n ...hubTarget(\"createGuestHandoff\"),\n credentials: checkGuestCredentials(\"createGuestHandoff\", options),\n sendsApp: true,\n callOptions: toSignalOnly(options),\n })) as GuestHandoffDto;\n },\n\n async mergeGuestSession(request, options) {\n await transport.send({\n ...hubTarget(\"mergeGuestSession\"),\n body: { handoff: request.handoff },\n credentials: checkGuestCredentials(\"mergeGuestSession\", options),\n noContent: true,\n sendsApp: true,\n callOptions: toSignalOnly(options),\n });\n },\n\n async saveGuestWallet(request, callOptions) {\n const credentials = checkGuestCredentials(\"saveGuestWallet\", callOptions);\n\n return (await transport.send({\n ...hubTarget(\"saveGuestWallet\"),\n body: buildSaveExternalAccountBody(request),\n sendsApp: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalAccountDto;\n },\n\n async removeGuestWallet(walletId, callOptions) {\n const credentials = checkGuestCredentials(\"removeGuestWallet\", callOptions);\n await transport.send({\n ...hubTarget(\"removeGuestWallet\", encodeURIComponent(walletId)),\n sendsApp: true,\n noContent: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n });\n },\n\n async markGuestWalletUsed(walletId, request, callOptions) {\n const credentials = checkGuestCredentials(\"markGuestWalletUsed\", callOptions);\n const lastChainId = request?.last_chain_id;\n return (await transport.send({\n ...hubTarget(\"markGuestWalletUsed\", encodeURIComponent(walletId)),\n ...(lastChainId === undefined ? {} : { body: { last_chain_id: lastChainId } }),\n sendsApp: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalAccountDto;\n },\n\n async answerWalletOffer(request, callOptions) {\n const token: unknown = callOptions?.sessionCsrfToken;\n if (typeof token !== \"string\" || token === \"\") {\n throw new TypeError(\"answerWalletOffer: sessionCsrfToken must be a non-empty string\");\n }\n const accept = readWalletIds(\"accept_guest_accounts\", request?.accept_guest_accounts ?? null) ?? [];\n const discard = readWalletIds(\"discard_guest_accounts\", request?.discard_guest_accounts);\n const shown = readWalletIds(\"shown\", request?.shown);\n const body: AnswerWalletOfferRequestDto = { accept_guest_accounts: accept };\n if (discard !== undefined) body.discard_guest_accounts = discard;\n if (shown !== undefined) body.shown = shown;\n\n return (await transport.send({\n ...hubTarget(\"answerWalletOffer\"),\n body,\n sendsApp: true,\n credentials: { kind: \"pinned-session\", token },\n callOptions: toSignalOnly(callOptions),\n })) as SessionDto;\n },\n\n async resolveGuestCheckout(request, callOptions) {\n const body: CheckoutResolveRequestDto = {};\n if (request.asset !== undefined) body.asset = request.asset;\n if (request.destination !== undefined) body.destination = request.destination;\n return (await transport.send({\n ...hubTarget(\"resolveGuestCheckout\"),\n body,\n sendsApp: true,\n credentials: checkGuestCredentials(\"resolveGuestCheckout\", callOptions),\n isAnswer: isCheckoutResolutionDto,\n callOptions: toSignalOnly(callOptions),\n })) as CheckoutResolutionDto;\n },\n\n async resolveCheckout(request, callOptions) {\n const body: CheckoutResolveRequestDto = {};\n if (request.asset !== undefined) body.asset = request.asset;\n if (request.destination !== undefined) body.destination = request.destination;\n return (await transport.send({\n ...hubTarget(\"resolveCheckout\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n isAnswer: isCheckoutResolutionDto,\n callOptions: callOptions,\n })) as CheckoutResolutionDto;\n },\n\n async warmGuestExternalBalances(request, callOptions) {\n await transport.send({\n credentials: checkGuestCredentials(\"warmGuestExternalBalances\", callOptions),\n ...hubTarget(\"warmGuestExternalBalances\"),\n body: buildExternalBalancesBody(request),\n sendsApp: true,\n noContent: true,\n callOptions: toSignalOnly(callOptions),\n });\n },\n\n async warmExternalBalances(request, callOptions) {\n await transport.send({\n credentials: SESSION,\n ...hubTarget(\"warmExternalBalances\"),\n body: buildExternalBalancesBody(request),\n sendsApp: true,\n noContent: true,\n callOptions,\n });\n },\n\n async getGuestExternalBalances(request, callOptions) {\n return (await transport.send({\n credentials: checkGuestReadCredentials(\"getGuestExternalBalances\", callOptions),\n ...hubTarget(\"getGuestExternalBalances\", undefined, buildExternalBalancesQuery(request)),\n sendsApp: true,\n isAnswer: isExternalBalancesDto,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalBalancesDto;\n },\n\n async getExternalBalances(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"getExternalBalances\", undefined, buildExternalBalancesQuery(request)),\n sendsApp: true,\n isAnswer: isExternalBalancesDto,\n callOptions,\n })) as ExternalBalancesDto;\n },\n\n async quoteGuestPayIn(request, callOptions) {\n return (await transport.send({\n credentials: checkGuestCredentials(\"quoteGuestPayIn\", callOptions),\n ...hubTarget(\"quoteGuestPayIn\"),\n body: buildCheckoutQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async quoteCheckout(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"quoteCheckout\"),\n body: buildCheckoutQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async quoteTopUp(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"quoteTopUp\"),\n body: buildTopUpQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async confirmGuestPayIn(payInId, request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"confirmGuestPayIn\", callOptions?.idempotencyKey);\n const body: ConfirmPayInRequestDto = {\n signatures: buildSignatureBatch(\"confirmGuestPayIn\", request, { allowTxHash: false, allowEmpty: true }),\n };\n\n return (await transport.send({\n credentials: checkGuestCredentials(\"confirmGuestPayIn\", callOptions),\n ...hubTarget(\"confirmGuestPayIn\", encodePathId(\"confirmGuestPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async confirmPayIn(payInId, request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"confirmPayIn\", callOptions?.idempotencyKey);\n const body: ConfirmPayInRequestDto = {\n signatures: buildSignatureBatch(\"confirmPayIn\", request, { allowTxHash: false, allowEmpty: true }),\n };\n\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"confirmPayIn\", encodePathId(\"confirmPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async adjustGuestPayIn(payInId, request, callOptions) {\n const body: AdjustPayInRequestDto = {\n signatures: buildSignatureBatch(\"adjustGuestPayIn\", request, { allowTxHash: true, allowEmpty: false }),\n };\n\n return (await transport.send({\n credentials: checkGuestCredentials(\"adjustGuestPayIn\", callOptions),\n ...hubTarget(\"adjustGuestPayIn\", encodePathId(\"adjustGuestPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async adjustPayIn(payInId, request, callOptions) {\n const body: AdjustPayInRequestDto = {\n signatures: buildSignatureBatch(\"adjustPayIn\", request, { allowTxHash: true, allowEmpty: false }),\n };\n\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"adjustPayIn\", encodePathId(\"adjustPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async cancelGuestPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: checkGuestCredentials(\"cancelGuestPayIn\", callOptions),\n ...hubTarget(\"cancelGuestPayIn\", encodePathId(\"cancelGuestPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async cancelPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"cancelPayIn\", encodePathId(\"cancelPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async getGuestPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: checkGuestReadCredentials(\"getGuestPayIn\", callOptions),\n ...hubTarget(\"getGuestPayIn\", encodePathId(\"getGuestPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async getPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"getPayIn\", encodePathId(\"getPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n };\n}\n\n/**\n * Keeps only the caller's abort signal from per-call options: the guest and pinned routes take no other option.\n */\nfunction toSignalOnly(options: { signal?: AbortSignal } | undefined): CoordinatorCallOptions | undefined {\n return options?.signal === undefined ? undefined : { signal: options.signal };\n}\n\n/**\n * Checks a guest write's credentials and returns them.\n *\n * @throws {TypeError} when `guestCsrfToken` is not a non-empty string or `cookieAccess` is not a guest cookie scope.\n */\nfunction checkGuestCredentials(method: string, options: GuestCallOptions | undefined): RouteCredentials {\n const token: unknown = options?.guestCsrfToken;\n if (typeof token !== \"string\" || token === \"\") {\n throw new TypeError(`${method}: guestCsrfToken must be a non-empty string`);\n }\n const cookieAccess: unknown = options?.cookieAccess;\n if (cookieAccess !== \"unpartitioned\" && cookieAccess !== \"partitioned\") {\n throw new TypeError(`${method}: cookieAccess must be \"unpartitioned\" or \"partitioned\"`);\n }\n return { kind: \"guest\", token, cookieAccess };\n}\n\n/** Validates the cookie scope of a guest read without requiring or reading any token. */\nfunction checkGuestReadCredentials(method: string, options: GuestReadCallOptions | undefined): RouteCredentials {\n const cookieAccess: unknown = options?.cookieAccess;\n if (cookieAccess !== \"unpartitioned\" && cookieAccess !== \"partitioned\") {\n throw new TypeError(`${method}: cookieAccess must be \"unpartitioned\" or \"partitioned\"`);\n }\n return { kind: \"guest-read\", cookieAccess };\n}\n\n/**\n * Builds the body of `saveExternalAccount` and `saveGuestWallet` key by key: `chain_kind`, `address`, `wallet_brand`,\n * `connector`, `saved_via`, and the optional fields `display_name`, `last_chain_id` and `reconnect` when defined.\n */\nfunction buildSaveExternalAccountBody(request: SaveExternalAccountRequestDto): SaveExternalAccountRequestDto {\n return {\n chain_kind: request.chain_kind,\n address: request.address,\n wallet_brand: request.wallet_brand,\n connector: request.connector,\n ...(request.display_name === undefined ? {} : { display_name: request.display_name }),\n ...(request.last_chain_id === undefined ? {} : { last_chain_id: request.last_chain_id }),\n saved_via: request.saved_via,\n ...(request.reconnect === undefined ? {} : { reconnect: request.reconnect }),\n };\n}\n\n/**\n * A copy of one wallet-id list of the offer answer, or `undefined` when the caller left it out. Anything else that is\n * not an array of strings (`null` included) throws before sending.\n */\nfunction readWalletIds(field: string, value: unknown): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw new TypeError(`answerWalletOffer: ${field} must be an array of wallet ids`);\n }\n return [...value];\n}\n\n/**\n * Builds the body of `quoteRoute` key by key: `source.asset`, `source.amount`, `destination.asset`, then\n * `destination.address` only when it is defined. A quote never carries `purpose` or `payment_ref`.\n */\nfunction buildRouteRequestBody(request: RouteRequestDto): RouteRequestDto {\n const destination = request.destination;\n\n return {\n source: { asset: request.source.asset, amount: request.source.amount },\n destination:\n destination.address === undefined\n ? { asset: destination.asset }\n : { asset: destination.asset, address: destination.address },\n };\n}\n\n/**\n * Builds the body of `openRoute`: the quote body ({@link buildRouteRequestBody}), then `purpose` and `payment_ref`, each\n * only when it is defined. The key order is fixed: the Coordinator compares the body's bytes under one idempotency key.\n */\nfunction buildRouteOpenBody(request: RouteRequestDto): RouteRequestDto {\n return {\n ...buildRouteRequestBody(request),\n ...(request.purpose === undefined ? {} : { purpose: request.purpose }),\n ...(request.payment_ref === undefined ? {} : { payment_ref: request.payment_ref }),\n };\n}\n\n/**\n * Builds the body of `warmExternalBalances` and `warmGuestExternalBalances`: exactly `wallets`.\n */\nfunction buildExternalBalancesBody(request: ExternalBalancesRequestDto): ExternalBalancesRequestDto {\n return { wallets: buildPayInWallets(request.wallets) };\n}\n\n/**\n * Builds the query of `getExternalBalances` and `getGuestExternalBalances` from the request's `wallets`: `evm` and\n * `svm`, then JSON `wallet` and its optional checkout target. Each value is URI-encoded.\n */\nfunction buildExternalBalancesQuery(request: ExternalBalancesRequestDto): string {\n const wallets = buildPayInWallets(request.wallets);\n const parts: string[] = [];\n if (wallets.evm !== undefined) {\n parts.push(`evm=${encodeURIComponent(wallets.evm)}`);\n }\n if (wallets.svm !== undefined) {\n parts.push(`svm=${encodeURIComponent(wallets.svm)}`);\n }\n\n if (request.wallet !== undefined) {\n parts.push(`wallet=${encodeURIComponent(JSON.stringify(buildWalletDescriptor(request.wallet)))}`);\n if (request.asset !== undefined && request.destination !== undefined) {\n parts.push(`asset=${encodeURIComponent(request.asset)}`, `destination=${encodeURIComponent(request.destination)}`);\n }\n }\n\n return parts.length === 0 ? \"\" : `?${parts.join(\"&\")}`;\n}\n\n/**\n * Builds a pay-in call's `wallets` key by key: `evm` and `svm`, only when defined.\n */\nfunction buildPayInWallets(wallets: PayInWalletsDto): PayInWalletsDto {\n const body: PayInWalletsDto = {};\n if (wallets.evm !== undefined) {\n body.evm = wallets.evm;\n }\n\n if (wallets.svm !== undefined) {\n body.svm = wallets.svm;\n }\n\n return body;\n}\n\n/**\n * Builds `quoteTopUp`'s body key by key: `wallets`, then `wallet` only when it is defined, then `asset` and `amount`,\n * then `sources` and `source_chains` when defined. Never a `destination`.\n */\nfunction buildTopUpQuoteBody(request: TopUpQuoteRequestDto): TopUpQuoteRequestDto {\n return {\n wallets: buildPayInWallets(request.wallets),\n ...(request.wallet === undefined ? {} : { wallet: buildWalletDescriptor(request.wallet) }),\n asset: request.asset,\n amount: request.amount,\n ...(request.sources === undefined ? {} : { sources: [...request.sources] }),\n ...(request.source_chains === undefined ? {} : { source_chains: [...request.source_chains] }),\n };\n}\n\n/** Builds a checkout with an explicit destination and the wallet's complete capabilities answer. */\nfunction buildCheckoutQuoteBody(request: CheckoutQuoteRequestDto): CheckoutQuoteRequestDto {\n const wallet = request.wallet;\n return {\n wallets: buildPayInWallets(request.wallets),\n ...(wallet === undefined\n ? {}\n : {\n wallet: {\n kind: wallet.kind,\n ...(wallet.name === undefined ? {} : { name: wallet.name }),\n ...(wallet.capabilities === undefined ? {} : { capabilities: wallet.capabilities }),\n },\n }),\n asset: request.asset,\n amount: request.amount,\n ...(request.sources === undefined ? {} : { sources: [...request.sources] }),\n ...(request.source_chains === undefined ? {} : { source_chains: [...request.source_chains] }),\n destination: request.destination,\n };\n}\n\n/**\n * Builds a quote's `wallet` key by key: `kind`, then `name` and `capabilities` only when they are defined.\n */\nfunction buildWalletDescriptor(wallet: PayInWalletDescriptorDto): PayInWalletDescriptorDto {\n return {\n kind: wallet.kind,\n ...(wallet.name === undefined ? {} : { name: wallet.name }),\n ...(wallet.capabilities === undefined ? {} : { capabilities: buildCapabilities(wallet.capabilities) }),\n };\n}\n\n/**\n * Copies a `wallet_getCapabilities` answer chain by chain, in its own order, with {@link buildChainCapabilities}. The\n * answer comes from the wallet unchecked, so a `capabilities` that is not an object is sent as it is, for the\n * Coordinator to refuse as `400 WALLET_MALFORMED`; the quote then goes out again without `wallet`.\n */\nfunction buildCapabilities(\n capabilities: Record<string, PayInChainCapabilitiesDto | null>,\n): Record<string, PayInChainCapabilitiesDto | null> {\n const value: unknown = capabilities;\n if (!isJsonObject(value)) {\n return capabilities;\n }\n\n return Object.fromEntries(Object.entries(capabilities).map(([chainId, chain]) => [chainId, buildChainCapabilities(chain)]));\n}\n\n/**\n * Copies one chain's capabilities, keeping only the three the Coordinator reads, each only when it is defined:\n * `alternateGasFees` and `paymasterService` as `{ supported }`, and `atomic` as `{ status }`. A wallet reports many\n * more, which never reach the wire. A `null` chain stays `null`; a chain or a capability that is not an object is sent\n * as it is, for the Coordinator to refuse as `400 WALLET_MALFORMED`.\n */\nfunction buildChainCapabilities(chain: PayInChainCapabilitiesDto | null): PayInChainCapabilitiesDto | null {\n const value: unknown = chain;\n if (chain === null || !isJsonObject(value)) {\n return chain;\n }\n\n const copy: PayInChainCapabilitiesDto = {};\n if (chain.alternateGasFees !== undefined) {\n copy.alternateGasFees = buildSupportCapability(chain.alternateGasFees);\n }\n if (chain.paymasterService !== undefined) {\n copy.paymasterService = buildSupportCapability(chain.paymasterService);\n }\n if (chain.atomic !== undefined) {\n const atomic: unknown = chain.atomic;\n copy.atomic = isJsonObject(atomic) ? { status: chain.atomic.status } : chain.atomic;\n }\n\n return copy;\n}\n\n/**\n * Copies a `{ supported }` capability: exactly `supported`, or the value as it is when it is not an object.\n */\nfunction buildSupportCapability(capability: { supported: boolean }): { supported: boolean } {\n const value: unknown = capability;\n\n return isJsonObject(value) ? { supported: capability.supported } : capability;\n}\n\n/**\n * What a signature batch may hold: `confirmPayIn` takes signatures only and may be empty, `adjustPayIn` takes\n * signatures and sent transactions' hashes and may not.\n */\ninterface SignatureBatchRules {\n /**\n * Whether an item may carry a `tx_hash`.\n */\n allowTxHash: boolean;\n\n /**\n * Whether the batch may hold no item.\n */\n allowEmpty: boolean;\n}\n\n/**\n * Builds a confirm or adjust batch, item by item and key by key: `step_id` then `signature`, or `step_id` then\n * `tx_hash`. Nothing about a step's own signature is checked here beyond being a non-empty string; the Coordinator\n * checks the rest (`422 SIGNATURE_BATCH_INVALID`).\n *\n * @throws {TypeError} when `request.signatures` is not an array, or is empty where `rules` say it may not be, or an\n * item is not an object, has an empty `step_id`, carries both or neither of `signature` and `tx_hash`, carries an\n * empty `signature`, a `tx_hash` that is not `0x` followed by 64 hex digits, or a `tx_hash` where `rules` refuse\n * one.\n */\nfunction buildSignatureBatch(\n method: \"confirmPayIn\" | \"confirmGuestPayIn\",\n request: ConfirmPayInRequestDto,\n rules: SignatureBatchRules & { allowTxHash: false },\n): PayInStepSignatureDto[];\nfunction buildSignatureBatch(\n method: \"adjustPayIn\" | \"adjustGuestPayIn\",\n request: AdjustPayInRequestDto,\n rules: SignatureBatchRules & { allowTxHash: true },\n): (PayInStepSignatureDto | PayInStepTxHashDto)[];\nfunction buildSignatureBatch(\n method: string,\n request: unknown,\n rules: SignatureBatchRules,\n): (PayInStepSignatureDto | PayInStepTxHashDto)[] {\n const items: unknown = isJsonObject(request) ? request.signatures : undefined;\n if (!Array.isArray(items)) {\n throw new TypeError(`${method}: signatures must be an array`);\n }\n if (items.length === 0 && !rules.allowEmpty) {\n throw new TypeError(`${method}: signatures must hold at least one item`);\n }\n\n return Array.from(items, (item: unknown, index) =>\n buildSignatureItem(`${method}: signatures[${index}]`, item, rules.allowTxHash),\n );\n}\n\n/**\n * Builds one batch item key by key, per {@link buildSignatureBatch}. `label` names the item in a refusal.\n *\n * @throws {TypeError} when the item breaks a rule {@link buildSignatureBatch} lists.\n */\nfunction buildSignatureItem(label: string, item: unknown, allowTxHash: boolean): PayInStepSignatureDto | PayInStepTxHashDto {\n if (!isJsonObject(item)) {\n throw new TypeError(`${label} must be an object`);\n }\n\n const stepId = item.step_id;\n if (typeof stepId !== \"string\" || stepId === \"\") {\n throw new TypeError(`${label}.step_id must be a non-empty string`);\n }\n\n const signature = item.signature;\n const txHash = item.tx_hash;\n if ((signature === undefined) === (txHash === undefined)) {\n throw new TypeError(`${label} must carry exactly one of signature and tx_hash`);\n }\n\n if (txHash === undefined) {\n if (typeof signature !== \"string\" || signature === \"\") {\n throw new TypeError(`${label}.signature must be a non-empty string`);\n }\n\n return { step_id: stepId, signature };\n }\n\n if (!allowTxHash) {\n throw new TypeError(`${label} carries a tx_hash, which is never sent on confirm`);\n }\n if (typeof txHash !== \"string\" || !TX_HASH_PATTERN.test(txHash)) {\n throw new TypeError(`${label}.tx_hash must be 0x followed by 64 hex digits`);\n }\n\n return { step_id: stepId, tx_hash: txHash };\n}\n\n/**\n * Checks a route open or pay-in confirm's idempotency key: 1 to {@link MAX_IDEMPOTENCY_KEY_LENGTH} visible ASCII characters.\n *\n * @throws {TypeError} when it is anything else.\n */\nfunction checkIdempotencyKey(method: string, key: unknown): string {\n if (typeof key !== \"string\" || key.length > MAX_IDEMPOTENCY_KEY_LENGTH || !IDEMPOTENCY_KEY_PATTERN.test(key)) {\n throw new TypeError(`${method}: idempotencyKey must be 1 to ${MAX_IDEMPOTENCY_KEY_LENGTH} visible ASCII characters`);\n }\n\n return key;\n}\n\n/**\n * Checks a route id and encodes it for the path. `.` and `..` are refused: `encodeURIComponent` leaves them as they\n * are, and the URL parser would resolve them as dot segments, sending the call to another hub API path.\n *\n * @throws {TypeError} when it is not a non-empty string, or is `.` or `..`.\n */\nfunction encodePathId(method: string, field: string, routeId: unknown): string {\n if (typeof routeId !== \"string\" || routeId === \"\" || routeId === \".\" || routeId === \"..\") {\n throw new TypeError(`${method}: ${field} must be a non-empty string other than \".\" and \"..\"`);\n }\n\n return encodeURIComponent(routeId);\n}\n\n/**\n * Builds `listRoutes`' query string: `?status=a,b&limit=N`, each part only when it is sent, or `\"\"` when neither is.\n * The states need no encoding: every `ROUTE_STATES` member is lowercase letters and `_`.\n *\n * @throws {TypeError} when `query` is not an object, `states` is not an array of `ROUTE_STATES` members, or `limit`\n * is not an integer from 1 to {@link MAX_ROUTE_LIST_LIMIT}.\n */\nfunction buildRouteListQuery(query: ListRoutesQuery | undefined): string {\n if (query === undefined) {\n return \"\";\n }\n if (!isJsonObject(query)) {\n throw new TypeError(\"listRoutes: query must be an object\");\n }\n\n const parts: string[] = [];\n const states: unknown = query.states;\n if (states !== undefined) {\n if (!Array.isArray(states) || !states.every(isRouteStateDto)) {\n throw new TypeError(`listRoutes: states must hold only ${ROUTE_STATES.join(\", \")}`);\n }\n if (states.length > 0) {\n parts.push(`status=${states.join(\",\")}`);\n }\n }\n\n const limit: unknown = query.limit;\n if (limit !== undefined) {\n if (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1 || limit > MAX_ROUTE_LIST_LIMIT) {\n throw new TypeError(`listRoutes: limit must be an integer from 1 to ${MAX_ROUTE_LIST_LIMIT}`);\n }\n parts.push(`limit=${limit}`);\n }\n\n return parts.length === 0 ? \"\" : `?${parts.join(\"&\")}`;\n}\n\n/**\n * Validates `baseUrl` and removes its trailing slashes.\n *\n * @throws {TypeError} when it is not an absolute `http:` or `https:` URL without a query or fragment.\n */\nfunction normaliseBaseUrl(baseUrl: unknown): string {\n if (typeof baseUrl !== \"string\" || baseUrl === \"\") {\n throw new TypeError(\"createCoordinatorClient: baseUrl is required\");\n }\n\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n throw new TypeError(`createCoordinatorClient: baseUrl must be an absolute URL, got \"${baseUrl}\"`);\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new TypeError(`createCoordinatorClient: baseUrl must use http: or https:, got \"${url.protocol}\"`);\n }\n\n if (url.search !== \"\" || url.hash !== \"\" || baseUrl.includes(\"?\") || baseUrl.includes(\"#\")) {\n throw new TypeError(\"createCoordinatorClient: baseUrl must not carry a query or a fragment\");\n }\n\n return url.href.replace(/\\/+$/, \"\");\n}\n\n/**\n * Builds the request sender every method shares. Every response reports its server time to `onServerTime` before\n * its answer is read.\n *\n * The route's {@link RouteCredentials} are written after every other header. A session call with `omitCredentials`\n * goes out with `credentials: \"omit\"` and without `X-CSRF-Token`, and the token is not read: the token only proves the\n * session the cookie names, so it means nothing on a request that carries no cookie. Only a session call ever reads\n * the stored token.\n *\n * @throws {TypeError} when a route header names `X-CSRF-Token` or `X-Stridge-Cookie-Access`, which only the\n * credentials write.\n */\nfunction createTransport(\n baseUrl: string,\n appId: string,\n csrf: CsrfAccessor,\n fetchFn: FetchLike,\n onServerTime: ServerTimeSink | undefined,\n): Transport {\n return {\n async send(call) {\n const signal = call.callOptions?.signal;\n const credentials = call.credentials;\n const omitCredentials = credentials.kind === \"session\" && call.callOptions?.omitCredentials === true;\n const headers: Record<string, string> = {};\n if (call.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n if (call.sendsApp === true) {\n headers[APP_HEADER] = appId;\n }\n if (call.headers !== undefined) {\n for (const name of Object.keys(call.headers)) {\n if (CREDENTIAL_HEADERS.has(name.toLowerCase())) {\n throw new TypeError(`a route header may not name ${name}`);\n }\n }\n Object.assign(headers, call.headers);\n }\n if (credentials.kind === \"session\" && call.method !== \"GET\" && !omitCredentials) {\n const token = await csrf.get();\n if (typeof token === \"string\" && token !== \"\") {\n headers[CSRF_HEADER] = token;\n }\n }\n if (credentials.kind === \"pinned-session\") {\n headers[CSRF_HEADER] = credentials.token;\n }\n if (credentials.kind === \"guest\") {\n headers[CSRF_HEADER] = credentials.token;\n }\n if (credentials.kind === \"guest\" || credentials.kind === \"guest-read\") {\n headers[GUEST_COOKIE_ACCESS_HEADER] = credentials.cookieAccess;\n }\n\n const init: RequestInit = {\n method: call.method,\n headers,\n credentials: omitCredentials ? \"omit\" : \"include\",\n };\n if (call.body !== undefined) {\n init.body = JSON.stringify(call.body);\n }\n if (signal !== undefined) {\n init.signal = signal;\n }\n\n let response: Response;\n const sentAtMs = Date.now();\n try {\n response = await fetchFn(`${baseUrl}${call.path}`, init);\n } catch (cause) {\n if (signal?.aborted === true) {\n throw cause;\n }\n throw new SuaNetworkError(cause);\n }\n reportServerTime(onServerTime, response.headers, sentAtMs, Date.now());\n\n return readAnswer(response, signal, call.noContent === true, call.isAnswer);\n },\n };\n}\n\n/**\n * Reads an answer: an error envelope on any status and any non-`2xx` throw a `SuaError`. On a `noContent` route any\n * other `2xx` resolves `undefined`. On every other route a `2xx` whose body is not a JSON object (a `204` included),\n * or fails the route's `isAnswer` check, throws a `SuaError` with code `internal`, and any other `2xx` resolves its\n * parsed body.\n *\n * A body that fails to read rethrows the abort when the caller aborted. Otherwise it throws `SuaNetworkError` on a\n * `2xx` (no usable answer arrived) and counts as an empty body on a failure status.\n */\nasync function readAnswer(\n response: Response,\n signal: AbortSignal | undefined,\n noContent: boolean,\n isAnswer: ((value: unknown) => boolean) | undefined,\n): Promise<unknown> {\n if (response.status === 204) {\n if (noContent) {\n return undefined;\n }\n\n throw toSuaError({ status: 204, retryAfter: response.headers.get(\"Retry-After\"), body: \"\" });\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch (cause) {\n if (signal?.aborted === true) {\n throw cause;\n }\n if (response.ok) {\n throw new SuaNetworkError(cause);\n }\n text = \"\";\n }\n\n const parsed = parseBody(text);\n const isEnvelope = parsed.kind === \"json\" && isErrorEnvelopeDto(parsed.value);\n const isSuccessBody =\n parsed.kind === \"json\" && isJsonObject(parsed.value) && (isAnswer === undefined || isAnswer(parsed.value));\n\n if (noContent && response.ok && !isEnvelope) {\n return undefined;\n }\n\n if (isEnvelope || !response.ok || !isSuccessBody) {\n throw toSuaError({\n status: response.status,\n retryAfter: response.headers.get(\"Retry-After\"),\n body: text,\n });\n }\n\n return parsed.value;\n}\n","const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;\nconst BASE64_URL_PATTERN = /^[A-Za-z0-9_-]*$/;\nconst CHUNK_SIZE = 0x8000;\n\n/**\n * Builds a binary string (one character per byte, every code unit 0–255) from bytes, in chunks so a large input\n * never overflows the argument limit of `String.fromCharCode`. A binary string is the only input `btoa` handles\n * correctly.\n */\nfunction toBinaryString(bytes: Uint8Array): string {\n let out = \"\";\n for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) {\n out += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK_SIZE));\n }\n return out;\n}\n\n/**\n * Turns the binary string `atob` returns back into bytes.\n */\nfunction fromBinaryString(binary: string): Uint8Array {\n const out = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n out[index] = binary.charCodeAt(index);\n }\n return out;\n}\n\n/**\n * Encodes bytes as standard base64 (RFC 4648 §4: `+`, `/`, padded with `=`). This is the encoding of the\n * Coordinator's `[]byte` JSON fields (`body`, `stamp_header.value`, `provider_response`) and of\n * `session_public_key`.\n *\n * Works on bytes, never on text: to base64 a string, encode it with {@link utf8ToBytes} first. Calling `btoa` on\n * a string with any character above U+00FF throws, and on a Latin-1 string it silently encodes the wrong bytes.\n */\nexport function toBase64(bytes: Uint8Array): string {\n return btoa(toBinaryString(bytes));\n}\n\n/**\n * Decodes standard base64 (RFC 4648 §4). Padding may be present or omitted; whitespace and the URL-safe\n * alphabet (`-`, `_`) are refused.\n *\n * @throws {TypeError} when `value` is not standard base64.\n */\nexport function fromBase64(value: string): Uint8Array {\n if (typeof value !== \"string\" || !BASE64_PATTERN.test(value) || value.length % 4 === 1) {\n throw new TypeError(\"fromBase64: expected standard base64\");\n }\n try {\n return fromBinaryString(atob(value));\n } catch {\n throw new TypeError(\"fromBase64: expected standard base64\");\n }\n}\n\n/**\n * Encodes bytes as base64url without padding (RFC 4648 §5: `-`, `_`, no `=`). This is the encoding of the\n * Turnkey stamp string before it is wrapped in standard base64 for `stamp_header.value` (guide §7.2).\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n return toBase64(bytes).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Decodes base64url (RFC 4648 §5) without padding. Padding, whitespace and the standard alphabet (`+`, `/`) are\n * refused.\n *\n * @throws {TypeError} when `value` is not unpadded base64url.\n */\nexport function fromBase64Url(value: string): Uint8Array {\n if (typeof value !== \"string\" || !BASE64_URL_PATTERN.test(value) || value.length % 4 === 1) {\n throw new TypeError(\"fromBase64Url: expected unpadded base64url\");\n }\n return fromBase64(value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n}\n","const HEX_PATTERN = /^(?:[0-9a-fA-F]{2})*$/;\n\n/**\n * Encodes bytes as lowercase hex, two characters per byte, with no `0x` prefix.\n *\n * @example toHex(new Uint8Array([0x02, 0x4e])) === \"024e\"\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) {\n out += byte.toString(16).padStart(2, \"0\");\n }\n return out;\n}\n\n/**\n * Decodes hex into bytes. Accepts either case; refuses a `0x` prefix, an odd length and any non-hex character.\n *\n * @throws {TypeError} when `hex` is not an even-length string of hex digits.\n */\nexport function fromHex(hex: string): Uint8Array {\n if (typeof hex !== \"string\" || !HEX_PATTERN.test(hex)) {\n throw new TypeError(\"fromHex: expected an even-length hex string without a 0x prefix\");\n }\n const out = new Uint8Array(hex.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n","const SEQUENCE_TAG = 0x30;\nconst INTEGER_TAG = 0x02;\nconst COORDINATE_LENGTH = 32;\nconst RAW_LENGTH = COORDINATE_LENGTH * 2;\nconst MAX_INTEGER_LENGTH = COORDINATE_LENGTH + 1;\nconst LONG_FORM_BIT = 0x80;\n\n/**\n * Encodes one 32-byte big-endian coordinate as a minimal, positive DER INTEGER: leading zeros stripped (at least one\n * byte kept), then one `0x00` prepended when the high bit of the first remaining byte is set.\n */\nfunction encodeInteger(value: Uint8Array): Uint8Array {\n let start = 0;\n while (start < value.length - 1 && value[start] === 0) {\n start += 1;\n }\n const digits = value.subarray(start);\n const pad = digits[0] >= 0x80 ? 1 : 0;\n const out = new Uint8Array(2 + pad + digits.length);\n out[0] = INTEGER_TAG;\n out[1] = pad + digits.length;\n out.set(digits, 2 + pad);\n return out;\n}\n\n/**\n * Converts a raw P-256 ECDSA signature (r‖s, 32 bytes each) to DER (X.690):\n * `0x30 <len> 0x02 <rlen> <r> 0x02 <slen> <s>`, where each integer is minimal and positive: leading `0x00` bytes are\n * stripped (keeping at least one byte), then one `0x00` is prepended when the first remaining byte is `≥ 0x80`.\n * Lengths are always short-form (the whole signature is at most 72 bytes).\n *\n * Example (§12.7): r `a364…d7f6` has its high bit set and becomes `022100a364…d7f6`; s `4199…556e` does not and\n * becomes `02204199…556e`, giving `3045022100a364f4…42556e`.\n *\n * @throws {TypeError} when `raw` is not exactly 64 bytes.\n */\nexport function rawSignatureToDer(raw: Uint8Array): Uint8Array {\n if (!(raw instanceof Uint8Array) || raw.length !== RAW_LENGTH) {\n throw new TypeError(\"rawSignatureToDer: expected a 64-byte r‖s signature\");\n }\n const r = encodeInteger(raw.subarray(0, COORDINATE_LENGTH));\n const s = encodeInteger(raw.subarray(COORDINATE_LENGTH));\n const out = new Uint8Array(2 + r.length + s.length);\n out[0] = SEQUENCE_TAG;\n out[1] = r.length + s.length;\n out.set(r, 2);\n out.set(s, 2 + r.length);\n return out;\n}\n\n/**\n * One DER INTEGER once read: its value without the sign-padding byte, and the offset just past it.\n */\ninterface DerInteger {\n value: Uint8Array;\n next: number;\n}\n\n/**\n * Reads one strict DER INTEGER at `offset`: tag `0x02`, a short-form length of 1–33 that ends at or before `end`, a\n * positive and minimal encoding, and a value of at most 32 bytes once the sign-padding byte is dropped.\n *\n * @throws {TypeError} when the INTEGER breaks any of those rules.\n */\nfunction readInteger(der: Uint8Array, offset: number, end: number): DerInteger {\n if (offset + 2 > end || der[offset] !== INTEGER_TAG) {\n throw new TypeError(\"derSignatureToRaw: expected an INTEGER\");\n }\n const length = der[offset + 1];\n if ((length & LONG_FORM_BIT) !== 0) {\n throw new TypeError(\"derSignatureToRaw: long-form lengths are not allowed\");\n }\n if (length < 1 || length > MAX_INTEGER_LENGTH) {\n throw new TypeError(\"derSignatureToRaw: INTEGER length out of range\");\n }\n const start = offset + 2;\n const next = start + length;\n if (next > end) {\n throw new TypeError(\"derSignatureToRaw: INTEGER runs past the end of the SEQUENCE\");\n }\n const first = der[start];\n if (first >= 0x80) {\n throw new TypeError(\"derSignatureToRaw: negative INTEGER\");\n }\n const padded = first === 0 && length > 1;\n if (padded && der[start + 1] < 0x80) {\n throw new TypeError(\"derSignatureToRaw: non-minimal INTEGER\");\n }\n const value = der.subarray(padded ? start + 1 : start, next);\n if (value.length > COORDINATE_LENGTH) {\n throw new TypeError(\"derSignatureToRaw: INTEGER is longer than 32 bytes\");\n }\n return { value, next };\n}\n\n/**\n * Converts a DER ECDSA signature to raw r‖s (64 bytes): each INTEGER is stripped of leading `0x00` bytes and\n * left-padded with zeros to 32 bytes. The exact inverse of {@link rawSignatureToDer} on its output.\n *\n * Strict: a `0x30` SEQUENCE with a short-form length equal to the rest of the input, holding exactly two `0x02`\n * INTEGERs with short-form lengths of 1–33 bytes, each positive (first byte `< 0x80`) and minimal (a leading `0x00`\n * only when the next byte is `≥ 0x80`), with a value of at most 32 bytes once stripped, and no trailing bytes.\n *\n * @throws {TypeError} when `der` breaks any of those rules.\n */\nexport function derSignatureToRaw(der: Uint8Array): Uint8Array {\n if (!(der instanceof Uint8Array) || der.length < 2 || der[0] !== SEQUENCE_TAG) {\n throw new TypeError(\"derSignatureToRaw: expected a DER SEQUENCE\");\n }\n const length = der[1];\n if ((length & LONG_FORM_BIT) !== 0) {\n throw new TypeError(\"derSignatureToRaw: long-form lengths are not allowed\");\n }\n if (length !== der.length - 2) {\n throw new TypeError(\"derSignatureToRaw: SEQUENCE length does not match the input\");\n }\n const r = readInteger(der, 2, der.length);\n const s = readInteger(der, r.next, der.length);\n if (s.next !== der.length) {\n throw new TypeError(\"derSignatureToRaw: trailing bytes after the two INTEGERs\");\n }\n const out = new Uint8Array(RAW_LENGTH);\n out.set(r.value, COORDINATE_LENGTH - r.value.length);\n out.set(s.value, RAW_LENGTH - s.value.length);\n return out;\n}\n","/**\n * Returns WebCrypto's `SubtleCrypto`, read from `globalThis` at call time so importing a module never touches it (a\n * server bundle may import the SDK on a runtime without WebCrypto).\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport function getSubtle(): SubtleCrypto {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;\n if (!subtle) {\n throw new Error(\"WebCrypto is unavailable\");\n }\n return subtle;\n}\n","/**\n * A WebCrypto key pair. Structurally the DOM's `CryptoKeyPair`, declared here because the SDK compiles without the\n * DOM library; a `CryptoKeyPair` from `crypto.subtle.generateKey` is assignable to it.\n */\nexport interface CryptoKeyPairLike {\n /**\n * The public key. WebCrypto always allows exporting a public key, whatever `extractable` said.\n */\n readonly publicKey: CryptoKey;\n\n /**\n * The private key: ECDSA P-256, `extractable: false`, usages `[\"sign\"]`. It never leaves WebCrypto.\n */\n readonly privateKey: CryptoKey;\n}\n\n/**\n * The keypair: the browser-held P-256 key that signs (the glossary's \"keypair\"; the backend's \"session credential\").\n * Registered once per sign-in or renewal and valid for about 60 minutes.\n *\n * Every field survives a structured clone, so the whole object can be stored in IndexedDB as is.\n */\nexport interface Keypair {\n /**\n * The WebCrypto pair.\n */\n keys: CryptoKeyPairLike;\n\n /**\n * The 33-byte compressed SEC1 public key: `0x02` or `0x03` (the parity of Y), then the 32-byte X coordinate.\n */\n publicKey: Uint8Array;\n\n /**\n * `publicKey` as 66 lowercase hex characters. The form the stamps, the login activity and the code sealer use.\n */\n publicKeyHex: string;\n\n /**\n * `publicKey` as standard base64 (44 characters). Kept for stored keypairs; no request sends it.\n */\n publicKeyBase64: string;\n}\n\n/**\n * The WebCrypto parameters of the keypair: ECDSA on P-256.\n */\nexport const KEYPAIR_ALGORITHM = { name: \"ECDSA\", namedCurve: \"P-256\" } as const;\n\n/**\n * The WebCrypto parameters of every signature: ECDSA with SHA-256. WebCrypto hashes the message itself and returns\n * raw r‖s (IEEE P1363, 64 bytes).\n */\nexport const SIGNATURE_ALGORITHM = { name: \"ECDSA\", hash: \"SHA-256\" } as const;\n\n/**\n * The registration's activity type: the keypair's own login.\n */\nexport const STAMP_LOGIN_ACTIVITY_TYPE = \"ACTIVITY_TYPE_STAMP_LOGIN\";\n\n/**\n * The login window the registration asks for, as the decimal string the activity carries: one hour, the Coordinator's\n * `OWNER_SESSION_LIFETIME`. There is no server-side logout, so this is how long a registered keypair can sign.\n */\nexport const STAMP_LOGIN_EXPIRATION_SECONDS = \"3600\";\n\n/**\n * The stamp's `scheme`.\n */\nexport const STAMP_SCHEME = \"SIGNATURE_SCHEME_TK_API_P256\";\n\n/**\n * The stamp header's name.\n */\nexport const STAMP_HEADER_NAME = \"X-Stamp\";\n","import { toHex, utf8ToBytes } from \"#/encoding\";\n\nimport { rawSignatureToDer } from \"./der\";\nimport { getSubtle } from \"./subtle\";\nimport { SIGNATURE_ALGORITHM } from \"./types\";\n\n/**\n * Signs the UTF-8 bytes of `message` with ECDSA P-256 / SHA-256 and returns WebCrypto's raw r‖s bytes.\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nasync function signBytes(privateKey: CryptoKey, message: string): Promise<Uint8Array> {\n const subtle = getSubtle();\n return new Uint8Array(await subtle.sign(SIGNATURE_ALGORITHM, privateKey, utf8ToBytes(message)));\n}\n\n/**\n * Signs `message` with ECDSA P-256 and SHA-256 (`SIGNATURE_ALGORITHM`) over the UTF-8 bytes of `message`\n * (`utf8ToBytes`), returned as **raw r‖s**: the 64 bytes WebCrypto produces, as 128 lowercase hex characters. No DER,\n * no low-S normalisation. No Coordinator request takes this form; stamps use {@link signDer}.\n *\n * ECDSA is randomised, so two calls give different signatures; test by verifying, not by comparing.\n *\n * @param privateKey The keypair's private key.\n * @param message The message, verbatim.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function signRaw(privateKey: CryptoKey, message: string): Promise<string> {\n return toHex(await signBytes(privateKey, message));\n}\n\n/**\n * Signs `message` for the **stamp** (guide §7.2): the same ECDSA P-256 / SHA-256 signature over the UTF-8 bytes of\n * `message` as {@link signRaw}, converted with `rawSignatureToDer` and returned as lowercase DER hex (140–144\n * characters; 138 or fewer is possible but rare).\n *\n * @param privateKey The keypair's private key.\n * @param message The exact activity body string that the relay will forward.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function signDer(privateKey: CryptoKey, message: string): Promise<string> {\n return toHex(rawSignatureToDer(await signBytes(privateKey, message)));\n}\n","import { toBase64Url, utf8ToBytes } from \"#/encoding\";\nimport type { AttestationDto, CredentialDto, RegisterKeypairRequestDto } from \"#/models\";\n\nimport { signDer } from \"./sign\";\nimport { type Keypair, STAMP_LOGIN_ACTIVITY_TYPE, STAMP_LOGIN_EXPIRATION_SECONDS } from \"./types\";\n\nconst COMPRESSED_PUBLIC_KEY_HEX = /^0[23][0-9a-f]{64}$/;\n\n/**\n * Builds the keypair's login activity, once, as the exact string the stamp signs and the hub relays:\n *\n * `{\"type\":\"ACTIVITY_TYPE_STAMP_LOGIN\",\"timestampMs\":\"<nowMs>\",\"organizationId\":\"<organizationId>\",\"parameters\":{\"publicKey\":\"<publicKeyHex>\",\"expirationSeconds\":\"3600\",\"invalidateExisting\":false}}`\n *\n * The hub refuses any other key, casing or order of fields, a window above its own, and `invalidateExisting: true`\n * (which would sign the person out on every other device). Never re-serialise the result.\n *\n * @param organizationId The wallet's `provider_account_ref`.\n * @param publicKeyHex The keypair's compressed public key: 66 lowercase hex characters starting `02` or `03`.\n * @param nowMs The activity's timestamp, in milliseconds since the epoch.\n * @throws {TypeError} when `organizationId` is empty or `publicKeyHex` is not a lowercase compressed key.\n */\nexport function buildStampLogin(organizationId: string, publicKeyHex: string, nowMs: number = Date.now()): string {\n if (typeof organizationId !== \"string\" || organizationId === \"\") {\n throw new TypeError(\"buildStampLogin: expected a non-empty organization id\");\n }\n if (typeof publicKeyHex !== \"string\" || !COMPRESSED_PUBLIC_KEY_HEX.test(publicKeyHex)) {\n throw new TypeError(\"buildStampLogin: expected a 66-character lowercase compressed public key hex\");\n }\n return JSON.stringify({\n type: STAMP_LOGIN_ACTIVITY_TYPE,\n timestampMs: String(Math.trunc(nowMs)),\n organizationId,\n parameters: {\n publicKey: publicKeyHex,\n expirationSeconds: STAMP_LOGIN_EXPIRATION_SECONDS,\n invalidateExisting: false,\n },\n });\n}\n\n/**\n * Builds the `X-Stamp-Attested` value over `body`: the keypair's DER signature over the UTF-8 bytes of `body`\n * (`signDer`), in the JSON `{\"publicKeyAttestation\",\"scheme\",\"publicKey\",\"signature\"}` with the attestation verbatim,\n * then its UTF-8 bytes as **unpadded base64url**. Never log the result: it carries the attestation token.\n *\n * @param body The exact string to sign, from {@link buildStampLogin}.\n * @param keypair The keypair that sealed the code the attestation was issued for.\n * @param attestation The credential's `attestation`.\n */\nexport async function stampAttested(body: string, keypair: Keypair, attestation: AttestationDto): Promise<string> {\n const signature = await signDer(keypair.keys.privateKey, body);\n const stamp = JSON.stringify({\n publicKeyAttestation: attestation.token,\n scheme: attestation.scheme,\n publicKey: keypair.publicKeyHex,\n signature,\n });\n return toBase64Url(utf8ToBytes(stamp));\n}\n\n/**\n * Builds the registration body for a credential: the keypair's login for `organizationId` ({@link buildStampLogin})\n * and its attested stamp ({@link stampAttested}), as exactly `{ round_id: credential.round_id, stamped_body,\n * attested_stamp }`.\n *\n * @param organizationId The wallet's `provider_account_ref`.\n * @throws {TypeError} on the inputs {@link buildStampLogin} refuses.\n */\nexport async function createRegisterKeypairRequest(\n credential: CredentialDto,\n keypair: Keypair,\n organizationId: string,\n nowMs: number = Date.now(),\n): Promise<RegisterKeypairRequestDto> {\n const stampedBody = buildStampLogin(organizationId, keypair.publicKeyHex, nowMs);\n return {\n round_id: credential.round_id,\n stamped_body: stampedBody,\n attested_stamp: await stampAttested(stampedBody, keypair, credential.attestation),\n };\n}\n","import { toBase64, toHex } from \"#/encoding\";\n\nimport { getSubtle } from \"./subtle\";\nimport { type CryptoKeyPairLike, KEYPAIR_ALGORITHM, type Keypair } from \"./types\";\n\nconst UNCOMPRESSED_LENGTH = 65;\nconst COMPRESSED_LENGTH = 33;\nconst UNCOMPRESSED_PREFIX = 0x04;\n\n/**\n * Reports whether a key's algorithm is ECDSA on P-256.\n */\nfunction isEcdsaP256(key: CryptoKey): boolean {\n const algorithm = key.algorithm as { name?: unknown; namedCurve?: unknown } | undefined;\n return algorithm?.name === KEYPAIR_ALGORITHM.name && algorithm.namedCurve === KEYPAIR_ALGORITHM.namedCurve;\n}\n\n/**\n * Checks that `keys` is an ECDSA P-256 pair whose private half can sign.\n *\n * @throws {TypeError} when it is not.\n */\nfunction assertSigningPair(keys: CryptoKeyPairLike): void {\n const { publicKey, privateKey } = keys ?? {};\n if (!publicKey || publicKey.type !== \"public\" || !isEcdsaP256(publicKey)) {\n throw new TypeError(\"keypairFromKeys: the public key must be an ECDSA P-256 public key\");\n }\n if (\n !privateKey ||\n privateKey.type !== \"private\" ||\n !isEcdsaP256(privateKey) ||\n !Array.from(privateKey.usages ?? []).includes(\"sign\")\n ) {\n throw new TypeError(\"keypairFromKeys: the private key must be an ECDSA P-256 private key that can sign\");\n }\n}\n\n/**\n * Generates a new keypair (guide §3.3): `crypto.subtle.generateKey(KEYPAIR_ALGORITHM, false, [\"sign\"])`, so the\n * private key is ECDSA P-256, non-extractable and can only sign. Then derives the compressed public key forms through\n * {@link keypairFromKeys}.\n *\n * Reads `globalThis.crypto.subtle` at call time, never at module load.\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function generateKeypair(): Promise<Keypair> {\n const keys = (await getSubtle().generateKey(KEYPAIR_ALGORITHM, false, [\"sign\"])) as CryptoKeyPairLike;\n return keypairFromKeys(keys);\n}\n\n/**\n * Builds a {@link Keypair} around an existing WebCrypto pair, for example one read back from storage: exports\n * `keys.publicKey` as `\"raw\"` (the 65-byte uncompressed point), compresses it with {@link compressPublicKey}, and fills\n * `publicKeyHex` (`toHex`, lowercase) and `publicKeyBase64` (`toBase64`, standard, padded). `keys` is kept by\n * reference.\n *\n * @throws {TypeError} when `keys.publicKey.algorithm` is not ECDSA on P-256, or `keys.privateKey` is not an ECDSA\n * private key whose usages include `\"sign\"`.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function keypairFromKeys(keys: CryptoKeyPairLike): Promise<Keypair> {\n const subtle = getSubtle();\n assertSigningPair(keys);\n const raw = new Uint8Array(await subtle.exportKey(\"raw\", keys.publicKey));\n const publicKey = compressPublicKey(raw);\n return {\n keys,\n publicKey,\n publicKeyHex: toHex(publicKey),\n publicKeyBase64: toBase64(publicKey),\n };\n}\n\n/**\n * Compresses an uncompressed SEC1 P-256 point (`0x04 ‖ X ‖ Y`, 65 bytes) into 33 bytes: prefix `0x02 + (Y[31] & 1)`,\n * then X (guide §3.3: `publicKey[0] = 2 + (raw[64] & 1)`). Returns a new array; the input is not modified.\n *\n * Only the encoding is checked, not that the point is on the curve (WebCrypto produced it).\n *\n * @throws {TypeError} when `uncompressed` is not 65 bytes starting with `0x04`.\n */\nexport function compressPublicKey(uncompressed: Uint8Array): Uint8Array {\n if (\n !(uncompressed instanceof Uint8Array) ||\n uncompressed.length !== UNCOMPRESSED_LENGTH ||\n uncompressed[0] !== UNCOMPRESSED_PREFIX\n ) {\n throw new TypeError(\"compressPublicKey: expected a 65-byte uncompressed point starting with 0x04\");\n }\n const out = new Uint8Array(COMPRESSED_LENGTH);\n out[0] = 0x02 + (uncompressed[UNCOMPRESSED_LENGTH - 1] & 1);\n out.set(uncompressed.subarray(1, COMPRESSED_LENGTH), 1);\n return out;\n}\n","import { toBase64, toBase64Url, utf8ToBytes } from \"#/encoding\";\nimport type { StampHeaderDto } from \"#/models\";\n\nimport { STAMP_HEADER_NAME, STAMP_SCHEME } from \"./types\";\n\nconst COMPRESSED_PUBLIC_KEY_HEX = /^0[23][0-9a-fA-F]{64}$/;\nconst NON_EMPTY_HEX = /^(?:[0-9a-fA-F]{2})+$/;\n\n/**\n * Builds the Turnkey API-key stamp string (guide §7.2; `router/internal/turnkey/stamp.go`): the compact JSON\n * `{\"publicKey\":\"<publicKeyHex>\",\"scheme\":\"SIGNATURE_SCHEME_TK_API_P256\",\"signature\":\"<signatureDerHex>\"}`, keys in\n * exactly that order and no whitespace (build it with `JSON.stringify` of an object literal in that order), then its\n * UTF-8 bytes as **unpadded base64url** (`toBase64Url`).\n *\n * Both hex inputs are lowercased before they are embedded.\n *\n * Vector (§12.7): public key `024e7fb37bf4a0c496da3d6ce2bd68f82b1a1c877a8f258a4bceb121bec94ba272` and the §12.7 DER\n * signature give the string whose standard base64 is the §12.7 `stamp_header.value`.\n *\n * @param publicKeyHex The keypair's compressed public key: 66 hex characters starting `02` or `03`.\n * @param signatureDerHex The DER signature over the body, as hex (from `signDer`).\n * @throws {TypeError} when `publicKeyHex` is not 66 hex characters starting `02` or `03`, or `signatureDerHex` is not\n * a non-empty even-length hex string.\n */\nexport function buildStamp(publicKeyHex: string, signatureDerHex: string): string {\n if (typeof publicKeyHex !== \"string\" || !COMPRESSED_PUBLIC_KEY_HEX.test(publicKeyHex)) {\n throw new TypeError(\"buildStamp: expected a 66-character compressed public key hex starting 02 or 03\");\n }\n if (typeof signatureDerHex !== \"string\" || !NON_EMPTY_HEX.test(signatureDerHex)) {\n throw new TypeError(\"buildStamp: expected a non-empty even-length DER signature hex\");\n }\n const stamp = JSON.stringify({\n publicKey: publicKeyHex.toLowerCase(),\n scheme: STAMP_SCHEME,\n signature: signatureDerHex.toLowerCase(),\n });\n return toBase64Url(utf8ToBytes(stamp));\n}\n\n/**\n * Builds the relay's `stamp_header`: `{ name: \"X-Stamp\", value }` where `value` is the **standard base64 (padded)**\n * of the UTF-8 bytes of {@link buildStamp}'s string, so base64 of base64url. The Coordinator decodes it once and\n * forwards the result as the `X-Stamp` header verbatim.\n *\n * Vector (§12.7): the §12.7 public key and DER signature give exactly the §12.7 `stamp_header.value`\n * (`ZXlKd2RXSnNhV05MWlhr…Wk5UVTJaU0o5`).\n *\n * @throws {TypeError} on the same inputs as {@link buildStamp}.\n */\nexport function buildStampHeader(publicKeyHex: string, signatureDerHex: string): StampHeaderDto {\n return {\n name: STAMP_HEADER_NAME,\n value: toBase64(utf8ToBytes(buildStamp(publicKeyHex, signatureDerHex))),\n };\n}\n\n/**\n * Encodes the activity body for the relay's `body` field (guide §7.3): the **standard base64 (padded)** of the exact\n * UTF-8 bytes of `body`, which are the bytes the stamp signed. `toBase64(utf8ToBytes(body))`; never `btoa(body)`,\n * which throws on any character above U+00FF and silently encodes Latin-1 wrongly.\n *\n * Vector (§12.7): the §12.7 body string encodes to the §12.7 request's `body`\n * (`eyJ0eXBlIjoiQUNUSVZJVFlfVFlQRV9TSUdOX1JBV19QQVlMT0FEX1YyIiwi…In19`).\n */\nexport function encodeRelayBody(body: string): string {\n return toBase64(utf8ToBytes(body));\n}\n","import type { RelayPurposeDto, RelayRequestDto } from \"#/models\";\n\nimport { signDer } from \"./sign\";\nimport { buildStampHeader, encodeRelayBody } from \"./stamp\";\n\nimport type { Keypair } from \"./types\";\n\n/**\n * Stamps an activity body and builds the relay request for it (guide §7.2–§7.3):\n *\n * 1. `signDer(keypair.keys.privateKey, body)` over the exact UTF-8 bytes of `body`.\n * 2. Returns exactly `{ body: encodeRelayBody(body), stamp_header: buildStampHeader(keypair.publicKeyHex,\n * signatureDer), purpose }`, with those keys in that order.\n *\n * `body` is the string `buildSignRawPayloadBody` returned; it is never parsed or re-serialised here.\n *\n * @param body The activity body string to sign and forward.\n * @param keypair The registered keypair.\n * @param purpose The relay's purpose. Defaults to `\"signing\"`.\n */\nexport async function createRelayRequest(\n body: string,\n keypair: Keypair,\n purpose: RelayPurposeDto = \"signing\",\n): Promise<RelayRequestDto> {\n const signatureDer = await signDer(keypair.keys.privateKey, body);\n return {\n body: encodeRelayBody(body),\n stamp_header: buildStampHeader(keypair.publicKeyHex, signatureDer),\n purpose,\n };\n}\n","import { DECIMAL_INTEGER_PATTERN } from \"#/shared/patterns\";\n\nimport { MAX_TOKEN_DECIMALS } from \"./constants\";\n\n/**\n * A decimal amount as text: digits with an optional fraction after a `.` (`12`, `12.`, `12.5`), or a fraction alone\n * (`.5`). No sign, exponent, grouping or spaces.\n */\nconst DECIMAL_TEXT_PATTERN = /^(?:([0-9]+)(?:\\.([0-9]*))?|\\.([0-9]+))$/;\n\n/**\n * A run of fraction digits that are all zeros, or none.\n */\nconst ZEROS_PATTERN = /^0*$/;\n\n/**\n * Reads an amount in base units as the API writes it (a holding's `amount`, a leg's `input_amount`, a pay-in's\n * `delivered`): a decimal integer without leading zeros, which may exceed 2^53. `null` when `text` is not one. Pure.\n *\n * @example parseBaseUnits(\"419397733767447402007014\") === 419397733767447402007014n\n * @example parseBaseUnits(\"012\") === null\n */\nexport function parseBaseUnits(text: string): bigint | null {\n return typeof text === \"string\" && DECIMAL_INTEGER_PATTERN.test(text) ? BigInt(text) : null;\n}\n\n/**\n * Reads a decimal amount of a token with `decimals` decimals into its base units, exactly: `toBaseUnits(\"20\", 6)` is\n * `20000000n`, the `amount` a 20 USDC.e quote sends. `null` when `text` is not a decimal amount (see the pattern above)\n * or names a fraction finer than one base unit: an amount is never rounded. Zeros past `decimals` are exact, so\n * `\"1.5000000\"` reads at 6 decimals. Pure.\n *\n * @example toBaseUnits(\"1096.08\", 6) === 1096080000n\n * @example toBaseUnits(\"0.0000001\", 6) === null\n *\n * @throws {TypeError} when `decimals` is not a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.\n */\nexport function toBaseUnits(text: string, decimals: number): bigint | null {\n checkDecimals(\"toBaseUnits\", decimals);\n if (typeof text !== \"string\") {\n return null;\n }\n const match = DECIMAL_TEXT_PATTERN.exec(text);\n if (match === null) {\n return null;\n }\n const fraction = match[2] ?? match[3] ?? \"\";\n if (!ZEROS_PATTERN.test(fraction.slice(decimals))) {\n return null;\n }\n const whole = BigInt(match[1] ?? \"0\");\n const kept = fraction.slice(0, decimals).padEnd(decimals, \"0\");\n\n return whole * 10n ** BigInt(decimals) + (kept === \"\" ? 0n : BigInt(kept));\n}\n\n/**\n * Writes base units of a token with `decimals` decimals as a decimal figure, rounded toward zero to\n * `maxFractionDigits` (every decimal by default) and without trailing zeros: `formatBaseUnits(20049318n, 6, 2)` is\n * `\"20.04\"`. No grouping and no symbol; the screens format it for display. A negative amount keeps its sign, unless it\n * rounds to zero. Pure.\n *\n * @example formatBaseUnits(1096076785n, 6) === \"1096.076785\"\n * @example formatBaseUnits(20000000n, 6) === \"20\"\n *\n * @throws {TypeError} when `units` is not a bigint, `decimals` is not a whole number from 0 to\n * {@link MAX_TOKEN_DECIMALS}, or `maxFractionDigits` is not a whole number from 0.\n */\nexport function formatBaseUnits(units: bigint, decimals: number, maxFractionDigits: number = decimals): string {\n if (typeof units !== \"bigint\") {\n throw new TypeError(\"formatBaseUnits: units must be a bigint\");\n }\n checkDecimals(\"formatBaseUnits\", decimals);\n if (!Number.isSafeInteger(maxFractionDigits) || maxFractionDigits < 0) {\n throw new TypeError(\"formatBaseUnits: maxFractionDigits must be a whole number from 0\");\n }\n const magnitude = units < 0n ? -units : units;\n const scale = 10n ** BigInt(decimals);\n const fraction = (magnitude % scale)\n .toString()\n .padStart(decimals, \"0\")\n .slice(0, Math.min(decimals, maxFractionDigits))\n .replace(/0+$/, \"\");\n const figure = fraction === \"\" ? (magnitude / scale).toString() : `${magnitude / scale}.${fraction}`;\n\n return units < 0n && figure !== \"0\" ? `-${figure}` : figure;\n}\n\n/**\n * Throws unless `decimals` is a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.\n *\n * @throws {TypeError} naming `method` when it is not.\n */\nfunction checkDecimals(method: string, decimals: number): void {\n if (!Number.isSafeInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS) {\n throw new TypeError(`${method}: decimals must be a whole number from 0 to ${MAX_TOKEN_DECIMALS}`);\n }\n}\n","import { DEPOSIT_NATIVE_SELECTOR, PERMIT2_ADDRESS, RELAY_DEPOSITORY_ADDRESS } from \"#/client/constants\";\nimport {\n type Eip712StepDto,\n type EvmTransactionPayloadDto,\n type EvmTransactionStepDto,\n type SolanaTransactionStepDto,\n PAY_IN_TERMINAL_STATES,\n type PayInDestinationDto,\n type PayInDto,\n type PayInLegDto,\n type PayInStepBaseDto,\n type PayInStepDto,\n type PayInTerminalStateDto,\n} from \"#/models\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport { CALLDATA_PATTERN } from \"#/shared/patterns\";\n\nimport { evmChainHex, parseCaip19, parseCaip2 } from \"./caip\";\nimport { parseBaseUnits } from \"./units\";\n\nimport type { PayInStepKind } from \"./types\";\n\n/**\n * A hex quantity as an `evm_transaction` payload writes its value, gas and fees: `0x` and at least one hex digit.\n */\nconst HEX_QUANTITY_PATTERN = /^0x[0-9a-fA-F]+$/;\n\n/**\n * The selector of ERC-20 `approve(address,uint256)`, lowercase with its `0x`.\n */\nconst APPROVE_SELECTOR = \"0x095ea7b3\";\n\nconst TRANSFER_SELECTOR = \"0xa9059cbb\";\n\nconst TEMPO_FEE_MANAGER = \"0xfeec000000000000000000000000000000000000\";\nconst SET_USER_TOKEN_SELECTOR = \"0xe7897444\";\nconst TEMPO_CHAIN_HEX = \"0x1079\";\n\n/**\n * The length of ERC-20 approval or transfer calldata: `0x`, the 4-byte selector and two 32-byte words.\n */\nconst ERC20_CALLDATA_LENGTH = 2 + 8 + 64 + 64;\n\n/**\n * The length of `depositNative(address,bytes32)` calldata as text: `0x`, the 4-byte selector and two 32-byte words.\n */\nconst DEPOSIT_NATIVE_CALLDATA_LENGTH = 2 + 8 + 64 + 64;\n\n/**\n * An ABI-encoded address word as text without `0x`: 12 zero bytes (24 zero digits), then 20 bytes of address.\n */\nconst ADDRESS_WORD_PATTERN = /^0{24}[0-9a-fA-F]{40}$/;\n\n/**\n * {@link PERMIT2_ADDRESS} as an ABI-encoded address word: 12 zero bytes, then the address, lowercase, without `0x`.\n */\nconst PERMIT2_SPENDER_WORD = `${\"0\".repeat(24)}${PERMIT2_ADDRESS.slice(2).toLowerCase()}`;\n\n/**\n * The `primaryType` of mechanism `V`'s one step: a plain Permit2 transfer with no witness, which Stridge's relayer\n * sends. Checked field by field ({@link isRelayedTransfer}), since no witness binds what the signature allows.\n */\nconst RELAYED_TRANSFER_TYPE = \"PermitTransferFrom\";\n\n/**\n * The exact `types` of a {@link RELAYED_TRANSFER_TYPE} step, each list as `[name, type]` in order, as core writes them.\n */\nconst RELAYED_TRANSFER_TYPES: Readonly<Record<string, readonly (readonly [string, string])[]>> = {\n EIP712Domain: [\n [\"name\", \"string\"],\n [\"chainId\", \"uint256\"],\n [\"verifyingContract\", \"address\"],\n ],\n [RELAYED_TRANSFER_TYPE]: [\n [\"permitted\", \"TokenPermissions\"],\n [\"spender\", \"address\"],\n [\"nonce\", \"uint256\"],\n [\"deadline\", \"uint256\"],\n ],\n TokenPermissions: [\n [\"token\", \"address\"],\n [\"amount\", \"uint256\"],\n ],\n};\n\n/**\n * A `uint256` as core writes it in typed data: a decimal string with no leading zero.\n */\nconst DECIMAL_UINT_PATTERN = /^(0|[1-9][0-9]*)$/;\n\n/**\n * The zero EVM address, lowercase.\n */\nconst ZERO_ADDRESS = `0x${\"0\".repeat(40)}`;\n\n/**\n * The `primaryType`s of the typed-data kinds whose type alone names them (pay-in guide §6.1). `Permit` is K3 or K4\n * depending on its fields, so it is told apart by {@link permitKind}.\n */\nconst EIP712_KINDS: Readonly<Record<string, PayInStepKind>> = {\n ReceiveWithAuthorization: \"K1\",\n PermitBatchWitnessTransferFrom: \"K2\",\n PermitWitnessTransferFrom: \"K2\",\n [RELAYED_TRANSFER_TYPE]: \"K2\",\n MetaTransaction: \"K5\",\n SignedBatchedCall: \"K6\",\n};\n\n/**\n * The fields of an EIP-2612 `Permit` (K3), in order.\n */\nconst EIP2612_PERMIT_FIELDS = [\"owner\", \"spender\", \"value\", \"nonce\", \"deadline\"] as const;\n\n/**\n * The fields of a DAI-style `Permit` (K4), in order.\n */\nconst DAI_PERMIT_FIELDS = [\"holder\", \"spender\", \"nonce\", \"expiry\", \"allowed\"] as const;\n\n/**\n * Reports whether the status closes ordinary pay-in actions. Use {@link isPayInSettled} to decide when to stop polling.\n */\nexport function isPayInTerminalState(state: unknown): state is PayInTerminalStateDto {\n return PAY_IN_TERMINAL_STATES.some((terminal) => terminal === state);\n}\n\n/** A canceled or failed pay-in can still complete while Core supplies a late-transfer poll hint. */\nexport function isPayInSettled(read: Pick<PayInDto, \"status\" | \"poll_after_ms\">): boolean {\n return (\n read.status === \"completed\" ||\n read.status === \"expired\" ||\n ((read.status === \"canceled\" || read.status === \"failed\") && read.poll_after_ms == null)\n );\n}\n\n/**\n * The step to do now (pay-in guide §5.6): the entry of `steps` that `required_steps[0]` names. `null` when the pay-in\n * is terminal, when nothing is required (a `processing` pay-in waiting on a chain, a bridge or the drip), or when no\n * step has that id. Never a step from history: only `required_steps` is acted on after confirm, one step at a time and\n * in order, since the next step often exists only once the previous one lands. Pure.\n */\nexport function nextRequiredStep(payIn: Pick<PayInDto, \"status\" | \"steps\" | \"required_steps\">): PayInStepDto | null {\n if (isPayInTerminalState(payIn.status)) {\n return null;\n }\n const stepId = payIn.required_steps[0];\n if (stepId === undefined) {\n return null;\n }\n\n return payIn.steps.find((step) => step.id === stepId) ?? null;\n}\n\n/**\n * Names a pay-in step's kind (pay-in guide §6.1): `K8` for `solana_transaction`, `K7` for `evm_transaction`, and\n * for an `eip712` the kind its payload's `primaryType` names, a `Permit` told apart by its fields. `\"unknown\"` for any\n * other scheme, a typed-data type outside the list, or a `Permit` with neither field list: such a step is never\n * signed. The kind is for choosing the copy and the wallet call; it says nothing about whether the payload is sound,\n * which {@link isSignablePayInStep} checks. Pure.\n */\nexport function payInStepKind(step: Pick<PayInStepBaseDto, \"scheme\" | \"payload\">): PayInStepKind | \"unknown\" {\n if (step.scheme === \"solana_transaction\") return \"K8\";\n if (step.scheme === \"evm_transaction\") {\n return \"K7\";\n }\n if (step.scheme !== \"eip712\" || !isJsonObject(step.payload) || typeof step.payload.primaryType !== \"string\") {\n return \"unknown\";\n }\n const { primaryType } = step.payload;\n if (primaryType === \"Permit\") {\n return permitKind(step.payload.types);\n }\n\n return Object.hasOwn(EIP712_KINDS, primaryType) ? EIP712_KINDS[primaryType] : \"unknown\";\n}\n\n/**\n * The instant, in epoch milliseconds, by which every one of `steps` must be signed or sent and submitted: the earliest\n * of their `expires_at` and, while the pay-in is `requires_confirmation`, its own `expires_at` (the confirm\n * deadline); after confirm, its `deadline` when it has one instead. At quote time pass every quote step (a Solana step\n * lives about 40 s, the quote 60 s); after confirm, the required step.\n *\n * `null` when there is no instant at all, or one does not parse: no deadline can be proven, so treat it as passed and\n * sign nothing. Compare it with a server-corrected clock, less a margin for the wallet prompt. Pure.\n */\nexport function earliestPayInExpiry(\n payIn: Pick<PayInDto, \"status\" | \"expires_at\" | \"deadline\">,\n steps: readonly Pick<PayInStepBaseDto, \"expires_at\">[],\n): number | null {\n const instants = steps.map((step) => step.expires_at);\n if (payIn.status === \"requires_confirmation\") {\n instants.push(payIn.expires_at);\n } else if (typeof payIn.deadline === \"string\") {\n instants.push(payIn.deadline);\n }\n if (instants.length === 0) {\n return null;\n }\n const times = instants.map((instant) => (typeof instant === \"string\" ? Date.parse(instant) : Number.NaN));\n if (times.some((time) => Number.isNaN(time))) {\n return null;\n }\n\n return Math.min(...times);\n}\n\n/**\n * Reports whether a wallet may be asked to sign or send `step` (pay-in guide §8): its scheme is known and its payload\n * holds what that wallet call needs, checked by value, since a pay-in answer is read without checking any payload.\n * The kit runs it before every wallet prompt; a step that fails it is never signed: cancel the pay-in and report it\n * (§8.4). Pure.\n *\n * - `eip712` — the step is on an `eip155` chain; the payload has an object `types` whose every entry is a list of\n * `{ name, type }` strings and which holds `EIP712Domain` and the `primaryType`; a `primaryType` whose kind is K1 to\n * K6 ({@link payInStepKind}); an object `domain` and `message`; and no number anywhere that is not a safe integer.\n * `JSON.parse` rounds a larger number, so the payload passed to the wallet would no longer be the one core sent, and\n * the step is refused rather than signed altered. A K2 `PermitTransferFrom` (mechanism `V`) has exactly core's\n * types, domain name and field shapes ({@link isRelayedTransfer}). Permit2 is bound where the kind says it must be, any case of\n * {@link PERMIT2_ADDRESS} accepted: a K2 transfer's `domain.verifyingContract` is Permit2, a K3 or K4 permit's\n * `message.spender` is Permit2, and a K5 meta-transaction's `message.functionSignature` is\n * `approve(PERMIT2_ADDRESS, amount)` calldata. Core puts a signed approval on chain without the user paying gas, so\n * one naming any other spender is never signed.\n * - `evm_transaction` — `from` and `to` are EVM addresses, `data` is `0x` and whole bytes of hex, `value`, `gas`,\n * `max_fee_per_gas` and `max_priority_fee_per_gas` are hex quantities, `chain_id` is exactly the step's chain as\n * {@link evmChainHex} writes it, and the call has the shape of a Permit2 approval, Tempo fee-coin step, coin send, or wallet transfer.\n * A wallet transfer must also pass {@link isWalletTransfer} against its leg and destination before a prompt.\n *\n * - `solana_transaction` — a Solana CAIP-2 chain and nonempty message/fee-payer strings. The hub's lazy signer\n * validates the v0 message bytes, sponsor, user and instructions before the Wallet Standard prompt.\n *\n * Whether the step is the one to do now, whether its signer is the connected wallet (and a coin send's depositor and\n * value its leg's), and whether it has expired are the caller's to check ({@link nextRequiredStep}, {@link earliestPayInExpiry}).\n */\nexport function isSignablePayInStep(\n step: PayInStepDto,\n): step is Eip712StepDto | EvmTransactionStepDto | SolanaTransactionStepDto {\n if (!isJsonObject(step) || !isJsonObject(step.payload) || typeof step.chain !== \"string\") {\n return false;\n }\n switch (step.scheme) {\n case \"solana_transaction\":\n return (\n parseCaip2(step.chain)?.namespace === \"solana\" &&\n typeof step.payload.message === \"string\" &&\n step.payload.message.length > 0 &&\n typeof step.payload.fee_payer === \"string\" &&\n step.payload.fee_payer.length > 0\n );\n case \"eip712\":\n return isSignableEip712(step.chain, step.payload, payInStepKind(step));\n case \"evm_transaction\":\n return isSendableEvmTransaction(step.chain, step.payload);\n default:\n return false;\n }\n}\n\n/**\n * Reports whether an `evm_transaction` payload is ERC-20 `approve(PERMIT2_ADDRESS, amount)` that sends no native\n * value (pay-in guide §8.3, K7): `data` is the `0x095ea7b3` selector and two 32-byte words, the first of them\n * {@link PERMIT2_ADDRESS}, and `value` is a hex zero. Any amount passes, core asking for the max; that `to` is the leg's\n * source token is the caller's to check. Pure.\n */\nexport function isPermit2Approval(payload: Pick<EvmTransactionPayloadDto, \"data\" | \"value\">): boolean {\n if (!isJsonObject(payload)) {\n return false;\n }\n const { data, value } = payload;\n\n return isPermit2ApproveCalldata(data) && isHexQuantity(value) && BigInt(value) === 0n;\n}\n\n/**\n * Reads the token from a zero-value Tempo FeeManager setUserToken call, or null for any other payload.\n * The caller binds the token and sender to the leg and connected wallet before sending.\n */\nexport function tempoFeeTokenOf(payload: unknown): string | null {\n if (!isJsonObject(payload)) return null;\n const { chain_id, to, data, value } = payload;\n if (\n chain_id !== TEMPO_CHAIN_HEX ||\n typeof to !== \"string\" ||\n to.toLowerCase() !== TEMPO_FEE_MANAGER ||\n typeof data !== \"string\" ||\n data.slice(0, 10).toLowerCase() !== SET_USER_TOKEN_SELECTOR ||\n !ADDRESS_WORD_PATTERN.test(data.slice(10)) ||\n !isHexQuantity(value) ||\n BigInt(value) !== 0n\n )\n return null;\n return `0x${data.slice(34).toLowerCase()}`;\n}\n\n/**\n * Reports whether an `evm_transaction` payload is a coin send (mechanism `W`): `to` is {@link RELAY_DEPOSITORY_ADDRESS}\n * in any case, `data` is exactly the {@link DEPOSIT_NATIVE_SELECTOR} and two 32-byte words, the first a zero-padded\n * address (the depositor), and `value` is a hex quantity above zero. That the depositor is the wallet and the value is\n * at most the leg's `input_amount` are the caller's to check. Pure.\n */\nexport function isCoinSend(payload: Pick<EvmTransactionPayloadDto, \"to\" | \"data\" | \"value\">): boolean {\n if (!isJsonObject(payload)) {\n return false;\n }\n const { to, data, value } = payload;\n\n return (\n typeof to === \"string\" &&\n to.toLowerCase() === RELAY_DEPOSITORY_ADDRESS.toLowerCase() &&\n coinSendDepositor(data) !== null &&\n isHexQuantity(value) &&\n BigInt(value) > 0n\n );\n}\n\n/**\n * Whether the calldata and value have the shape of a native or ERC-20 wallet transfer.\n */\nfunction isWalletTransferShape(data: string, value: string): boolean {\n if (!isHexQuantity(value)) return false;\n if (data === \"0x\") return BigInt(value) > 0n;\n return (\n data.length === ERC20_CALLDATA_LENGTH &&\n data.slice(0, 10).toLowerCase() === TRANSFER_SELECTOR &&\n CALLDATA_PATTERN.test(data) &&\n ADDRESS_WORD_PATTERN.test(data.slice(10, 74)) &&\n BigInt(value) === 0n\n );\n}\n\n/**\n * Binds an X, Y or U transfer to its leg's chain, asset and exact input, and to the pay-in's recipient. Y and U\n * move only ERC-20 tokens.\n * The caller checks the enclosing step, connected sender and reviewed destination separately.\n */\nexport function isWalletTransfer(\n payload: EvmTransactionPayloadDto,\n leg: Pick<PayInLegDto, \"mechanism\" | \"source_asset\" | \"input_amount\">,\n destination: PayInDestinationDto,\n): boolean {\n if ((leg.mechanism !== \"X\" && leg.mechanism !== \"Y\" && leg.mechanism !== \"U\") || !isJsonObject(payload)) return false;\n const source = parseCaip19(leg.source_asset);\n const chain = source === null ? null : evmChainHex(source.chain);\n const amount = parseBaseUnits(leg.input_amount);\n const { to, data, value, chain_id } = payload;\n if (\n source === null ||\n chain === null ||\n chain_id !== chain ||\n amount === null ||\n amount <= 0n ||\n !isEvmAddress(destination.address) ||\n !isEvmAddress(to) ||\n typeof data !== \"string\" ||\n !isWalletTransferShape(data, value)\n )\n return false;\n\n if (source.assetNamespace === \"slip44\") {\n return (\n leg.mechanism === \"X\" &&\n /^[0-9]+$/.test(source.assetReference) &&\n leg.source_asset === destination.asset &&\n data === \"0x\" &&\n to.toLowerCase() === destination.address.toLowerCase() &&\n BigInt(value) === amount\n );\n }\n const token = source.assetReference;\n const target = parseCaip19(destination.asset);\n return (\n source.assetNamespace === \"erc20\" &&\n isEvmAddress(token) &&\n target?.chain === source.chain &&\n target.assetNamespace === \"erc20\" &&\n isEvmAddress(target.assetReference) &&\n token.toLowerCase() === target.assetReference.toLowerCase() &&\n to.toLowerCase() === token.toLowerCase() &&\n data !== \"0x\" &&\n data.slice(34, 74).toLowerCase() === destination.address.slice(2).toLowerCase() &&\n BigInt(`0x${data.slice(74)}`) === amount\n );\n}\n\n/**\n * The depositor a coin send's `data` names (its first word), as `0x` and 40 lowercase hex digits, or `null` when\n * `data` is not coin-send calldata ({@link isCoinSend}). Pure.\n */\nexport function coinSendDepositor(data: unknown): string | null {\n if (\n typeof data !== \"string\" ||\n data.length !== DEPOSIT_NATIVE_CALLDATA_LENGTH ||\n data.slice(0, 10).toLowerCase() !== DEPOSIT_NATIVE_SELECTOR ||\n !CALLDATA_PATTERN.test(data) ||\n !ADDRESS_WORD_PATTERN.test(data.slice(10, 74))\n ) {\n return null;\n }\n\n return `0x${data.slice(34, 74).toLowerCase()}`;\n}\n\n/**\n * Reports whether `data` is ERC-20 `approve(PERMIT2_ADDRESS, amount)` calldata, any amount: the `0x095ea7b3` selector\n * and two 32-byte words, the first of them {@link PERMIT2_ADDRESS}, either case. A K7 transaction's `data` and a K5\n * meta-transaction's `functionSignature` are both read with it.\n */\nfunction isPermit2ApproveCalldata(data: unknown): data is string {\n return (\n typeof data === \"string\" &&\n data.length === ERC20_CALLDATA_LENGTH &&\n CALLDATA_PATTERN.test(data) &&\n data.slice(0, 10).toLowerCase() === APPROVE_SELECTOR &&\n data.slice(10, 74).toLowerCase() === PERMIT2_SPENDER_WORD\n );\n}\n\n/**\n * Reports whether `value` is {@link PERMIT2_ADDRESS}, in any case.\n */\nfunction isPermit2Address(value: unknown): boolean {\n return typeof value === \"string\" && value.toLowerCase() === PERMIT2_ADDRESS.toLowerCase();\n}\n\n/**\n * The kind of a typed-data `Permit`: K3 when `types.Permit` lists the EIP-2612 fields in order, K4 when it lists the\n * DAI-style ones, `\"unknown\"` otherwise.\n */\nfunction permitKind(types: unknown): PayInStepKind | \"unknown\" {\n if (!isJsonObject(types) || !Array.isArray(types.Permit)) {\n return \"unknown\";\n }\n const names = types.Permit.map((field: unknown) => (isJsonObject(field) ? field.name : undefined));\n if (hasFieldNames(names, EIP2612_PERMIT_FIELDS)) {\n return \"K3\";\n }\n if (hasFieldNames(names, DAI_PERMIT_FIELDS)) {\n return \"K4\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Reports whether `names` is exactly `expected`, in order.\n */\nfunction hasFieldNames(names: readonly unknown[], expected: readonly string[]): boolean {\n return names.length === expected.length && expected.every((name, index) => names[index] === name);\n}\n\n/**\n * The `eip712` rule of {@link isSignablePayInStep}.\n */\nfunction isSignableEip712(chain: string, payload: Record<string, unknown>, kind: PayInStepKind | \"unknown\"): boolean {\n const { types, primaryType, domain, message } = payload;\n\n return (\n evmChainHex(chain) !== null &&\n isEip712Types(types) &&\n Object.hasOwn(types, \"EIP712Domain\") &&\n typeof primaryType === \"string\" &&\n Object.hasOwn(types, primaryType) &&\n isJsonObject(domain) &&\n isJsonObject(message) &&\n isTypedDataKind(kind) &&\n bindsPermit2(kind, domain, message) &&\n (primaryType !== RELAYED_TRANSFER_TYPE || isRelayedTransfer(types, domain, message)) &&\n hasOnlySafeIntegers(payload)\n );\n}\n\n/**\n * Reports whether typed data of `kind` binds Permit2 where that kind must (pay-in guide §6.1): a K2 transfer's\n * `domain.verifyingContract` is Permit2, a K3 or K4 permit's `message.spender` is Permit2, and a K5\n * meta-transaction's `message.functionSignature` approves Permit2 ({@link isPermit2ApproveCalldata}). K1 and K6 name\n * no Permit2 and pass; any other kind fails.\n */\nfunction bindsPermit2(\n kind: PayInStepKind | \"unknown\",\n domain: Record<string, unknown>,\n message: Record<string, unknown>,\n): boolean {\n switch (kind) {\n case \"K1\":\n case \"K6\":\n return true;\n case \"K2\":\n return isPermit2Address(domain.verifyingContract);\n case \"K3\":\n case \"K4\":\n return isPermit2Address(message.spender);\n case \"K5\":\n return isPermit2ApproveCalldata(message.functionSignature);\n default:\n return false;\n }\n}\n\n/**\n * Reports whether a `PermitTransferFrom` is exactly core's relayed transfer: `types` holds only\n * {@link RELAYED_TRANSFER_TYPES}, field for field and in order; the domain, the message and `permitted` hold exactly\n * the declared keys, so a wallet that reads the keys signs the digest core issued; the domain is named `Permit2` with\n * a positive number `chainId`; `permitted` is one `{ token, amount }`; `spender` is a nonzero address; and the amount,\n * nonce and deadline are decimal `uint256` strings.\n * The spender is core's relayer, which differs by environment, so it is not pinned: which token, how much and until\n * when are the caller's to check against the leg.\n */\nfunction isRelayedTransfer(\n types: Record<string, unknown[]>,\n domain: Record<string, unknown>,\n message: Record<string, unknown>,\n): boolean {\n const { permitted } = message;\n return (\n Object.keys(types).length === Object.keys(RELAYED_TRANSFER_TYPES).length &&\n Object.entries(RELAYED_TRANSFER_TYPES).every(\n ([name, fields]) =>\n Object.hasOwn(types, name) &&\n types[name]!.length === fields.length &&\n fields.every(([field, type], index) => {\n const entry = types[name]![index];\n return isJsonObject(entry) && entry.name === field && entry.type === type;\n }),\n ) &&\n hasExactKeys(domain, [\"name\", \"chainId\", \"verifyingContract\"]) &&\n domain.name === \"Permit2\" &&\n Number.isSafeInteger(domain.chainId) &&\n (domain.chainId as number) > 0 &&\n hasExactKeys(message, [\"permitted\", \"spender\", \"nonce\", \"deadline\"]) &&\n isJsonObject(permitted) &&\n hasExactKeys(permitted, [\"token\", \"amount\"]) &&\n isEvmAddress(permitted.token) &&\n isDecimalUint(permitted.amount) &&\n isEvmAddress(message.spender) &&\n message.spender.toLowerCase() !== ZERO_ADDRESS &&\n isDecimalUint(message.nonce) &&\n isDecimalUint(message.deadline)\n );\n}\n\n/**\n * Reports whether `value` has exactly the keys `keys`, in any order.\n */\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n const own = Object.keys(value);\n return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key));\n}\n\n/**\n * Reports whether `value` is a `uint256` as a decimal string ({@link DECIMAL_UINT_PATTERN}) below 2^256.\n */\nfunction isDecimalUint(value: unknown): value is string {\n return typeof value === \"string\" && DECIMAL_UINT_PATTERN.test(value) && BigInt(value) < 2n ** 256n;\n}\n\n/**\n * Reports whether `value` is a typed-data `types` object: every entry a list of `{ name, type }` with string values.\n */\nfunction isEip712Types(value: unknown): value is Record<string, unknown[]> {\n return (\n isJsonObject(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field: unknown) => isJsonObject(field) && typeof field.name === \"string\" && typeof field.type === \"string\",\n ),\n )\n );\n}\n\n/**\n * Reports whether `kind` is one the EVM wallet signs as typed data, K1 to K6.\n */\nfunction isTypedDataKind(kind: PayInStepKind | \"unknown\"): boolean {\n return [\"K1\", \"K2\", \"K3\", \"K4\", \"K5\", \"K6\"].includes(kind);\n}\n\n/**\n * Reports whether every number anywhere inside `root` is a safe integer. Walks with its own stack, so a deeply nested\n * payload cannot overflow the call stack, and visits each object once.\n */\nfunction hasOnlySafeIntegers(root: unknown): boolean {\n const pending: unknown[] = [root];\n const seen = new Set<object>();\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n return false;\n }\n if (typeof value === \"object\" && value !== null && !seen.has(value)) {\n seen.add(value);\n for (const child of Object.values(value)) {\n pending.push(child);\n }\n }\n }\n\n return true;\n}\n\n/**\n * The `evm_transaction` rule of {@link isSignablePayInStep}.\n */\nfunction isSendableEvmTransaction(chain: string, payload: Record<string, unknown>): boolean {\n const chainHex = evmChainHex(chain);\n\n return (\n chainHex !== null &&\n payload.chain_id === chainHex &&\n isEvmAddress(payload.from) &&\n isEvmAddress(payload.to) &&\n typeof payload.data === \"string\" &&\n CALLDATA_PATTERN.test(payload.data) &&\n isHexQuantity(payload.value) &&\n isHexQuantity(payload.gas) &&\n isHexQuantity(payload.max_fee_per_gas) &&\n isHexQuantity(payload.max_priority_fee_per_gas) &&\n (isPermit2Approval({ data: payload.data, value: payload.value }) ||\n isCoinSend({ to: payload.to, data: payload.data, value: payload.value }) ||\n tempoFeeTokenOf(payload) !== null ||\n isWalletTransferShape(payload.data, payload.value))\n );\n}\n\n/**\n * Reports whether `value` is an EVM address: `0x` and 40 hex digits, any case.\n */\nfunction isEvmAddress(value: unknown): value is string {\n return typeof value === \"string\" && EVM_ADDRESS_PATTERN.test(value);\n}\n\n/**\n * Reports whether `value` is a hex quantity: `0x` and at least one hex digit.\n */\nfunction isHexQuantity(value: unknown): value is string {\n return typeof value === \"string\" && HEX_QUANTITY_PATTERN.test(value);\n}\n","/**\n * The default `Sleep`: a `setTimeout` of `ms` (negative values count as `0`). When `signal` is already aborted it\n * rejects with `signal.reason` without scheduling anything; when `signal` aborts during the wait it clears the timer\n * and rejects with `signal.reason`. The abort listener is removed once the wait settles either way.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n\n const onAbort = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n reject(signal?.reason);\n };\n\n const timer = setTimeout(\n () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n ms > 0 ? ms : 0,\n );\n\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import { sleep as defaultSleep } from \"./sleep\";\n\nimport type { WaitForActiveWalletOptions, WaitForActiveWalletOutcome } from \"./types\";\n\n/**\n * Polls `GET /wallet/v1/account` until the wallet is active, closed, or the attempts run out (guide §5, §10).\n * Every read counts against the session's 120-a-minute limit, which the default 1.5 s\n * interval keeps well under.\n *\n * Since Coordinator rc.19 nothing is polled on the normal path: verify returns the wallet, and a keypair registration\n * waits on the server for it to become active. Use this only for a short, bounded read (a small `maxAttempts`), such\n * as fetching `provider_account_ref` once after the first registration.\n *\n * The loop, for `attempt` from 1 to `maxAttempts`:\n *\n * 1. `signal?.throwIfAborted()`.\n * 2. `wallet = await getWallet({ signal })`. The first read happens at once.\n * 3. `wallet.status === \"active\"`, and (when `requireWalletRef`) `wallet.provider_account_ref !== \"\"`\n * → resolve `{ kind: \"active\", wallet }`.\n * 4. `wallet.status === \"wound_down\"` → resolve `{ kind: \"wound-down\", wallet }`.\n * 5. `attempt === maxAttempts` → resolve `{ kind: \"timeout\", wallet }`.\n * 6. `await sleep(intervalMs, signal)` and continue.\n *\n * So `getWallet` is called at most `maxAttempts` times and `sleep` at most `maxAttempts - 1` times. An active wallet\n * with an empty `provider_account_ref` keeps polling. Errors from `getWallet` propagate at once, without a retry. An\n * abort rejects with `signal.reason`.\n *\n * @throws {TypeError} (as a rejection) when `maxAttempts` is not a positive integer or `intervalMs` is negative.\n */\nexport async function waitForActiveWallet(options: WaitForActiveWalletOptions): Promise<WaitForActiveWalletOutcome> {\n const { getWallet, signal, intervalMs = 1500, maxAttempts = 80, requireWalletRef = true, sleep = defaultSleep } = options;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new TypeError(\"waitForActiveWallet: maxAttempts must be a positive integer\");\n }\n if (!Number.isFinite(intervalMs) || intervalMs < 0) {\n throw new TypeError(\"waitForActiveWallet: intervalMs must be a non-negative finite number\");\n }\n\n for (let attempt = 1; ; attempt += 1) {\n signal?.throwIfAborted();\n const wallet = await getWallet({ signal });\n if (wallet.status === \"active\" && (!requireWalletRef || wallet.provider_account_ref !== \"\")) {\n return { kind: \"active\", wallet };\n }\n if (wallet.status === \"wound_down\") {\n return { kind: \"wound-down\", wallet };\n }\n if (attempt === maxAttempts) {\n return { kind: \"timeout\", wallet };\n }\n await sleep(intervalMs, signal);\n }\n}\n","import { sleep as defaultSleep } from \"./sleep\";\n\nimport type { WaitForRoundOptions, WaitForRoundOutcome } from \"./types\";\n\n/**\n * Whether `value` is a finite number above zero.\n */\nfunction isPositiveFinite(value: number): boolean {\n return Number.isFinite(value) && value > 0;\n}\n\n/**\n * Polls `GET /wallet/v1/auth-rounds/{id}` until the round is ready, failed, or ends (guide §3.2). Only an open that answered\n * `202` needs it: a `200` open already carries the ready round. A `202` (`status: \"opening\"`) means still opening;\n * that includes an unknown round and a decoy, so besides `ready` and `failed` the only stop is `expires_at`.\n *\n * The loop, with `attempt` starting at 0:\n *\n * 1. `signal?.throwIfAborted()`.\n * 2. `round = await getRound(roundId, { signal })`. The first read happens at once, with no initial wait.\n * 3. `round.status === \"ready\"` → resolve `{ kind: \"ready\", round }`; `round.status === \"failed\"` → resolve\n * `{ kind: \"failed\" }` at once, whatever time is left.\n * 4. `remaining = expiresAtMs - now()`. `remaining <= 0` → resolve `{ kind: \"expired\" }`.\n * 5. `await sleep(min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal)`, then\n * `attempt += 1` and go to 1. So with the defaults the waits are 250, 500, 1000, 1000, … ms, and the last read\n * lands at `expires_at`.\n *\n * Errors from `getRound` (a `SuaNetworkError`, say) propagate at once, without a retry; the caller may call again\n * for the same round. An abort rejects with `signal.reason`.\n *\n * Pure apart from the injected `getRound`, `sleep` and `now`.\n *\n * @throws {TypeError} (as a rejection, before the first read) when `expiresAt` does not parse with `Date.parse`,\n * `initialIntervalMs` or `maxIntervalMs` is not a positive finite number, or `backoffFactor` is below `1`.\n */\nexport async function waitForRound(options: WaitForRoundOptions): Promise<WaitForRoundOutcome> {\n const {\n getRound,\n roundId,\n expiresAt,\n signal,\n initialIntervalMs = 250,\n maxIntervalMs = 1000,\n backoffFactor = 2,\n sleep = defaultSleep,\n now = Date.now,\n } = options;\n\n const expiresAtMs = Date.parse(expiresAt);\n if (Number.isNaN(expiresAtMs)) {\n throw new TypeError(\"waitForRound: expiresAt must be an RFC 3339 instant\");\n }\n if (!isPositiveFinite(initialIntervalMs)) {\n throw new TypeError(\"waitForRound: initialIntervalMs must be a positive finite number\");\n }\n if (!isPositiveFinite(maxIntervalMs)) {\n throw new TypeError(\"waitForRound: maxIntervalMs must be a positive finite number\");\n }\n if (!(backoffFactor >= 1)) {\n throw new TypeError(\"waitForRound: backoffFactor must be at least 1\");\n }\n\n for (let attempt = 0; ; attempt += 1) {\n signal?.throwIfAborted();\n const round = await getRound(roundId, { signal });\n if (round.status === \"ready\") {\n return { kind: \"ready\", round };\n }\n if (round.status === \"failed\") {\n return { kind: \"failed\" };\n }\n const remaining = expiresAtMs - now();\n if (remaining <= 0) {\n return { kind: \"expired\" };\n }\n await sleep(Math.min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal);\n }\n}\n","import { toHex } from \"#/encoding\";\nimport type { SignRawPayloadActivityDto } from \"#/models\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\n\nimport type { SignRawPayloadInput } from \"./types\";\n\n/**\n * Builds the `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2` body for an EVM message signature (guide §7.1, §12.7): the exact\n * string to sign and relay, never re-serialised afterwards. Keep it: `settleRelay` compares the answer with it.\n *\n * Returns `JSON.stringify` of an object literal written in exactly this key order (a `SignRawPayloadActivityDto`):\n * `type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\"`, `timestampMs: String(input.signedAtMs)`, `organizationId:\n * input.walletRef`, `parameters: { signWith: input.evmAddress, payload: toHex(input.payload), encoding:\n * \"PAYLOAD_ENCODING_HEXADECIMAL\", hashFunction: \"HASH_FUNCTION_KECCAK256\" }`. The payload hex is lowercase with no\n * `0x`; the address is kept verbatim.\n *\n * Vector (§12.7): `{ walletRef: \"497b3e43-6b9d-4555-b839-5b791701aa43\", evmAddress:\n * \"0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716\", payload: utf8ToBytes(\"stridge relay smoke test\"), signedAtMs:\n * 1790000000000 }` returns the §12.7 body byte for byte.\n *\n * @throws {TypeError} when `walletRef` is empty, `evmAddress` is not `0x` plus 40 hex digits, `payload` is empty, or\n * `signedAtMs` is not a non-negative safe integer.\n */\nexport function buildSignRawPayloadBody(input: SignRawPayloadInput): string {\n const { walletRef, evmAddress, payload, signedAtMs } = input;\n if (typeof walletRef !== \"string\" || walletRef === \"\") {\n throw new TypeError(\"buildSignRawPayloadBody: walletRef must be a non-empty string\");\n }\n if (typeof evmAddress !== \"string\" || !EVM_ADDRESS_PATTERN.test(evmAddress)) {\n throw new TypeError(\"buildSignRawPayloadBody: evmAddress must be 0x followed by 40 hex digits\");\n }\n if (!(payload instanceof Uint8Array) || payload.length === 0) {\n throw new TypeError(\"buildSignRawPayloadBody: payload must be a non-empty Uint8Array\");\n }\n if (!Number.isSafeInteger(signedAtMs) || signedAtMs < 0) {\n throw new TypeError(\"buildSignRawPayloadBody: signedAtMs must be a non-negative safe integer\");\n }\n\n const activity: SignRawPayloadActivityDto = {\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: String(signedAtMs),\n organizationId: walletRef,\n parameters: {\n signWith: evmAddress,\n payload: toHex(payload),\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_KECCAK256\",\n },\n };\n return JSON.stringify(activity);\n}\n","/**\n * The EIP-191 version `0x45` (\"E\") prefix of a personal message, before the decimal byte length: the byte `0x19`, then\n * `Ethereum Signed Message:` and a line feed.\n */\nexport const PERSONAL_MESSAGE_PREFIX = \"\\x19Ethereum Signed Message:\\n\";\n\n/**\n * The order n of the secp256k1 group. A signature's `s` above `n / 2` is \"high\"; the low-s form is `n - s`.\n */\nexport const SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;\n\n/**\n * r and s of a secp256k1 signature: 32 bytes as 64 hex digits, either case.\n */\nexport const SCALAR_HEX_PATTERN = /^[0-9a-fA-F]{64}$/;\n","import { utf8ToBytes } from \"#/encoding\";\n\nimport { buildSignRawPayloadBody } from \"./buildSignRawPayloadBody\";\nimport { PERSONAL_MESSAGE_PREFIX } from \"./constants\";\n\nimport type { PersonalSignBody, PersonalSignInput } from \"./types\";\n\n/**\n * Builds the EIP-191 personal-message payload for a text message: the UTF-8 bytes of\n * `PERSONAL_MESSAGE_PREFIX + String(byteLength)` followed by the UTF-8 bytes of `message`, where `byteLength` is the\n * UTF-8 byte count of `message` written in decimal (`utf8ToBytes(message).length`, never `message.length`). The\n * message is always text: a `0x…` string is encoded as its characters.\n *\n * `keccak256` of the result equals viem's `hashMessage(message)`.\n *\n * Vectors:\n * - `\"hello world\"` → hex `19457468657265756d205369676e6564204d6573736167653a0a313168656c6c6f20776f726c64` (the\n * length is `11`); its keccak-256 is `d9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68`.\n * - `\"héllo\"` has 6 UTF-8 bytes, so the length part is `\"6\"`.\n * - `\"0x1234\"` is 6 characters of text, so the length part is `\"6\"` and the bytes are `30 78 31 32 33 34`.\n *\n * @throws {TypeError} when `message` is not a non-empty string.\n */\nexport function buildPersonalSignPayload(message: string): Uint8Array {\n if (typeof message !== \"string\" || message === \"\") {\n throw new TypeError(\"buildPersonalSignPayload: message must be a non-empty string\");\n }\n const messageBytes = utf8ToBytes(message);\n const prefixBytes = utf8ToBytes(`${PERSONAL_MESSAGE_PREFIX}${String(messageBytes.length)}`);\n const payload = new Uint8Array(prefixBytes.length + messageBytes.length);\n payload.set(prefixBytes, 0);\n payload.set(messageBytes, prefixBytes.length);\n return payload;\n}\n\n/**\n * Builds the relay body for an app's `sign(message)`: the only path an app's message takes to a signature.\n *\n * 1. `payload = buildPersonalSignPayload(input.message)`.\n * 2. `body = buildSignRawPayloadBody({ walletRef: input.walletRef, evmAddress: input.evmAddress, payload, signedAtMs:\n * input.signedAtMs })`, so the body carries `PAYLOAD_ENCODING_HEXADECIMAL`, `HASH_FUNCTION_KECCAK256` and the\n * payload as lowercase hex without `0x`.\n * 3. Returns exactly `{ body, payload }`.\n *\n * Turnkey then signs `keccak256(payload)`, which is viem's `hashMessage(message)`, so the signature (after\n * `toEvmSignature`) is byte-identical to viem's `signMessage`.\n *\n * Vector: `{ walletRef: \"497b3e43-6b9d-4555-b839-5b791701aa43\", evmAddress: \"0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716\",\n * message: \"hello world\", signedAtMs: 1790000000000 }` gives a body whose `parameters.payload` is the\n * `buildPersonalSignPayload(\"hello world\")` hex above and whose other fields match the guide's relay example body.\n *\n * @throws {TypeError} when `message` is empty or not a string, and on every input `buildSignRawPayloadBody` refuses.\n */\nexport function buildPersonalSignBody(input: PersonalSignInput): PersonalSignBody {\n const payload = buildPersonalSignPayload(input.message);\n const body = buildSignRawPayloadBody({\n walletRef: input.walletRef,\n evmAddress: input.evmAddress,\n payload,\n signedAtMs: input.signedAtMs,\n });\n return { body, payload };\n}\n","import { bytesToUtf8, fromBase64 } from \"#/encoding\";\nimport type { RelayResponseDto } from \"#/models\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\n\nimport { SCALAR_HEX_PATTERN } from \"./constants\";\n\nimport type { RelayResult } from \"./types\";\n\n/**\n * The only recovery ids the hub can build an EVM signature from.\n */\nconst RECOVERY_IDS: ReadonlySet<string> = new Set([\"00\", \"01\"]);\n\n/**\n * The only activity type this decoder reads a result for.\n */\nconst SIGN_RAW_PAYLOAD_TYPE = \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\";\n\n/**\n * gRPC codes that prove Turnkey refused the request before acting on it: `INVALID_ARGUMENT` (3), `NOT_FOUND` (5),\n * `ALREADY_EXISTS` (6), `PERMISSION_DENIED` (7), `RESOURCE_EXHAUSTED` (8), `FAILED_PRECONDITION` (9), `OUT_OF_RANGE`\n * (11), `UNIMPLEMENTED` (12) and `UNAUTHENTICATED` (16). Every other code (`CANCELLED`, `UNKNOWN`,\n * `DEADLINE_EXCEEDED`, `ABORTED`, `INTERNAL`, `UNAVAILABLE`, `DATA_LOSS`) is what a server-side failure looks like, and\n * SigningRouter reads a Turnkey `5xx` as ambiguous.\n */\nconst REFUSAL_CODES: ReadonlySet<number> = new Set([3, 5, 6, 7, 8, 9, 11, 12, 16]);\n\n/**\n * Reads `provider_response` as a JSON object: standard base64, then strict UTF-8, then JSON. Returns `null` when any\n * step fails or the value is not a JSON object. Never throws.\n */\nfunction readProviderObject(providerResponse: unknown): Record<string, unknown> | null {\n if (typeof providerResponse !== \"string\" || providerResponse === \"\") {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(bytesToUtf8(fromBase64(providerResponse)));\n return isJsonObject(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Parses the signed body string back into the fields the answer must echo, or `null` when it is not a\n * `SignRawPayloadActivityDto` JSON with string fields. Never throws.\n */\nfunction readSignedBody(signedBody: unknown): Record<string, string> | null {\n if (typeof signedBody !== \"string\") {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(signedBody);\n } catch {\n return null;\n }\n if (!isJsonObject(parsed) || !isJsonObject(parsed.parameters)) {\n return null;\n }\n const fields: Record<string, unknown> = {\n type: parsed.type,\n organizationId: parsed.organizationId,\n signWith: parsed.parameters.signWith,\n payload: parsed.parameters.payload,\n encoding: parsed.parameters.encoding,\n hashFunction: parsed.parameters.hashFunction,\n };\n const strings: Record<string, string> = {};\n for (const [key, value] of Object.entries(fields)) {\n if (typeof value !== \"string\") {\n return null;\n }\n strings[key] = value;\n }\n return strings;\n}\n\n/**\n * Whether two values are the same string, ignoring ASCII case (an address's checksum case, a hex payload's case).\n */\nfunction sameIgnoringCase(actual: unknown, expected: string): boolean {\n return typeof actual === \"string\" && actual.toLowerCase() === expected.toLowerCase();\n}\n\n/**\n * Whether a completed activity is the one that was signed: the same type (a raw-payload signature), organization,\n * address, payload, encoding and hash function. The address and the payload hex compare without case; everything\n * else compares exactly.\n */\nfunction activityMatchesSignedBody(activity: Record<string, unknown>, signedBody: unknown): boolean {\n const expected = readSignedBody(signedBody);\n if (expected === null || expected.type !== SIGN_RAW_PAYLOAD_TYPE) {\n return false;\n }\n const intent = isJsonObject(activity.intent) ? activity.intent.signRawPayloadIntentV2 : undefined;\n if (!isJsonObject(intent)) {\n return false;\n }\n return (\n activity.type === expected.type &&\n activity.organizationId === expected.organizationId &&\n sameIgnoringCase(intent.signWith, expected.signWith) &&\n sameIgnoringCase(intent.payload, expected.payload) &&\n intent.encoding === expected.encoding &&\n intent.hashFunction === expected.hashFunction\n );\n}\n\n/**\n * The relay's verdicts this decoder reads.\n */\nconst VERDICTS: ReadonlySet<unknown> = new Set([\"signed\", \"rejected\", \"partially_approved\", \"ambiguous\"]);\n\n/**\n * Decodes a relay's `200` or `202` answer into its outcome (guide §7.4). A `200` is not proof of a signature.\n *\n * A response that carries the key `verdict` (rc.55's `RelayResult`) is read by the relay's verdict first, before any\n * guess from the provider's bytes:\n *\n * - `ambiguous` → `unknown` with cause `ambiguous`, whatever the bytes hold: the request may have reached the\n * provider, so it is never a refusal.\n * - `partially_approved` → `cosignature`, with `activity_ref`.\n * - `rejected` → `refused`, with the error body's numeric `code` and string `message` when the bytes hold them, else\n * `providerCode: null` and `providerMessage: \"\"`.\n * - `signed` → steps 3 to 8 below, except that an error body (step 4) is `unknown` with cause `provider-error`,\n * never `refused`.\n * - any other value → `unknown` with cause `unreadable`.\n *\n * A response with no `verdict` (an older Coordinator) runs every step, and the first that matches wins:\n *\n * 1. `response` is not an object → `unknown` with cause `unreadable`.\n * 2. `root_activity` is a non-null object → `cosignature`.\n * 3. `provider_response` is `null`, `\"\"`, not standard base64 (`fromBase64`), not UTF-8 (`bytesToUtf8`), not JSON, or\n * not a JSON object → `unknown` with cause `unreadable`.\n * 4. The object has no `activity` key, or `activity` is not a JSON object: Turnkey's error body. Its `code` is one of\n * the client-error gRPC codes (3, 5, 6, 7, 8, 9, 11, 12, 16) → `refused`, with `providerCode` and\n * `providerMessage` (its `message` when a string, else `\"\"`). Any other code, or none → `unknown` with cause\n * `provider-error`, since SigningRouter reads a Turnkey `5xx` as ambiguous and an older Coordinator drops that\n * verdict.\n * 5. `activity.status !== \"ACTIVITY_STATUS_COMPLETED\"` → `unknown` with cause `status` and `activityStatus` (the\n * status when a string, else `null`).\n * 6. The activity is not the one in `signedBody`: its `type` is not `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2`, its\n * `organizationId` differs, or `intent.signRawPayloadIntentV2` is missing or differs in `signWith`, `payload` (both\n * without case), `encoding` or `hashFunction` → `unknown` with cause `mismatch`.\n * 7. `activity.result.signRawPayloadResult` has `r` and `s` of 64 hex digits and `v` exactly `\"00\"` or `\"01\"` →\n * `signed`, with `r` and `s` lowercased. Any other `v` (`\"1b\"`, `\"02\"`, `\"0\"`, a number) is refused here: the hub\n * can only build an EVM signature from those two recovery ids.\n * 8. Otherwise → `unknown` with cause `unreadable`.\n *\n * `activityRef` is `response.activity_ref` when it is a string, else `\"\"`; `activityStatus` is `null` except in step\n * 5. Does not recover the signer from the signature: the caller still checks it against the wallet's address. Pure;\n * never throws.\n *\n * Vectors (§12.7): with the §12.7 body as `signedBody`, the \"Response `200`\" body is `signed` with r\n * `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `00` and activityRef `01a0e31a-743d-7894-9edc-e00e87805a51`; the\n * \"waiting for a second approval\" body is `cosignature` even though its decoded activity says `COMPLETED`.\n *\n * @param response The relay's `200` or `202` body.\n * @param signedBody The exact activity body string that was signed and relayed (`buildSignRawPayloadBody`'s result).\n */\nexport function decodeRelayResponse(response: RelayResponseDto, signedBody: string): RelayResult {\n if (!isJsonObject(response)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef: \"\", activityStatus: null };\n }\n\n const activityRef = typeof response.activity_ref === \"string\" ? response.activity_ref : \"\";\n const hasVerdict = Object.hasOwn(response, \"verdict\");\n const verdict: unknown = response.verdict;\n\n if (hasVerdict) {\n if (!VERDICTS.has(verdict)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n if (verdict === \"ambiguous\") {\n return { kind: \"unknown\", cause: \"ambiguous\", activityRef, activityStatus: null };\n }\n if (verdict === \"partially_approved\") {\n return { kind: \"cosignature\", activityRef };\n }\n if (verdict === \"rejected\") {\n const body = readProviderObject(response.provider_response);\n const code = body?.code;\n const message = body?.message;\n return {\n kind: \"refused\",\n activityRef,\n providerCode: typeof code === \"number\" ? code : null,\n providerMessage: typeof message === \"string\" ? message : \"\",\n };\n }\n } else {\n const rootActivity: unknown = response.root_activity;\n if (typeof rootActivity === \"object\" && rootActivity !== null) {\n return { kind: \"cosignature\", activityRef };\n }\n }\n\n const provider = readProviderObject(response.provider_response);\n if (provider === null) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n const activity = provider.activity;\n if (!isJsonObject(activity)) {\n const { code, message } = provider;\n if (hasVerdict || typeof code !== \"number\" || !REFUSAL_CODES.has(code)) {\n return { kind: \"unknown\", cause: \"provider-error\", activityRef, activityStatus: null };\n }\n return {\n kind: \"refused\",\n activityRef,\n providerCode: code,\n providerMessage: typeof message === \"string\" ? message : \"\",\n };\n }\n\n const status = activity.status;\n if (status !== \"ACTIVITY_STATUS_COMPLETED\") {\n return {\n kind: \"unknown\",\n cause: \"status\",\n activityRef,\n activityStatus: typeof status === \"string\" ? status : null,\n };\n }\n\n if (!activityMatchesSignedBody(activity, signedBody)) {\n return { kind: \"unknown\", cause: \"mismatch\", activityRef, activityStatus: null };\n }\n\n const result = activity.result;\n const signature = isJsonObject(result) ? result.signRawPayloadResult : undefined;\n if (!isJsonObject(signature)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n const { r, s, v } = signature;\n if (\n typeof r !== \"string\" ||\n typeof s !== \"string\" ||\n typeof v !== \"string\" ||\n !SCALAR_HEX_PATTERN.test(r) ||\n !SCALAR_HEX_PATTERN.test(s) ||\n !RECOVERY_IDS.has(v)\n ) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n return { kind: \"signed\", r: r.toLowerCase(), s: s.toLowerCase(), v, activityRef };\n}\n","import { isSuaError, isSuaNetworkError } from \"#/errors/guards\";\nimport type { RelayResponseDto } from \"#/models\";\n\nimport { decodeRelayResponse } from \"./decodeRelayResponse\";\n\nimport type { RelayResult } from \"./types\";\n\n/**\n * Sends a relay once and settles it into a {@link RelayResult}, folding in the outcomes that arrive as thrown errors.\n * Typical use: `settleRelay(() => client.relay(request), body)`, where `body` is the string that was signed.\n *\n * - `send` resolves → `decodeRelayResponse(response, signedBody)`.\n * - `send` rejects with a `SuaNetworkError` (`isSuaNetworkError`, so a copy from a second bundle counts) → `{ kind:\n * \"unknown\", cause: \"network\", activityRef: \"\", activityStatus: null }`.\n * - `send` rejects with a `SuaError` (`isSuaError`) whose `code` is `\"ambiguous\"` → `unknown` with cause\n * `ambiguous`.\n * - A `SuaError` with a `2xx` status (an unusable body: empty, not JSON, not an object, or a `204`) → `unknown` with\n * cause `unreadable`: the Coordinator answered success, so the request may have been signed.\n * - A `SuaError` with any status outside `4xx`, notably a `5xx` with or without the Coordinator's envelope → `unknown`\n * with cause `server`. A proxy in front of the Coordinator (nginx, Cloudflare, the hub proxy) can answer\n * `502`, `504` or `524` after the stamp was forwarded, and the Coordinator's own `500` can follow a provider call.\n * - Any other rejection is rethrown unchanged: a `4xx` `SuaError` (`401 CREDENTIAL_EXPIRED`, `409\n * WALLET_NOT_ACTIVE`, `429`, a proxy's `413`, …) is a refusal before anything reached the provider, and an abort is\n * the caller's.\n *\n * Calls `send` exactly once and never retries.\n *\n * @param send Sends the relay, typically `client.relay`.\n * @param signedBody The exact activity body string that was signed (`buildSignRawPayloadBody`'s result). A completed\n * activity that does not echo it settles as `unknown` with cause `mismatch`.\n */\nexport async function settleRelay(send: () => Promise<RelayResponseDto>, signedBody: string): Promise<RelayResult> {\n let response: RelayResponseDto;\n try {\n response = await send();\n } catch (error) {\n if (isSuaNetworkError(error)) {\n return { kind: \"unknown\", cause: \"network\", activityRef: \"\", activityStatus: null };\n }\n if (!isSuaError(error)) {\n throw error;\n }\n if (error.code === \"ambiguous\") {\n return { kind: \"unknown\", cause: \"ambiguous\", activityRef: \"\", activityStatus: null };\n }\n if (error.status >= 200 && error.status < 300) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef: \"\", activityStatus: null };\n }\n if (error.status < 400 || error.status >= 500) {\n return { kind: \"unknown\", cause: \"server\", activityRef: \"\", activityStatus: null };\n }\n throw error;\n }\n return decodeRelayResponse(response, signedBody);\n}\n","import { SCALAR_HEX_PATTERN, SECP256K1_ORDER } from \"./constants\";\n\n/**\n * The length of r or s as hex digits.\n */\nconst SCALAR_HEX_LENGTH = 64;\n\n/**\n * Half the secp256k1 order: an `s` above it is high.\n */\nconst HALF_ORDER = SECP256K1_ORDER / 2n;\n\n/**\n * What EVM adds to a recovery id to form `v` (27 or 28).\n */\nconst EVM_RECOVERY_OFFSET = 27;\n\n/**\n * Turns Turnkey's raw-payload result into the 65-byte EVM signature an app receives:\n * `0x` ‖ r ‖ s ‖ (27 + v), as 132 lowercase characters.\n *\n * 1. Refuses anything but `r` and `s` of exactly 64 hex digits (either case) and `v` exactly `\"00\"` or `\"01\"`.\n * 2. Low-s: when `BigInt(\"0x\" + s) > SECP256K1_ORDER / 2n`, replaces `s` with `SECP256K1_ORDER - s` (left-padded to 64\n * hex digits) and flips the recovery id (`0` ↔ `1`). A signature with `s` exactly `n / 2` or below is kept.\n * 3. Returns `\"0x\" + r.toLowerCase() + s.toLowerCase() + (27 + v).toString(16)`, so v is `1b` or `1c`.\n *\n * The caller recovers the signer from the **raw** `r`, `s`, `v` first and only then calls this; the output recovers to\n * the same address because flipping v compensates for negating s.\n *\n * Vectors:\n * - The guide's relay result (r `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `\"00\"`) has a low s, so the output is\n * `0x3f1c8a9e…0b2d4f6a5e2a7c9e…9b1d3f5a1b`.\n * - s = `SECP256K1_ORDER - 1` with v `\"00\"` becomes s = `…0001` (63 zeros, then `1`) with v `1c`.\n * - s = `SECP256K1_ORDER / 2n` exactly is not high: kept, v unchanged.\n *\n * @throws {TypeError} when `r`, `s` or `v` breaks rule 1.\n */\nexport function toEvmSignature(r: string, s: string, v: string): string {\n if (typeof r !== \"string\" || !SCALAR_HEX_PATTERN.test(r)) {\n throw new TypeError(\"toEvmSignature: r must be 64 hex digits\");\n }\n if (typeof s !== \"string\" || !SCALAR_HEX_PATTERN.test(s)) {\n throw new TypeError(\"toEvmSignature: s must be 64 hex digits\");\n }\n if (v !== \"00\" && v !== \"01\") {\n throw new TypeError('toEvmSignature: v must be \"00\" or \"01\"');\n }\n\n let sHex = s.toLowerCase();\n let recoveryId = v === \"01\" ? 1 : 0;\n const sValue = BigInt(`0x${sHex}`);\n if (sValue > HALF_ORDER) {\n sHex = (SECP256K1_ORDER - sValue).toString(16).padStart(SCALAR_HEX_LENGTH, \"0\");\n recoveryId = 1 - recoveryId;\n }\n\n return `0x${r.toLowerCase()}${sHex}${(EVM_RECOVERY_OFFSET + recoveryId).toString(16)}`;\n}\n","/**\n * How many recent samples the server clock keeps. Its offset is their median.\n */\nexport const SERVER_CLOCK_WINDOW = 5;\n\n/**\n * How close, in ms, the first two samples must agree before their offset is applied. One sample alone never moves\n * the offset.\n */\nexport const SERVER_CLOCK_AGREEMENT_MS = 2_000;\n\n/**\n * The longest round trip, in ms, a sample may have. A slower answer says too little about when the server wrote its\n * time, so it is discarded.\n */\nexport const SERVER_CLOCK_MAX_ROUND_TRIP_MS = 5_000;\n\n/**\n * The smallest offset, in ms, the server clock applies. `Date` has whole-second resolution, so a smaller offset is\n * noise and counts as 0.\n */\nexport const SERVER_CLOCK_MIN_OFFSET_MS = 1_000;\n","import {\n SERVER_CLOCK_AGREEMENT_MS,\n SERVER_CLOCK_MAX_ROUND_TRIP_MS,\n SERVER_CLOCK_MIN_OFFSET_MS,\n SERVER_CLOCK_WINDOW,\n} from \"./constants\";\n\nimport type { ServerClock, ServerClockOptions, ServerTimeSample } from \"./types\";\n\n/**\n * Whether a sample can be used: three finite times and a round trip from 0 to\n * {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} inclusive. A negative round trip means the device's clock moved during the\n * request.\n */\nfunction isUsableSample(sample: ServerTimeSample): boolean {\n const { serverTimeMs, sentAtMs, receivedAtMs } = sample;\n if (!Number.isFinite(serverTimeMs) || !Number.isFinite(sentAtMs) || !Number.isFinite(receivedAtMs)) {\n return false;\n }\n const roundTripMs = receivedAtMs - sentAtMs;\n return roundTripMs >= 0 && roundTripMs <= SERVER_CLOCK_MAX_ROUND_TRIP_MS;\n}\n\n/**\n * The middle value of a non-empty list; the mean of the two middle values when its length is even.\n */\nfunction median(values: readonly number[]): number {\n const sorted = [...values].sort((left, right) => left - right);\n const middle = Math.floor(sorted.length / 2);\n if (sorted.length % 2 === 1) {\n return sorted[middle] ?? 0;\n }\n return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;\n}\n\n/**\n * The offset the window yields: `0` with fewer than two samples, and with exactly two that differ by more than\n * {@link SERVER_CLOCK_AGREEMENT_MS}; otherwise their median, rounded to a whole ms, and `0` when that is smaller in\n * size than {@link SERVER_CLOCK_MIN_OFFSET_MS}.\n */\nfunction resolveOffset(offsets: readonly number[]): number {\n if (offsets.length < 2) {\n return 0;\n }\n const [first = 0, second = 0] = offsets;\n if (offsets.length === 2 && Math.abs(first - second) > SERVER_CLOCK_AGREEMENT_MS) {\n return 0;\n }\n const offset = Math.round(median(offsets));\n return Math.abs(offset) < SERVER_CLOCK_MIN_OFFSET_MS ? 0 : offset;\n}\n\n/**\n * Creates a {@link ServerClock}: the device's clock corrected by its offset from the server's, learnt from the\n * samples passed to `record` (the Coordinator client's `onServerTime`).\n *\n * - **A sample's offset** is `serverTimeMs` minus the midpoint of `sentAtMs` and `receivedAtMs`.\n * - **Discarded samples.** One with a non-finite time, a negative round trip, or a round trip longer than\n * {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} (too uncertain) is ignored.\n * - **The offset** is the median of the last {@link SERVER_CLOCK_WINDOW} kept samples. One sample alone never moves\n * it; two move it only when they agree within {@link SERVER_CLOCK_AGREEMENT_MS}; from three on, the median ignores a\n * lone outlier.\n * - **The floor.** An offset smaller in size than {@link SERVER_CLOCK_MIN_OFFSET_MS} counts as 0, since `Date` has\n * whole-second resolution.\n * - **Memory only.** Nothing is stored: a new clock (a reload) starts again at 0.\n *\n * Durations (sleeps, timeouts, polling intervals, the sign confirm's dwell) stay on the device's clock; this clock is\n * only for comparing the device's time with a time the server wrote.\n */\nexport function createServerClock(options: ServerClockOptions = {}): ServerClock {\n const deviceClock = options.deviceClock ?? Date.now;\n const offsets: number[] = [];\n let offsetMs = 0;\n\n return {\n now: () => deviceClock() + offsetMs,\n offsetMs: () => offsetMs,\n record(sample) {\n if (!isUsableSample(sample)) {\n return;\n }\n offsets.push(sample.serverTimeMs - (sample.sentAtMs + sample.receivedAtMs) / 2);\n if (offsets.length > SERVER_CLOCK_WINDOW) {\n offsets.shift();\n }\n offsetMs = resolveOffset(offsets);\n },\n };\n}\n"],"mappings":";;;;;AAGA,MAAa,oBAAoB;;;;AAKjC,MAAa,iBAAiB;;;;AAK9B,MAAa,mBAAsC,CAAC,mBAAmB,cAAc;;;;AAKrF,MAAa,cAAc;;;;;;;;AAS3B,MAAa,aAAa;;;;;;AAO1B,MAAa,qBAAqB;;;;AAKlC,MAAa,6BAA6B;;;;AAK1C,MAAa,uBAAuB;;;;;AAMpC,MAAa,wBAAwB;;;;;AAMrC,MAAa,uBAAuB;;;;;AAMpC,MAAa,kCAAkC;;;;;AAM/C,MAAa,+BAA+B;;;;;;AAO5C,MAAa,kBAAkB;;;;;AAM/B,MAAa,2BAA2B;;;;;AAMxC,MAAa,0BAA0B;;;;;;;;;;;;AC5EvC,IAAa,iBAAb,MAAa,uBAAuB,MAAM;;;;CAItC;;;;CAKA;;;;CAKA,YAAY,QAAgC,OAAgB;EACxD,MAAM,oCAAoC;EAC1C,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,OAAO,eAAe,MAAM,eAAe,SAAS;CACxD;AACJ;;;;;;;AC5BA,SAAgB,aAAa,OAAkD;CAC3E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;;;;;;;;;;;;;;;;;;;;;;;ACiEA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;;;CAIhC;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;;CAMA,YAAY,MAAoB;EAC5B,MAAM,wBAAwB,KAAK,OAAO,GAAG,KAAK,OAAO,KAAK,SA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AOA,SAAS,cAAc,SAAoC;CACvD,IAAI,QAAQ,SAAS,GACjB,OAAO;CAEX,MAAM,CAAC,QAAQ,GAAG,SAAS,KAAK;CAChC,IAAI,QAAQ,WAAW,KAAK,KAAK,IAAI,QAAQ,MAAM,IAAA,KAC/C,OAAO;CAEX,MAAM,SAAS,KAAK,MAAM,OAAO,OAAO,CAAC;CACzC,OAAO,KAAK,IAAI,MAAM,IAAA,MAAiC,IAAI;AAC/D;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,kBAAkB,UAA8B,CAAC,GAAgB;CAC7E,MAAM,cAAc,QAAQ,eAAe,KAAK;CAChD,MAAM,UAAoB,CAAC;CAC3B,IAAI,WAAW;CAEf,OAAO;EACH,WAAW,YAAY,IAAI;EAC3B,gBAAgB;EAChB,OAAO,QAAQ;GACX,IAAI,CAAC,eAAe,MAAM,GACtB;GAEJ,QAAQ,KAAK,OAAO,gBAAgB,OAAO,WAAW,OAAO,gBAAgB,CAAC;GAC9E,IAAI,QAAQ,SAAA,GACR,QAAQ,MAAM;GAElB,WAAW,cAAc,OAAO;EACpC;CACJ;AACJ"}
|
|
1
|
+
{"version":3,"file":"coordinator.js","names":["value","COMPRESSED_PUBLIC_KEY_HEX","defaultSleep","sleep","defaultSleep","sleep"],"sources":["../../../src/client/constants.ts","../../../src/errors/CsrfStoreError.ts","../../../src/shared/isJsonObject.ts","../../../src/errors/SuaError.ts","../../../src/errors/SuaNetworkError.ts","../../../src/errors/guards.ts","../../../src/errors/json.ts","../../../src/errors/SuaReason.ts","../../../src/errors/parseSuaError.ts","../../../src/models/Route/entities/RouteStateDto.ts","../../../src/client/endpoints.ts","../../../src/models/PayIn/entities/PayInDripDto.ts","../../../src/models/PayIn/entities/PayInLegStateDto.ts","../../../src/models/PayIn/entities/PayInMechanismDto.ts","../../../src/models/PayIn/entities/PayInPhaseDto.ts","../../../src/models/PayIn/entities/PayInShapeDto.ts","../../../src/models/PayIn/entities/PayInStateDto.ts","../../../src/models/PayIn/entities/PayInStepSchemeDto.ts","../../../src/models/PayIn/entities/PayInStepStatusDto.ts","../../../src/models/PayIn/entities/PayInUnspendableDto.ts","../../../src/models/Route/entities/RouteStepRoleDto.ts","../../../src/payIn/constants.ts","../../../src/payIn/caip.ts","../../../src/shared/patterns.ts","../../../src/client/guards.ts","../../../src/client/serverTime.ts","../../../src/client/createCoordinatorClient.ts","../../../src/encoding/base64.ts","../../../src/encoding/hex.ts","../../../src/crypto/der.ts","../../../src/crypto/subtle.ts","../../../src/crypto/types.ts","../../../src/crypto/sign.ts","../../../src/crypto/credential.ts","../../../src/crypto/keypair.ts","../../../src/crypto/stamp.ts","../../../src/crypto/relayRequest.ts","../../../src/payIn/units.ts","../../../src/payIn/steps.ts","../../../src/polling/sleep.ts","../../../src/polling/waitForActiveWallet.ts","../../../src/polling/waitForRound.ts","../../../src/relay/buildSignRawPayloadBody.ts","../../../src/relay/constants.ts","../../../src/relay/buildPersonalSignBody.ts","../../../src/relay/decodeRelayResponse.ts","../../../src/relay/settleRelay.ts","../../../src/relay/toEvmSignature.ts","../../../src/time/constants.ts","../../../src/time/createServerClock.ts"],"sourcesContent":["/**\n * The path prefix of the sign-in routes and every route that needs a session.\n */\nexport const WALLET_API_PREFIX = \"/wallet/v1\";\n\n/**\n * The path prefix of the guest routes: the guest, its saved accounts and its checkout.\n */\nexport const PAY_API_PREFIX = \"/pay/v1\";\n\n/**\n * Every path prefix the client calls under `baseUrl`, and so every prefix a hub proxy forwards.\n */\nexport const HUB_API_PREFIXES: readonly string[] = [WALLET_API_PREFIX, PAY_API_PREFIX];\n\n/**\n * The CSRF double-submit header. Sent with the stored `csrf_token` on every `POST`, `PUT` and `DELETE`.\n */\nexport const CSRF_HEADER = \"X-CSRF-Token\";\n\n/**\n * The app attribution header. Sent with the client's `appId` on `POST /wallet/v1/credentials/session`, `GET\n * /wallet/v1/account` and `POST /wallet/v1/relay` (the routes that require it, `internal/hub/router.go`), on the linked\n * wallet routes (`POST /wallet/v1/external-accounts`, `PATCH /wallet/v1/external-accounts/{id}`), on every\n * `/wallet/v1/routes` route, on the guest routes, on the wallet offer answer and on every pay-in route. Attribution is\n * never authority: the Coordinator does not check it against `Origin`.\n */\nexport const APP_HEADER = \"X-Stridge-App\";\n\n/**\n * The idempotency header, required on route open and pay-in confirm. Repeating an open key returns its first route.\n * Repeating a confirm key with the same body returns its pay-in; a different body is IDEMPOTENCY_KEY_REUSED.\n * The Coordinator scopes the key to the identity.\n */\nexport const IDEMPOTENCY_HEADER = \"Idempotency-Key\";\n\n/**\n * The longest `Idempotency-Key` the Coordinator takes, in characters.\n */\nexport const MAX_IDEMPOTENCY_KEY_LENGTH = 128;\n\n/**\n * The most routes one `GET /wallet/v1/routes` answer holds, and the largest `limit` the client sends.\n */\nexport const MAX_ROUTE_LIST_LIMIT = 100;\n\n/**\n * The CAIP-2 chain every route leaves from, Tempo (the Coordinator's `routing/domain.SourceChain`): the only\n * `chain_id` a route step may name. A route answer with a step on any other chain is unusable.\n */\nexport const ROUTE_SOURCE_CHAIN_ID = \"eip155:4217\";\n\n/**\n * The response header the hub proxy repeats the Coordinator's `Date` in, so the client can read the Coordinator's\n * clock even where the hosting platform rewrites `Date` with its own. The client reads it before `Date`.\n */\nexport const UPSTREAM_DATE_HEADER = \"X-Stridge-Upstream-Date\";\n\n/**\n * The longest `name` a pay-in quote's `wallet` descriptor takes, in characters (pay-in guide §4.2); a longer one is\n * `400 WALLET_MALFORMED`. The client sends the name as given, so cut it to this length first.\n */\nexport const MAX_EXTERNAL_WALLET_NAME_LENGTH = 64;\n\n/**\n * The most chains a pay-in quote's `wallet.capabilities` names (pay-in guide §4.2); more is `400 WALLET_MALFORMED`.\n * The client sends the chains as given.\n */\nexport const MAX_WALLET_CAPABILITY_CHAINS = 64;\n\n/**\n * The canonical Permit2 contract, at the same address on every EVM chain: the only spender a pay-in's approvals name,\n * whether the wallet sends one (K7) or signs one (K3 to K5), and the verifying contract of a Permit2 transfer (K2).\n * Never a Stridge contract.\n */\nexport const PERMIT2_ADDRESS = \"0x000000000022D473030F116dDEE9F6B43aC78BA3\";\n\n/**\n * Relay's depository, at the same address on every EVM chain it serves: the only `to` of a coin send (mechanism `W`),\n * which deposits the wallet's native coin there through `depositNative`. Never a Stridge contract.\n */\nexport const RELAY_DEPOSITORY_ADDRESS = \"0x4cD00E387622C35bDDB9b4c962C136462338BC31\";\n\n/**\n * The selector of Relay's `depositNative(address depositor, bytes32 id)`, lowercase with its `0x`: the call of every\n * coin send.\n */\nexport const DEPOSIT_NATIVE_SELECTOR = \"0x49290c1c\";\n","import type { VerifyRoundResponseDto } from \"#/models\";\n\n/**\n * The verify succeeded but `csrf.set` threw or rejected (for example `sessionStorage` refusing a write with\n * `QuotaExceededError` or `SecurityError`). Thrown by `CoordinatorClient.verifyRound` in that case.\n *\n * The session is already open: the Coordinator set its cookie in the same answer, and no route re-issues the token.\n * So the answer is never discarded. `answer` holds it in full, `csrf_token` and `credential` included: keep the token\n * (retry the store, or hold it in memory) and carry on with the credential, or the session stays locked until its\n * absolute expiry.\n */\nexport class CsrfStoreError extends Error {\n /**\n * The verify answer, unchanged.\n */\n readonly answer: VerifyRoundResponseDto;\n\n /**\n * The value `csrf.set` threw or rejected with.\n */\n readonly cause: unknown;\n\n /**\n * Wraps the store failure. The message is always `The csrf_token could not be stored`.\n */\n constructor(answer: VerifyRoundResponseDto, cause: unknown) {\n super(\"The csrf_token could not be stored\");\n this.name = \"CsrfStoreError\";\n this.answer = answer;\n this.cause = cause;\n Object.setPrototypeOf(this, CsrfStoreError.prototype);\n }\n}\n","/**\n * Reports whether `value` is a non-null, non-array object: the shape a parsed JSON object has. Unlike the protocol\n * guards' stricter check, class instances pass. Internal: not exported from the package index.\n */\nexport function isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import type { ErrorKindDto } from \"#/models\";\n\nimport type { SuaReason } from \"./SuaReason\";\n\n/**\n * A `SuaError`'s kind: the Coordinator's envelope `error.type`, including `ambiguous` (the relay's `202`). A failure\n * response with no readable envelope (a proxy's HTML page, an empty body) is `internal`.\n */\nexport type SuaErrorKind = ErrorKindDto;\n\n/**\n * The fields a {@link SuaError} is built from.\n */\nexport interface SuaErrorInit {\n /**\n * The HTTP status the Coordinator answered (for example `401`, or `202` for an ambiguous relay).\n */\n status: number;\n\n /**\n * The envelope's kind.\n */\n code: SuaErrorKind;\n\n /**\n * The envelope's stable code (`error.code`), normalised onto the closed {@link SuaReason} set.\n */\n reason: SuaReason;\n\n /**\n * Whole seconds to wait, from a `Retry-After` header. `undefined` when the response carried none.\n */\n retryAfterSeconds?: number;\n\n /**\n * The envelope's `request_id` (`req_…`), when it carried one.\n */\n requestId?: string;\n\n /**\n * The envelope's `param`, the request field the refusal is about, when it named one.\n */\n param?: string;\n\n /**\n * The response body: the parsed JSON when it parsed, the raw text otherwise, `undefined` when empty. For logs and\n * diagnostics only; branch on `status`, `code` and `reason`.\n */\n body?: unknown;\n}\n\n/**\n * A request got an HTTP answer that is not a usable success. Thrown by every `CoordinatorClient` method for any\n * response whose body is the error envelope, for any non-2xx response, and for a `2xx` whose body is unusable (empty,\n * not JSON, not an object, or an unexpected `204`), which has code `internal` and its `2xx` status.\n *\n * With the envelope it is the Coordinator's own answer: a refusal, or an outcome it could not assert (`code:\n * \"ambiguous\"`). Without one (`body` is not an `ErrorEnvelopeDto`) it most likely came from a hop in front of the\n * Coordinator, a proxy's `502` for example, and says nothing about whether the request reached it. `settleRelay`\n * reads a relay's `2xx` and `5xx` as unknown for that reason.\n *\n * Client transitions key on `status` plus `reason` (guide §11); `code` is the coarser kind. The fields map from the\n * envelope (`toSuaError`) as follows; the SDK keeps its own names, so `code` here is not the envelope's `code`:\n *\n * | `SuaError` | Envelope | Example |\n * |---|---|---|\n * | `code` | `error.type` | `\"rejected\"` |\n * | `reason` | `error.code`, when it is a published code; `\"\"` for a bare kind | `\"SESSION_EXPIRED\"` |\n * | `requestId` | `error.request_id` | `\"req_01J8Z…\"` |\n * | `param` | `error.param` | `\"limit\"` |\n */\nexport class SuaError extends Error {\n /**\n * The HTTP status.\n */\n readonly status: number;\n\n /**\n * The envelope's kind.\n */\n readonly code: SuaErrorKind;\n\n /**\n * The envelope's stable code (`error.code`), or `\"\"`.\n */\n readonly reason: SuaReason;\n\n /**\n * Whole seconds from `Retry-After`, when the response carried one (every rate-limit `429` does).\n */\n readonly retryAfterSeconds: number | undefined;\n\n /**\n * The Coordinator's id for the request (`req_…`), when the envelope carried one. Quote it in bug reports.\n */\n readonly requestId: string | undefined;\n\n /**\n * The request field the refusal is about, when the envelope named one.\n */\n readonly param: string | undefined;\n\n /**\n * The response body, for diagnostics.\n */\n readonly body: unknown;\n\n /**\n * Builds the error. The message reads `Coordinator answered <status> <code>`, followed by ` (<reason>)` when the\n * reason is not empty.\n */\n constructor(init: SuaErrorInit) {\n super(`Coordinator answered ${init.status} ${init.code}${init.reason ? ` (${init.reason})` : \"\"}`);\n this.name = \"SuaError\";\n this.status = init.status;\n this.code = init.code;\n this.reason = init.reason;\n this.retryAfterSeconds = init.retryAfterSeconds;\n this.requestId = init.requestId;\n this.param = init.param;\n this.body = init.body;\n Object.setPrototypeOf(this, SuaError.prototype);\n }\n}\n","/**\n * The request got no HTTP answer: `fetch` rejected for a reason other than the caller's abort (DNS, TLS, a dropped\n * connection, a CORS refusal). Thrown by every `CoordinatorClient` method in that case.\n *\n * On a state-changing call the request may still have reached the Coordinator, so the outcome is unknown: never\n * re-send a registration or a relay automatically. `settleRelay` reads it as an unknown outcome.\n */\nexport class SuaNetworkError extends Error {\n /**\n * The value `fetch` rejected with.\n */\n readonly cause: unknown;\n\n /**\n * Wraps the rejection. The message is always `Network request failed`.\n */\n constructor(cause: unknown) {\n super(\"Network request failed\");\n this.name = \"SuaNetworkError\";\n this.cause = cause;\n Object.setPrototypeOf(this, SuaNetworkError.prototype);\n }\n}\n","import type { ErrorEnvelopeDto } from \"#/models\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\n\nimport { CsrfStoreError } from \"./CsrfStoreError\";\nimport { SuaError } from \"./SuaError\";\nimport { SuaNetworkError } from \"./SuaNetworkError\";\n\nimport type { SuaReason } from \"./SuaReason\";\n\n/**\n * Reports whether `value` is shaped like the Coordinator's error envelope: a non-null, non-array object whose `error`\n * is a non-null, non-array object with a string `code`. Neither the value of `code` nor `type` (of any type, or\n * absent) is checked here: `toSuaError` normalises both, so a malformed kind still reads as a refusal rather than as\n * a success body. Extra keys are allowed.\n *\n * This is how the client tells an error body from a success body on a `2xx` (the relay's `202` is an envelope; the\n * round's `202` and the registration's `202` are not).\n */\nexport function isErrorEnvelopeDto(value: unknown): value is ErrorEnvelopeDto {\n if (!isJsonObject(value)) {\n return false;\n }\n\n const error = value.error;\n\n return isJsonObject(error) && typeof error.code === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link SuaError}, optionally with a given reason.\n *\n * True when `value instanceof SuaError`, or, for a copy of the class from a second bundle, when it is an `Error`\n * whose `name` is `\"SuaError\"` and which has a numeric `status` and string `code` and `reason`. With `reason`\n * given, the error's `reason` must also equal it (`isSuaError(error, \"CREDENTIAL_EXPIRED\")`).\n */\nexport function isSuaError(value: unknown, reason?: SuaReason): value is SuaError {\n if (!(value instanceof SuaError) && !isSuaErrorCopy(value)) {\n return false;\n }\n\n return reason === undefined || value.reason === reason;\n}\n\n/**\n * Reports whether `value` is a {@link SuaNetworkError}: `instanceof`, or an `Error` whose `name` is\n * `\"SuaNetworkError\"`.\n */\nexport function isSuaNetworkError(value: unknown): value is SuaNetworkError {\n return value instanceof SuaNetworkError || (value instanceof Error && value.name === \"SuaNetworkError\");\n}\n\n/**\n * Reports whether `value` is a {@link CsrfStoreError}: `instanceof`, or an `Error` whose `name` is `\"CsrfStoreError\"`\n * and which carries an `answer` object.\n */\nexport function isCsrfStoreError(value: unknown): value is CsrfStoreError {\n if (value instanceof CsrfStoreError) {\n return true;\n }\n\n return (\n value instanceof Error && value.name === \"CsrfStoreError\" && isJsonObject((value as Error & { answer?: unknown }).answer)\n );\n}\n\n/**\n * The duck-typed half of {@link isSuaError}: a `SuaError` built by another copy of the class.\n */\nfunction isSuaErrorCopy(value: unknown): value is SuaError {\n if (!(value instanceof Error) || value.name !== \"SuaError\") {\n return false;\n }\n\n const fields = value as Error & Record<string, unknown>;\n\n return typeof fields.status === \"number\" && typeof fields.code === \"string\" && typeof fields.reason === \"string\";\n}\n","/**\n * A response body read as text and parsed once: `empty` for `\"\"`, `json` when it parsed, `text` when it did not.\n */\nexport type ParsedBody = { kind: \"empty\" } | { kind: \"json\"; value: unknown } | { kind: \"text\"; text: string };\n\n/**\n * Parses a response body read as text. Never throws.\n */\nexport function parseBody(text: string): ParsedBody {\n if (text === \"\") {\n return { kind: \"empty\" };\n }\n\n try {\n return { kind: \"json\", value: JSON.parse(text) as unknown };\n } catch {\n return { kind: \"text\", text };\n }\n}\n","/**\n * Every reason code a hub API route the client calls can name, as the Coordinator's `pkg/errs` code list publishes them\n * (guide §11 lists most of them). `\"\"` is the refusal that names no reason.\n */\nexport const SUA_REASONS = [\n \"SESSION_MISSING\",\n \"CHECKOUT_RULE_NOT_FOUND\",\n \"SESSION_EXPIRED\",\n \"SESSION_REVOKED\",\n \"CREDENTIAL_EXPIRED\",\n \"APP_SUSPENDED\",\n \"ROUND_NOT_YOURS\",\n \"INVALID_CHALLENGE_CODE\",\n \"CHALLENGE_EXHAUSTED\",\n \"WALLET_NOT_ACTIVE\",\n \"PROVIDER_DRAINING\",\n \"ACCOUNT_EJECTED\",\n \"LOGIN_NOT_PERMITTED\",\n \"IDEMPOTENCY_KEY_MISSING\",\n \"IDEMPOTENCY_KEY_REUSED\",\n \"ASSET_NOT_LISTED\",\n \"AMOUNT_MALFORMED\",\n \"DESTINATION_MALFORMED\",\n \"DESTINATION_REQUIRED\",\n \"ROUTING_UNAVAILABLE\",\n \"ROUTE_NOT_OFFERED\",\n \"ROUTE_UNAVAILABLE\",\n \"ROUTE_NOT_FOUND\",\n \"ROUTE_SOURCE_ALREADY_REPORTED\",\n \"ROUTE_TX_CLAIMED\",\n \"ROUTE_NOT_REPORTABLE\",\n \"ROUTE_TX_MISMATCH\",\n \"PAYMENT_IN_FLIGHT\",\n \"INVALID_ADDRESS\",\n \"WALLET_MALFORMED\",\n \"WALLET_WOUND_DOWN\",\n \"AMOUNT_BELOW_MINIMUM\",\n \"INSUFFICIENT_ROUTABLE_BALANCE\",\n \"QUOTE_EXPIRED\",\n \"BALANCES_STALE\",\n \"ROUTE_STATE_CONFLICT\",\n \"ROUTE_BUSY\",\n \"SIGNATURE_BATCH_INVALID\",\n \"INTERNAL\",\n \"WALLET_BRAND_UNKNOWN\",\n \"WALLET_BRAND_MISMATCH\",\n \"EXTERNAL_ACCOUNT_LIMIT\",\n \"EXTERNAL_ACCOUNT_REMOVED\",\n \"RATE_LIMITED\",\n \"APP_NOT_FOUND\",\n \"GUEST_UNKNOWN\",\n \"GUEST_HANDOFF_INVALID\",\n \"GUEST_ALREADY_MERGED\",\n \"GUEST_OFFER_CHANGED\",\n \"\",\n] as const;\n\n/**\n * A refusal's reason, closed over {@link SUA_REASONS}. Any other string the Coordinator sends is read as `\"\"`; the raw\n * envelope stays on `SuaError.body`.\n *\n * What each one means for the client:\n *\n * - `SESSION_EXPIRED` (401) — no or expired session, **or** a missing or wrong `X-CSRF-Token`. If `GET\n * /wallet/v1/session` then answers `200`, the `csrf_token` is lost (\"session locked\"); otherwise there is no session.\n * - `SESSION_REVOKED` (401) — signed out elsewhere: clear the keypair and the token.\n * - `CREDENTIAL_EXPIRED` (401, relay only) — the keypair lapsed (expiry ≤ now + 5 s): renew, then re-confirm and\n * re-sign with a new `signedAtMs`.\n * - `APP_SUSPENDED` (403) — the `app_id` is unknown, malformed or inactive: a configuration error, never retried.\n * - `ROUND_NOT_YOURS` (403) — a renewal round verified without its session or `csrf_token`: the token is lost.\n * - `INVALID_CHALLENGE_CODE` (400) — a wrong code (the round survives, retype), or an unknown, expired or spent\n * round (on registration: start a new round).\n * - `CHALLENGE_EXHAUSTED` (429) — five wrong codes: the round is burned, start again.\n * - `WALLET_NOT_ACTIVE` (409) — the wallet is still provisioning: poll `GET /wallet/v1/account`, then retry (a\n * registration before the credential's `expires_at`, a route open under the same key).\n * - `PROVIDER_DRAINING` (409) and `ACCOUNT_EJECTED` (403) — SigningRouter state: show an error.\n * - `RATE_LIMITED` (429, verify and relay only) — Stridge's provider budget is spent; read `Retry-After`. The hub's own\n * rate limits stay reasonless (`\"\"`).\n * - `APP_NOT_FOUND` (404) — `GET /wallet/v1/apps/{id}` names no app.\n * - `\"\"` — any refusal without a published reason. Notably a rate-limit `429` (read `Retry-After`), a `403` from\n * SigningRouter's own rate limit or an enclave refusal (new round after backoff), a `500`, and the relay's `202`\n * ambiguous answer.\n *\n * Pay-ins also name `WALLET_MALFORMED`, `INSUFFICIENT_ROUTABLE_BALANCE`, `QUOTE_EXPIRED`,\n * `BALANCES_STALE`, `ROUTE_STATE_CONFLICT`, `ROUTE_BUSY` and `SIGNATURE_BATCH_INVALID`.\n * `AMOUNT_BELOW_MINIMUM` (422, smart-route quote) means the request is too small for these sources.\n * `error.minimum_amount`, when present, is the threshold in requested-asset base units.\n * `DESTINATION_REQUIRED` (400) is a guest quote sent without `destination`: a guest only checks out, so it is a client\n * bug, never retried.\n * `WALLET_WOUND_DOWN` is permanent, never a wallet-provisioning retry. A reasonless `500` retains its\n * HTTP status and never proves a confirm or adjust did nothing.\n *\n * The route reasons (`/wallet/v1/routes`, `pkg/errs/codes.go`):\n *\n * - `IDEMPOTENCY_KEY_MISSING` (400, open and pay-in confirm) — no `Idempotency-Key` arrived. The client never sends either without\n * one, so a proxy dropped the header: a configuration error.\n * - `IDEMPOTENCY_KEY_REUSED` (409) — on an open, core holds the key for another account. On a pay-in confirm, the key\n * names another body. Retry only with the same body and key; use a new key only for a new quote.\n * - `ASSET_NOT_LISTED` (400) — the source or destination asset is not in the token registry.\n * - `AMOUNT_MALFORMED` (400) — the amount is not a canonical positive decimal string of base units.\n * - `DESTINATION_MALFORMED` (400) — `destination.address` is not an EVM address.\n * - `ROUTING_UNAVAILABLE` (409) — core's routing is unreachable or failing (transient: retry later, an open under the\n * same key), or the app has no routing tenant in core (a configuration error).\n * - `ROUTE_NOT_OFFERED` (422) — the pair is never routed: the source is not on Tempo or the destination is not on an\n * EVM chain.\n * - `ROUTE_UNAVAILABLE` (422) — no provider routes this pair or amount right now: offer another destination or amount.\n * - `ROUTE_NOT_FOUND` (404) — no such route, or another account's.\n * - `ROUTE_SOURCE_ALREADY_REPORTED` (409) — the route already has a different source transaction.\n * - `ROUTE_TX_CLAIMED` (409) — the transaction is already another route's source.\n * - `ROUTE_NOT_REPORTABLE` (409) — the route's state no longer takes a source report.\n * - `ROUTE_TX_MISMATCH` (422) — the chain shows the transaction from another wallet or to another contract.\n * - `PAYMENT_IN_FLIGHT` (409, a route open and a pay-in quote or confirm) — another route of the tenant for the same\n * `payment_ref` may still move funds: follow that payment, never pay again.\n *\n * The external wallet and guest reasons (`pkg/errs/codes.go`):\n *\n * - `INVALID_ADDRESS` (400) — the address is not valid for its `chain_kind`.\n * - `WALLET_BRAND_UNKNOWN` (400) — the brand slug is not in the registry.\n * - `WALLET_BRAND_MISMATCH` (400) — the brand does not support the connector or the chain kind.\n * - `EXTERNAL_ACCOUNT_LIMIT` (409) — the account or the guest already keeps 20 wallets, or the wallets a wallet offer\n * answer accepts do not fit in the account (nothing changed).\n * - `EXTERNAL_ACCOUNT_REMOVED` (409) — the address was removed and stays removed unless the user explicitly saves it\n * again with `reconnect: true`.\n * - `GUEST_OFFER_CHANGED` (409, the wallet offer answer only) — the offer holds a wallet the answer's `shown` does not\n * name: nothing changed; read the session and ask again.\n * - `GUEST_UNKNOWN` (401, guest routes only) — the guest cookie names no live guest, or the guest token is missing or\n * wrong. Never a session refusal: it says nothing about the session.\n * - `GUEST_HANDOFF_INVALID` (400) and `GUEST_ALREADY_MERGED` (409) — the handoff and merge routes, which the hub does\n * not call.\n */\nexport type SuaReason = (typeof SUA_REASONS)[number];\n","import type { ErrorBodyDto, ErrorKindDto } from \"#/models\";\n\nimport { isErrorEnvelopeDto } from \"./guards\";\nimport { parseBody } from \"./json\";\nimport { SuaError, type SuaErrorKind } from \"./SuaError\";\nimport { SUA_REASONS, type SuaReason } from \"./SuaReason\";\n\n/**\n * A failure response whose body has already been read, for {@link toSuaError}. The client reads each body once, so\n * it hands the parts over rather than the `Response`.\n */\nexport interface SuaErrorResponse {\n /**\n * The HTTP status.\n */\n status: number;\n\n /**\n * The raw `Retry-After` header value, or `null` when absent.\n */\n retryAfter: string | null;\n\n /**\n * The raw body text, `\"\"` when empty.\n */\n body: string;\n}\n\n/**\n * The six envelope kinds the Coordinator names (`pkg/errs/errs.go`).\n */\nconst ERROR_KINDS: readonly ErrorKindDto[] = [\"invalid\", \"not_found\", \"conflict\", \"rejected\", \"ambiguous\", \"internal\"];\n\n/**\n * The obsolete asctime HTTP-date form (`Sun Nov 6 08:49:37 1994`), RFC 9110 §5.6.7.\n */\nconst ASCTIME_DATE = /^[A-Za-z]{3} [A-Za-z]{3} [ \\d]\\d \\d{2}:\\d{2}:\\d{2} \\d{4}$/;\n\n/**\n * Builds a {@link SuaError} from a failure response that was already read.\n *\n * 1. `body` is parsed as JSON when it is not empty; a parse failure keeps the raw text.\n * 2. When the parsed value is an error envelope (`isErrorEnvelopeDto`):\n * - `code` is `error.type` when it is one of the six `ErrorKindDto` values, and `\"internal\"` otherwise;\n * - `reason` is `error.code` when it is one of `SUA_REASONS`, and `\"\"` otherwise (the bare kind a refusal with no\n * stable code carries, such as a rate-limit `429`'s `\"rejected\"`, or a code the SDK does not list);\n * - `requestId` is `error.request_id` and `param` is `error.param`, each when it is a non-empty string.\n * 3. Otherwise (no envelope: empty body, HTML, another JSON shape) `code` is `\"internal\"` and `reason` is `\"\"`,\n * whatever the status.\n * 4. `retryAfterSeconds` is `parseRetryAfter(retryAfter)`.\n * 5. `SuaError.body` is the parsed JSON, else the raw text, else `undefined` for an empty body.\n *\n * Never throws.\n */\nexport function toSuaError(response: SuaErrorResponse): SuaError {\n const parsed = parseBody(response.body);\n let code: SuaErrorKind = \"internal\";\n let reason: SuaReason = \"\";\n let requestId: string | undefined;\n let param: string | undefined;\n let body: unknown;\n\n if (parsed.kind === \"json\") {\n body = parsed.value;\n if (isErrorEnvelopeDto(parsed.value)) {\n const error: Partial<Record<keyof ErrorBodyDto, unknown>> = parsed.value.error;\n code = toErrorKind(error.type);\n reason = toReason(error.code);\n requestId = toNonEmptyString(error.request_id);\n param = toNonEmptyString(error.param);\n }\n } else if (parsed.kind === \"text\") {\n body = parsed.text;\n }\n\n return new SuaError({\n status: response.status,\n code,\n reason,\n retryAfterSeconds: parseRetryAfter(response.retryAfter),\n requestId,\n param,\n body,\n });\n}\n\n/**\n * Reads a failure `Response` into a {@link SuaError}: reads `response.text()` once (a read failure counts as an empty\n * body), takes `Retry-After` from `response.headers`, and delegates to {@link toSuaError}.\n *\n * Consumes the body. Never rejects.\n */\nexport async function parseSuaError(response: Response): Promise<SuaError> {\n let body = \"\";\n try {\n body = await response.text();\n } catch {\n body = \"\";\n }\n\n let retryAfter: string | null = null;\n try {\n retryAfter = response.headers.get(\"Retry-After\");\n } catch {\n retryAfter = null;\n }\n\n return toSuaError({ status: response.status, retryAfter, body });\n}\n\n/**\n * Reads a `Retry-After` header value (RFC 9110 §10.2.3) into whole seconds to wait.\n *\n * - A non-negative integer of decimal digits (`\"30\"`, surrounding whitespace allowed) is returned as that number.\n * This is the only form the Coordinator sends (`ceil` of the bucket window, at least 1).\n * - An HTTP-date (`\"Wed, 21 Oct 2015 07:28:00 GMT\"`) is returned as `max(0, ceil((date - nowMs) / 1000))`.\n * - `null`, `\"\"`, a negative or fractional number, or anything unparseable returns `undefined`.\n *\n * @param value The raw header value.\n * @param nowMs The current time in ms since the epoch, for the HTTP-date form. Defaults to `Date.now()`.\n */\nexport function parseRetryAfter(value: string | null, nowMs?: number): number | undefined {\n if (value === null) {\n return undefined;\n }\n\n const trimmed = value.trim();\n if (/^\\d+$/.test(trimmed)) {\n const seconds = Number(trimmed);\n\n return Number.isSafeInteger(seconds) ? seconds : undefined;\n }\n\n /**\n * Every HTTP-date form (IMF-fixdate, RFC 850, asctime) starts with a day name. Requiring it keeps `Date.parse`'s\n * lenient reading of strings such as `\"-1\"` or `\"1.5\"` out.\n */\n if (!/^[A-Za-z]{3,9},?\\s/.test(trimmed)) {\n return undefined;\n }\n\n /**\n * The asctime form carries no zone but is UTC by definition; `Date.parse` would read it as local time.\n */\n const dateMs = Date.parse(ASCTIME_DATE.test(trimmed) ? `${trimmed} GMT` : trimmed);\n if (Number.isNaN(dateMs)) {\n return undefined;\n }\n\n return Math.max(0, Math.ceil((dateMs - (nowMs ?? Date.now())) / 1000));\n}\n\n/**\n * Narrows an envelope's `type` onto {@link ErrorKindDto}, reading an absent or unknown kind as `internal`.\n */\nfunction toErrorKind(type: unknown): SuaErrorKind {\n return ERROR_KINDS.find((kind) => kind === type) ?? \"internal\";\n}\n\n/**\n * Narrows an envelope's `code` onto {@link SuaReason}, reading a bare kind, an absent or an unlisted code as `\"\"`.\n */\nfunction toReason(code: unknown): SuaReason {\n return SUA_REASONS.find((known) => known === code) ?? \"\";\n}\n\n/**\n * Returns `value` when it is a non-empty string, else `undefined`.\n */\nfunction toNonEmptyString(value: unknown): string | undefined {\n return typeof value === \"string\" && value !== \"\" ? value : undefined;\n}\n","/**\n * Every state a route can be in, in the order a route moves through them, as the Coordinator lists core's route\n * states (`internal/routing/domain/routes.go` `States`). `GET /wallet/v1/routes?status=…` refuses any other name.\n */\nexport const ROUTE_STATES = [\n \"planned\",\n \"expired\",\n \"submitted\",\n \"awaiting_destination\",\n \"stalled\",\n \"completed\",\n \"refunded\",\n \"failed\",\n \"unresolved\",\n] as const;\n\n/**\n * A route state this client knows (`apidoc.Route.status`), one of {@link ROUTE_STATES}. A route's own `status` may also\n * be one core added after this client was built; such a state means the funds are in flight, never failed or done.\n *\n * - `planned` — opened: its steps are ready to sign and no source transaction is reported yet.\n * - `expired` — still `planned` when `expires_at` passed. A late source report is still followed.\n * - `submitted` — the source transaction is reported and core follows it.\n * - `awaiting_destination` — the source side is done; the funds are on their way to the destination.\n * - `stalled` — taking longer than expected. **Never a failure**: the funds are in flight.\n * - `completed` — delivered; `actual_output` and `destination_tx` name what arrived.\n * - `refunded` — the funds went back to the source address.\n * - `failed` — the route failed.\n * - `unresolved` — core cannot tell the outcome yet. **Never a failure**: the funds are in flight.\n */\nexport type RouteStateDto = (typeof ROUTE_STATES)[number];\n","import type { paths } from \"#/generated/hub\";\n\n/**\n * A path template the Coordinator's hub API document (`src/generated/openapi.json`) defines.\n */\ntype HubPath = keyof paths;\n\n/**\n * The HTTP verbs the client sends, as the document spells them.\n */\ntype HubVerb = \"get\" | \"post\" | \"put\" | \"patch\" | \"delete\";\n\n/**\n * The verbs the document defines on one path. A verb the path does not take is `never` there.\n */\ntype HubVerbOf<P extends HubPath> = {\n [V in HubVerb]: [NonNullable<paths[P][V]>] extends [never] ? never : V;\n}[HubVerb];\n\n/**\n * One endpoint: a verb and a path template the document pairs. A wrong path or verb fails to compile.\n */\ntype HubEndpoint = { [P in HubPath]: readonly [HubVerbOf<P>, P] }[HubPath];\n\n/**\n * Every hub endpoint the client calls, keyed by the client method that calls it. The single place a path is spelled;\n * the `satisfies` check holds each verb and path to the generated document.\n */\nconst HUB_ENDPOINTS = {\n resolveGuestCheckout: [\"post\", \"/pay/v1/checkouts/resolve\"],\n resolveCheckout: [\"post\", \"/wallet/v1/checkouts/resolve\"],\n listGuestAssets: [\"get\", \"/pay/v1/assets\"],\n listAssets: [\"get\", \"/wallet/v1/assets\"],\n startRound: [\"post\", \"/wallet/v1/auth-rounds\"],\n getRound: [\"get\", \"/wallet/v1/auth-rounds/{id}\"],\n verifyRound: [\"post\", \"/wallet/v1/auth-rounds/{id}/verify\"],\n registerKeypair: [\"post\", \"/wallet/v1/credentials/session\"],\n getSession: [\"get\", \"/wallet/v1/session\"],\n signOut: [\"delete\", \"/wallet/v1/session\"],\n getWallet: [\"get\", \"/wallet/v1/account\"],\n relay: [\"post\", \"/wallet/v1/relay\"],\n saveExternalAccount: [\"post\", \"/wallet/v1/external-accounts\"],\n markExternalAccountUsed: [\"patch\", \"/wallet/v1/external-accounts/{id}\"],\n removeExternalAccount: [\"delete\", \"/wallet/v1/external-accounts/{id}\"],\n answerWalletOffer: [\"patch\", \"/wallet/v1/session\"],\n quoteRoute: [\"post\", \"/wallet/v1/routes/quotes\"],\n openRoute: [\"post\", \"/wallet/v1/routes\"],\n getRoute: [\"get\", \"/wallet/v1/routes/{id}\"],\n listRoutes: [\"get\", \"/wallet/v1/routes\"],\n reportRouteSource: [\"post\", \"/wallet/v1/routes/{id}/source\"],\n getExternalBalances: [\"get\", \"/wallet/v1/balances\"],\n warmExternalBalances: [\"post\", \"/wallet/v1/balances\"],\n quoteTopUp: [\"post\", \"/wallet/v1/smart-routes\"],\n quoteCheckout: [\"post\", \"/wallet/v1/smart-routes\"],\n getPayIn: [\"get\", \"/wallet/v1/smart-routes/{id}\"],\n confirmPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/confirm\"],\n adjustPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/adjust\"],\n cancelPayIn: [\"post\", \"/wallet/v1/smart-routes/{id}/cancel\"],\n createGuestHandoff: [\"post\", \"/pay/v1/handoffs\"],\n mergeGuestSession: [\"post\", \"/pay/v1/session/merge\"],\n openGuest: [\"post\", \"/pay/v1/session\"],\n saveGuestWallet: [\"post\", \"/pay/v1/external-accounts\"],\n removeGuestWallet: [\"delete\", \"/pay/v1/external-accounts/{id}\"],\n markGuestWalletUsed: [\"patch\", \"/pay/v1/external-accounts/{id}\"],\n getGuestExternalBalances: [\"get\", \"/pay/v1/balances\"],\n warmGuestExternalBalances: [\"post\", \"/pay/v1/balances\"],\n quoteGuestPayIn: [\"post\", \"/pay/v1/smart-routes\"],\n getGuestPayIn: [\"get\", \"/pay/v1/smart-routes/{id}\"],\n confirmGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/confirm\"],\n adjustGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/adjust\"],\n cancelGuestPayIn: [\"post\", \"/pay/v1/smart-routes/{id}/cancel\"],\n} as const satisfies Record<string, HubEndpoint>;\n\n/**\n * The name of a hub endpoint the client calls.\n */\nexport type HubEndpointName = keyof typeof HUB_ENDPOINTS;\n\n/**\n * The upper-case verb a request sends.\n */\nexport type HubMethod = Uppercase<HubVerb>;\n\n/**\n * The verb and the path (after `baseUrl`) of one call.\n */\nexport interface HubTarget {\n /**\n * The HTTP verb.\n */\n method: HubMethod;\n\n /**\n * The path, the id already encoded, and the query string when the call takes one.\n */\n path: string;\n}\n\n/**\n * Builds one call's verb and path from its endpoint. `id` replaces the template's `{id}` and must already be encoded;\n * `query` is appended as given (`\"\"` or `?a=b`).\n */\nexport function hubTarget(name: HubEndpointName, id?: string, query = \"\"): HubTarget {\n const [verb, template] = HUB_ENDPOINTS[name];\n const path = id === undefined ? template : template.replace(\"{id}\", id);\n\n return { method: verb.toUpperCase() as HubMethod, path: `${path}${query}` };\n}\n","/**\n * Every state of the gas Stridge sends a wallet for an `R` leg (pay-in guide §5.3.2, §6.2), in order.\n */\nexport const PAY_IN_DRIP_STATES = [\"held\", \"sending\", \"landed\"] as const;\n\n/**\n * An `R` leg's `drip`, one of {@link PAY_IN_DRIP_STATES}: `held` until every other step is done, then `sending`, then\n * `landed` once the gas is in the wallet and the approval can be sent.\n */\nexport type PayInDripDto = (typeof PAY_IN_DRIP_STATES)[number];\n","/**\n * Every state a pay-in leg can be in (pay-in guide §7.2), as core names them, grouped as the guide shows them.\n */\nexport const PAY_IN_LEG_STATES = [\n \"planned\",\n \"needs_signature\",\n \"needs_approval\",\n \"approving\",\n \"submitting\",\n \"submitted\",\n \"in_flight\",\n \"refunding\",\n \"voiding\",\n \"filled\",\n \"refunded\",\n \"voided\",\n \"dropped\",\n \"needs_support\",\n \"written_off\",\n] as const;\n\n/**\n * A pay-in leg state this client knows, one of {@link PAY_IN_LEG_STATES}. A leg's own `status` may also be one core\n * added after this client was built; such a state means the funds may be moving, never failed.\n *\n * - `planned`, `needs_signature` — waiting for a signature.\n * - `needs_approval` (a wallet-sent approval is offered, or the drip is on its way), `approving` (its hash is\n * reported, core verifies it) — waiting for the approval.\n * - `submitting`, `submitted`, `in_flight` — in progress.\n * - `refunding`, `voiding` — in progress, returning funds.\n * - `filled` — arrived (`actual_output`).\n * - `refunded` — returned to the wallet (`refund_tx`, `refund_amount`).\n * - `voided`, `dropped` — not used: no funds moved, or they were returned.\n * - `needs_support`, `written_off` — Stridge is looking into it. **Never a failure.**\n */\nexport type PayInLegStateDto = (typeof PAY_IN_LEG_STATES)[number];\n","/**\n * Every mechanism a pay-in leg can pull funds with (pay-in guide §6), as core names them.\n */\nexport const PAY_IN_MECHANISMS = [\"P\", \"C\", \"B\", \"G\", \"N\", \"R\", \"S\", \"D\", \"W\", \"T\", \"X\", \"Y\", \"U\", \"V\"] as const;\n\n/**\n * How a pay-in leg pulls funds, one of {@link PAY_IN_MECHANISMS}. A leg's or a holding's `mechanism` may also be one\n * core added after this client was built.\n *\n * - `P` — an EIP-3009 transfer authorization: one `eip712` signature (K1); Stridge submits it and pays the gas.\n * - `C` — a Permit2 transfer for a token that already allows Permit2: one `eip712` signature (K2).\n * - `B` — a signed approval of Permit2 (K3, K4 or K5) that Stridge sends, then a Permit2 transfer (K2): two `eip712`\n * signatures at quote time.\n * - `G` — the wallet sends `approve(Permit2)` (K7) paying its gas from the token, then signs a Permit2 transfer (K2).\n * - `N` — the wallet sends `approve(Permit2)` (K7) paying its own gas, then signs a Permit2 transfer (K2).\n * - `R` — as `N`, after Stridge sends the wallet exactly one approval's gas (the drip).\n * - `S` — a sponsored Solana transaction the wallet signs and core broadcasts (K8); Stridge's fee payer pays its fee.\n * - `D` — a Calibur batch from an account already delegated through EIP-7702: one `eip712` signature (K6).\n * - `W` — a coin send: after confirm, the wallet sends its native coin to Relay's depository itself, paying its own\n * gas (K7, `depositNative`). Its leg has no step in the quote.\n * - `T` — a same-chain Tempo holding, catalog information rather than a supported pull mechanism.\n * - `X` — the checkout's own asset on its own chain: after confirm, the wallet sends it straight to the destination\n * itself, paying its own gas. Its transfer step appears and is answered as `W`'s is.\n * - `Y` — `X` with the gas paid by the wallet's gas station.\n * - `U` — `X` once Stridge sent the wallet exactly that transfer's gas (the drip); its step appears once the drip landed.\n * - `V` — the checkout's own asset on its own chain, already approved for Permit2: one `eip712` signature, a plain\n * Permit2 `PermitTransferFrom` (K2) to Stridge's relayer, which sends it to the destination and pays the gas.\n *\n * `X`, `Y`, `U` and `V` show only in a holding's `payable_mechanisms`, never in its `mechanisms`.\n */\nexport type PayInMechanismDto = (typeof PAY_IN_MECHANISMS)[number];\n","/**\n * Every phase a pay-in reports (pay-in guide §5.3), as core names them.\n */\nexport const PAY_IN_PHASES = [\"executing\", \"winding_down\"] as const;\n\n/**\n * A pay-in's `phase`, one of {@link PAY_IN_PHASES}.\n *\n * - `executing` — running.\n * - `winding_down` — stopping after a failure or a cancel while some legs are still live: keep polling until the state\n * is terminal.\n */\nexport type PayInPhaseDto = (typeof PAY_IN_PHASES)[number];\n","/**\n * Every shape a pay-in plan takes (pay-in guide §5.3), as core names them.\n */\nexport const PAY_IN_SHAPES = [\"single_leg\", \"multi_leg\"] as const;\n\n/**\n * A pay-in's `shape`, one of {@link PAY_IN_SHAPES}: one leg, or several legs across wallets and chains.\n */\nexport type PayInShapeDto = (typeof PAY_IN_SHAPES)[number];\n","/**\n * Every state a pay-in can be in (pay-in guide §7.1), as core names them.\n */\nexport const PAY_IN_STATES = [\n \"requires_confirmation\",\n \"requires_action\",\n \"processing\",\n \"on_hold\",\n \"completed\",\n \"failed\",\n \"canceled\",\n \"expired\",\n] as const;\n\n/**\n * The states a pay-in never leaves: polling stops at them.\n */\nexport const PAY_IN_TERMINAL_STATES = [\"completed\", \"failed\", \"canceled\", \"expired\"] as const;\n\n/**\n * A pay-in state this client knows, one of {@link PAY_IN_STATES}. A pay-in's own `status` may also be one core added\n * after this client was built; such a state means the funds may be moving, never failed or done.\n *\n * - `requires_confirmation` — quoted: sign every step and confirm before `expires_at`.\n * - `requires_action` — core needs a step from a wallet: do `required_steps[0]`, then adjust.\n * - `processing` — funds are moving, or core waits on a chain, a bridge or the drip. **Never a failure.**\n * - `on_hold` — a leg needs Stridge's support and nothing else is moving: Stridge's to resolve. **Never a failure.**\n * - `completed` — done; `delivered` is what reached the SUA account, which may be less than `amount`.\n * - `failed` — it could not complete; legs that moved funds are refunded (`refund_tx`, `refund_amount`).\n * - `canceled` — stopped (`cancellation_reason`).\n * - `expired` — never confirmed in time.\n */\nexport type PayInStateDto = (typeof PAY_IN_STATES)[number];\n\n/**\n * A terminal pay-in state, one of {@link PAY_IN_TERMINAL_STATES}.\n */\nexport type PayInTerminalStateDto = (typeof PAY_IN_TERMINAL_STATES)[number];\n","/**\n * Every scheme core issues to external wallets (pay-in guide §8). The step model also defines\n * `eip7702_authorization` and `tempo_transaction`, which core never issues to an external wallet.\n */\nexport const PAY_IN_STEP_SCHEMES = [\"eip712\", \"evm_transaction\", \"solana_transaction\"] as const;\n\n/**\n * A pay-in step's `scheme`, one of {@link PAY_IN_STEP_SCHEMES}: which wallet call the step takes.\n *\n * - `eip712` — `eth_signTypedData_v4` over the payload, unchanged (K1 to K6).\n * - `evm_transaction` — `eth_sendTransaction` with exactly the payload's fields; the wallet sends it (K7).\n * - `solana_transaction` — a sponsored Solana message; parsing does not enable signing.\n *\n * A step whose scheme is not one of them is never signed: cancel the pay-in and report it.\n */\nexport type PayInStepSchemeDto = (typeof PAY_IN_STEP_SCHEMES)[number];\n","/**\n * Every status a pay-in step can have (pay-in guide §7.3), as core names them.\n */\nexport const PAY_IN_STEP_STATUSES = [\n \"unsigned\",\n \"signed\",\n \"submitted\",\n \"invalid\",\n \"expired\",\n \"refused\",\n \"superseded\",\n \"dead\",\n] as const;\n\n/**\n * A pay-in step's `status`, one of {@link PAY_IN_STEP_STATUSES}. Only the steps `required_steps` names, and a quote's\n * `steps` at confirm, are acted on, whatever their status says.\n *\n * - `unsigned` — waiting for the wallet.\n * - `signed` — the signature was received.\n * - `submitted` — sent on chain (a wallet-sent approval, or an approval core sent); may carry `tx_hash`.\n * - `invalid` — the signature did not verify for the leg's source address (`reason`); a replacement follows in\n * `required_steps`.\n * - `expired` — not done before the step's `expires_at`.\n * - `refused` — the chain or the provider refused it (`reason`).\n * - `superseded` — a newer step replaced it before it was used.\n * - `dead` — the pay-in or its leg ended before it was used.\n */\nexport type PayInStepStatusDto = (typeof PAY_IN_STEP_STATUSES)[number];\n","/**\n * Every reason a holding goes unused (pay-in guide §5.3.1), as core names them.\n */\nexport const PAY_IN_UNSPENDABLE_REASONS = [\n \"route_unverifiable\",\n \"native_coin\",\n \"smart_account\",\n \"no_free_route\",\n \"drip_refused\",\n \"approval_required\",\n \"over_sponsor_cap\",\n] as const;\n\n/**\n * Why a holding goes unused, one of {@link PAY_IN_UNSPENDABLE_REASONS}.\n *\n * - `route_unverifiable` — the route could not be verified.\n * - `native_coin` — native coins (ETH, BNB, SOL, …) are never pulled.\n * - `smart_account` — the address is a smart-contract account on that chain.\n * - `no_free_route` — no gas-free mechanism exists for this token from this wallet.\n * - `drip_refused` — it needs a wallet-sent approval and Stridge cannot fund its gas now.\n * - `approval_required` — it needs a wallet-sent approval on a chain where core cannot plan one.\n * - `over_sponsor_cap` — using it would exceed the sponsored-gas allowance.\n */\nexport type PayInUnspendableReasonDto = (typeof PAY_IN_UNSPENDABLE_REASONS)[number];\n\n/**\n * A holding a pay-in plan does not use, and why (pay-in guide §5.3.1). Shown so a large balance that was not used is\n * not a mystery.\n */\nexport interface PayInUnspendableDto {\n /**\n * The holding's CAIP-19 asset.\n */\n asset: string;\n\n /**\n * The holding's amount, in its base units, as a decimal string. It may exceed 2^53.\n */\n amount: string;\n\n /**\n * Why it goes unused: one of `PAY_IN_UNSPENDABLE_REASONS`, or one core added later.\n */\n reason: PayInUnspendableReasonDto | (string & {});\n}\n","/**\n * Every role a route step can have, as core names them. The client refuses a route answer with any other role, so a\n * step it cannot name never reaches a signature.\n */\nexport const ROUTE_STEP_ROLES = [\"approve\", \"provider\", \"transfer\"] as const;\n\n/**\n * A route step's `role` (`apidoc.RouteStep.role`), closed over {@link ROUTE_STEP_ROLES}.\n *\n * - `approve` — an exact-amount ERC-20 approval of the source asset for the provider call that follows it.\n * - `provider` — the provider's call that moves the funds. Its hash is the one to report.\n * - `transfer` — a plain transfer, the only step of a route core settles itself. Its hash is the one to report.\n */\nexport type RouteStepRoleDto = (typeof ROUTE_STEP_ROLES)[number];\n","/**\n * The CAIP-2 namespace of EVM chains (`eip155:1`, `eip155:56`, Tempo's `eip155:4217`): its reference is the decimal\n * chain id.\n */\nexport const EVM_CAIP_NAMESPACE = \"eip155\";\n\n/**\n * The most decimals a token amount may have: an ERC-20 token's `decimals` is a `uint8`. An external holding naming\n * more is unusable, and the base-unit helpers refuse more.\n */\nexport const MAX_TOKEN_DECIMALS = 255;\n\n/**\n * Every kind of pay-in step (pay-in guide §6.1), told apart by the step's `scheme` and, for `eip712`, the payload's\n * `primaryType`. The kit never builds one; it recognises them to choose the wallet call and the copy, and never signs a\n * step whose kind it cannot name.\n *\n * - `K1` — an EIP-3009 transfer authorization (`ReceiveWithAuthorization`), mechanism\n * `P`.\n * - `K2` — a Permit2 transfer (`PermitBatchWitnessTransferFrom`, or `PermitWitnessTransferFrom`): mechanism `C`, and\n * the second step of `B`, `G`, `N` and `R`; or a plain `PermitTransferFrom` with no witness: mechanism `V`.\n * - `K3` — an EIP-2612 `Permit` (`owner, spender, value, nonce, deadline`) approving Permit2, the first step of `B`.\n * - `K4` — a DAI-style `Permit` (`holder, spender, nonce, expiry, allowed`) approving Permit2, the first step of `B`.\n * - `K5` — a Polygon `MetaTransaction` whose call approves Permit2, the first step of `B`.\n * - `K6` — a Calibur `SignedBatchedCall`, mechanism `D`.\n * - `K7` — a transaction the wallet sends itself (`evm_transaction`): `approve(Permit2, max)` for mechanisms `G`, `N`\n * and `R`, or a coin send (`depositNative` to Relay's depository) for mechanism `W`.\n * - `K8` — a sponsored Solana transaction, signed by the user and broadcast by Core.\n */\nexport const PAY_IN_STEP_KINDS = [\"K1\", \"K2\", \"K3\", \"K4\", \"K5\", \"K6\", \"K7\", \"K8\"] as const;\n","import { EVM_CAIP_NAMESPACE } from \"./constants\";\n\nimport type { Caip19Parts, Caip2Parts } from \"./types\";\n\n/**\n * A CAIP-2 chain id: a namespace of 3 to 8 lowercase letters, digits or hyphens, `:`, then a reference of 1 to 32\n * letters, digits, hyphens or underscores.\n */\nconst CAIP2_PATTERN = /^([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32})$/;\n\n/**\n * A CAIP-19 asset id: a CAIP-2 chain id, `/`, an asset namespace of 3 to 8 lowercase letters, digits or hyphens, `:`,\n * then an asset reference of 1 to 128 letters, digits, hyphens, dots or `%`. No token id: pay-ins move fungible\n * assets only.\n */\nconst CAIP19_PATTERN = /^(([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32}))\\/([-a-z0-9]{3,8}):([-.%a-zA-Z0-9]{1,128})$/;\n\n/**\n * An `eip155` reference: a decimal chain id without a leading zero.\n */\nconst EVM_CHAIN_REFERENCE_PATTERN = /^[1-9][0-9]*$/;\n\n/**\n * Splits a CAIP-2 chain id into its namespace and reference, or `null` when `chain` is not one. Pure.\n *\n * @example parseCaip2(\"eip155:56\") → { namespace: \"eip155\", reference: \"56\" }\n * @example parseCaip2(\"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\") → { namespace: \"solana\", reference: \"5eykt4Us…KqZKvdp\" }\n */\nexport function parseCaip2(chain: string): Caip2Parts | null {\n if (typeof chain !== \"string\") {\n return null;\n }\n const match = CAIP2_PATTERN.exec(chain);\n if (match === null) {\n return null;\n }\n\n return { namespace: match[1], reference: match[2] };\n}\n\n/**\n * Splits a CAIP-19 asset id into its chain and asset parts, or `null` when `asset` is not one. An asset id with a\n * token id (`…/erc721:0x…/1`) is not a pay-in asset and reads as `null`. Pure.\n *\n * @example parseCaip19(\"eip155:1/slip44:60\") → { chain: \"eip155:1\", namespace: \"eip155\", reference: \"1\",\n * assetNamespace: \"slip44\", assetReference: \"60\" }\n */\nexport function parseCaip19(asset: string): Caip19Parts | null {\n if (typeof asset !== \"string\") {\n return null;\n }\n const match = CAIP19_PATTERN.exec(asset);\n if (match === null) {\n return null;\n }\n\n return {\n chain: match[1],\n namespace: match[2],\n reference: match[3],\n assetNamespace: match[4],\n assetReference: match[5],\n };\n}\n\n/**\n * The hex chain id of an EVM CAIP-2 chain, lowercase and without leading zeros: what `wallet_switchEthereumChain` takes\n * and what keys `wallet_getCapabilities`. `null` when `chain` is not an `eip155` chain with a decimal chain id. Pure.\n *\n * @example evmChainHex(\"eip155:56\") === \"0x38\"\n * @example evmChainHex(\"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\") === null\n */\nexport function evmChainHex(chain: string): string | null {\n const reference = evmChainReference(chain);\n\n return reference === null ? null : `0x${BigInt(reference).toString(16)}`;\n}\n\n/**\n * The numeric chain id of an EVM CAIP-2 chain, as viem and wagmi take it. `null` when `chain` is not an `eip155` chain\n * with a decimal chain id, or when the id is too large to be a safe integer. Pure.\n *\n * @example evmChainNumber(\"eip155:4217\") === 4217\n */\nexport function evmChainNumber(chain: string): number | null {\n const reference = evmChainReference(chain);\n if (reference === null) {\n return null;\n }\n const chainId = Number(reference);\n\n return Number.isSafeInteger(chainId) ? chainId : null;\n}\n\n/**\n * The decimal chain id of an EVM CAIP-2 chain, or `null` when `chain` is not one.\n */\nfunction evmChainReference(chain: string): string | null {\n const parts = parseCaip2(chain);\n if (parts === null || parts.namespace !== EVM_CAIP_NAMESPACE || !EVM_CHAIN_REFERENCE_PATTERN.test(parts.reference)) {\n return null;\n }\n\n return parts.reference;\n}\n","/**\n * EVM calldata: `0x` and whole bytes of hex, either case (`0x` alone for none), as core writes it with\n * `hexutil.Encode`. A route step's `data` and a pay-in approval's `data` both match it. Internal: not exported from\n * the package index.\n */\nexport const CALLDATA_PATTERN = /^0x(?:[0-9a-fA-F]{2})*$/;\n\n/**\n * A decimal integer without leading zeros, as core writes a route step's native value in wei and every pay-in amount\n * in base units (kept as a string: it may exceed 2^53). Internal: not exported from the package index.\n */\nexport const DECIMAL_INTEGER_PATTERN = /^(?:0|[1-9][0-9]*)$/;\n","import {\n type CheckoutResolutionDto,\n type AssetDto,\n type AssetListDto,\n type ExternalBalanceReadDto,\n type ExternalBalancesDto,\n type ExternalHoldingDto,\n PAY_IN_STATES,\n type PayInDestinationDto,\n type PayInDto,\n type PayInLegDto,\n type PayInStateDto,\n type PayInStepDto,\n type PayInUnspendableDto,\n ROUTE_STATES,\n ROUTE_STEP_ROLES,\n type RouteDto,\n type RouteEndDto,\n type RouteFeesDto,\n type RouteListDto,\n type RouteQuoteDto,\n type RouteStateDto,\n type RouteStepCallDto,\n type RouteStepDto,\n} from \"#/models\";\nimport { evmChainHex } from \"#/payIn/caip\";\nimport { MAX_TOKEN_DECIMALS } from \"#/payIn/constants\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport { CALLDATA_PATTERN, DECIMAL_INTEGER_PATTERN } from \"#/shared/patterns\";\n\nimport { ROUTE_SOURCE_CHAIN_ID } from \"./constants\";\n\n/**\n * Reports whether `value` is shaped like a {@link RouteQuoteDto}: a JSON object whose `estimated_output`,\n * `minimum_output`, `expires_at` and `provider` are strings, whose `eta_seconds` is a safe integer, and whose `fees`\n * is an object with a string `platform` and `provider`. Its `trade_type` and `source_amount` are each a string,\n * `null` or absent.\n *\n * It checks shapes, not values: an amount is not checked to be digits, nor an instant to parse. Extra keys are\n * allowed, at every level, as on every Coordinator answer (`isErrorEnvelopeDto` allows them too), so a field the\n * Coordinator adds later never breaks the client.\n */\nexport function isRouteQuoteDto(value: unknown): value is RouteQuoteDto {\n return (\n isJsonObject(value) &&\n typeof value.estimated_output === \"string\" &&\n typeof value.minimum_output === \"string\" &&\n isOptionalString(value.trade_type) &&\n isOptionalString(value.source_amount) &&\n isRouteFeesDto(value.fees) &&\n Number.isSafeInteger(value.eta_seconds) &&\n typeof value.expires_at === \"string\" &&\n typeof value.provider === \"string\"\n );\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteDto}: {@link isRouteQuoteDto}, plus a non-empty string\n * `id`, a non-empty string `status`, a `steps` array whose every entry is a step the client can sign, an\n * `actual_output`, `destination_tx`, `source_tx`, `error`, `submitted_at` and `source_confirmed_at` that are each a\n * string, `null`, or absent, an `amount`, `created_at` and `updated_at` that are each a string or absent, and a\n * `source` and `destination` that are each a {@link RouteEndDto} (a string `asset` and `address`) or absent.\n *\n * The echoed fields are optional, so an answer from a Coordinator that predates them still reads; a present one of\n * the wrong shape fails the check. Whether an echo matches the request is the caller's to check.\n *\n * A step the client can sign has a `role` from `ROUTE_STEP_ROLES` and an `evm` call whose `chain_id` is\n * {@link ROUTE_SOURCE_CHAIN_ID}, whose `to` matches `EVM_ADDRESS_PATTERN`, whose `data` is `0x` and whole bytes of\n * hex, and whose `value` is a decimal integer. The steps are what the account signs, so their values are checked,\n * not only their shapes: an unknown role, another chain or a malformed call fails the check, and a step the client\n * cannot name never reaches a signature.\n *\n * A state outside `ROUTE_STATES` passes: core may add states, and a route whose funds are moving must still read.\n * Tell a known state with {@link isRouteStateDto}, and treat any other as in flight, never as failed or done. Extra\n * keys are allowed, as in {@link isRouteQuoteDto}, inside `evm` too; build a transaction from the four checked fields\n * only.\n */\nexport function isRouteDto(value: unknown): value is RouteDto {\n return isRouteWith(value, isRouteStepDto);\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteListDto}: a JSON object whose `data` is an array of routes and\n * whose `has_more` is a boolean. Each route is checked as in {@link isRouteDto}, except that a step's `chain_id` may\n * name any chain: the list also holds the routes that carried a pay-in's legs, whose steps run on the connected\n * wallet's chain, and a list is history, never something to sign. One malformed route fails the whole list; a route\n * in a state this client does not know does not. Extra keys are allowed, as in {@link isRouteQuoteDto}.\n *\n * Sign only the steps of a route read again through `getRoute`, whose answer {@link isRouteDto} holds to Tempo.\n */\nexport function isRouteListDto(value: unknown): value is RouteListDto {\n return (\n isJsonObject(value) &&\n Array.isArray(value.data) &&\n value.data.every((route) => isRouteWith(route, isListedRouteStepDto)) &&\n typeof value.has_more === \"boolean\"\n );\n}\n\n/**\n * Reports whether `value` is a route whose every step passes `isStep`, with the fields {@link isRouteDto} names.\n */\nfunction isRouteWith(value: unknown, isStep: (step: unknown) => boolean): value is RouteDto {\n return (\n isJsonObject(value) &&\n isRouteQuoteDto(value) &&\n isNonEmptyString(value.id) &&\n isNonEmptyString(value.status) &&\n Array.isArray(value.steps) &&\n value.steps.every(isStep) &&\n isOptionalString(value.actual_output) &&\n isOptionalString(value.destination_tx) &&\n isOptionalString(value.source_tx) &&\n isOptionalString(value.error) &&\n isOptionalString(value.refund_amount) &&\n isOptionalString(value.refund_tx) &&\n isOptionalString(value.submitted_at) &&\n isOptionalString(value.source_confirmed_at) &&\n isAbsentOrString(value.amount) &&\n isAbsentOrString(value.created_at) &&\n isAbsentOrString(value.updated_at) &&\n (value.source === undefined || isRouteEndDto(value.source)) &&\n (value.destination === undefined || isRouteEndDto(value.destination))\n );\n}\n\n/**\n * Reports whether `value` is one of the route states this client knows, `ROUTE_STATES`. A route's `status` that is\n * not one of them is a state core added later: the funds are in flight.\n */\nexport function isRouteStateDto(value: unknown): value is RouteStateDto {\n return isMember(ROUTE_STATES, value);\n}\n\n/**\n * Reports whether `value` is shaped like an {@link ExternalBalancesDto}: a JSON object whose `holdings` is an array of\n * holdings, whose `id` is a string, `null` or absent, whose `as_of` is `null`, absent or an object of\n * `{ block, at }` reads (a safe-integer `block` and a string `at`), and whose `missing` is `null`, absent or an array\n * of strings.\n *\n * A holding has a string `chain`, `asset` and `symbol`, a `decimals` that is an integer from 0 to 255, an `amount` that\n * is a decimal integer without leading zeros (kept as a string: it may exceed 2^53), a `usd` that is a string, `null`\n * or absent, and a `mechanisms` array of strings. A mechanism this client does not know passes; the quote is\n * authoritative. An optional field that is `null` reads as absent: refusing it would cost a read and protect nothing.\n * Extra keys are allowed, at every level, as on every Coordinator answer.\n */\nexport function isExternalBalancesDto(value: unknown): value is ExternalBalancesDto {\n return (\n isJsonObject(value) &&\n isOptionalString(value.id) &&\n isOptionalString(value.spendable_usd) &&\n (isAbsent(value.unpriced) || isStringArray(value.unpriced)) &&\n (isAbsent(value.unread) || isStringArray(value.unread)) &&\n (isAbsent(value.as_of) || (isJsonObject(value.as_of) && Object.values(value.as_of).every(isExternalBalanceReadDto))) &&\n (isAbsent(value.missing) || isStringArray(value.missing)) &&\n Array.isArray(value.holdings) &&\n value.holdings.every(isExternalHoldingDto)\n );\n}\n\n/**\n * Reports whether `value` is shaped like a {@link PayInDto}, the answer of every pay-in call: a JSON object with a\n * non-empty string `id` and `status`; a `phase`, `failure_reason`, `cancellation_reason`, `deadline` and `snapshot_id`\n * that are each a string, `null` or absent; a `destination` with a string `asset` and `address`; a string `amount`,\n * `delivered`, `shape` and `expires_at`; a `poll_after_ms` that is a non-negative safe integer, `null` or absent; and\n * arrays of `legs`, `steps`, `required_steps` and `unspendable`, each entry well-formed, where every id in\n * `required_steps` names an entry of `steps`.\n *\n * A leg has a safe-integer `n`, a non-empty string `status` and `mechanism`, a string `source_asset`, `input_amount`\n * and `min_output`, and a `source_tx`, `actual_output`, `refund_tx`, `refund_amount`, `fail_reason` and `drip` that\n * are each a string, `null` or absent. An unspendable holding has a string `asset`, `amount` and `reason`.\n *\n * It checks shapes, never values, and a step's base fields only: a non-empty string `id`, `scheme` and `status`,\n * a safe-integer `leg`, a string `chain` and `expires_at`, and a `digest`, `reason` and `tx_hash` that are each a\n * string, `null` or absent. A step's `payload` is not checked at all. `steps` is the pay-in's whole history and core\n * may add schemes, so a step this client could never sign must not make a pay-in that is moving money unreadable.\n * Check a step by value before a wallet sees it.\n *\n * Only the fields the guide marks required are required: an optional field that is `null` reads as absent, so a\n * pay-in that is moving money never turns unreadable over one (the guide's own loop polls at `poll_after_ms ?? 2000`).\n * A state, leg state, step status, scheme, mechanism, phase, shape or drip outside this client's lists passes: core\n * may add them. Tell a known pay-in state with {@link isPayInStateDto}, and treat any other as in flight, never as\n * failed or done. Extra keys are allowed, at every level, as on every Coordinator answer.\n */\nexport function isPayInDto(value: unknown): value is PayInDto {\n return (\n isJsonObject(value) &&\n isNonEmptyString(value.id) &&\n isNonEmptyString(value.status) &&\n isOptionalString(value.phase) &&\n isOptionalString(value.failure_reason) &&\n isOptionalString(value.cancellation_reason) &&\n isPayInDestinationDto(value.destination) &&\n (isAbsent(value.payee) || (isJsonObject(value.payee) && typeof value.payee.name === \"string\")) &&\n typeof value.amount === \"string\" &&\n typeof value.delivered === \"string\" &&\n typeof value.shape === \"string\" &&\n typeof value.expires_at === \"string\" &&\n isOptionalString(value.deadline) &&\n isOptionalString(value.fee_usd) &&\n Array.isArray(value.legs) &&\n value.legs.every(isPayInLegDto) &&\n Array.isArray(value.steps) &&\n value.steps.every(isPayInStepDto) &&\n isStringArray(value.required_steps) &&\n namesListedSteps(value.required_steps, value.steps) &&\n Array.isArray(value.unspendable) &&\n value.unspendable.every(isPayInUnspendableDto) &&\n isOptionalString(value.snapshot_id) &&\n (isAbsent(value.poll_after_ms) || isSafeIntegerFrom(value.poll_after_ms, 0, Number.MAX_SAFE_INTEGER))\n );\n}\n\n/**\n * Reports whether `value` is one of the pay-in states this client knows, `PAY_IN_STATES`. A pay-in's `status` that is\n * not one of them is a state core added later: the funds may be moving.\n */\nexport function isPayInStateDto(value: unknown): value is PayInStateDto {\n return isMember(PAY_IN_STATES, value);\n}\n\n/**\n * Reports whether `value` is an {@link ExternalBalanceReadDto}: an object with a safe-integer `block` and a string\n * `at`.\n */\nfunction isExternalBalanceReadDto(value: unknown): value is ExternalBalanceReadDto {\n return isJsonObject(value) && Number.isSafeInteger(value.block) && typeof value.at === \"string\";\n}\n\n/**\n * Reports whether `value` is an {@link ExternalHoldingDto}, per {@link isExternalBalancesDto}.\n */\nfunction isExternalHoldingDto(value: unknown): value is ExternalHoldingDto {\n return (\n isJsonObject(value) &&\n typeof value.chain === \"string\" &&\n typeof value.asset === \"string\" &&\n typeof value.symbol === \"string\" &&\n isSafeIntegerFrom(value.decimals, 0, MAX_TOKEN_DECIMALS) &&\n typeof value.amount === \"string\" &&\n DECIMAL_INTEGER_PATTERN.test(value.amount) &&\n isOptionalString(value.usd) &&\n (isAbsent(value.spendable) || typeof value.spendable === \"boolean\") &&\n (isAbsent(value.payable_mechanisms) || isStringArray(value.payable_mechanisms)) &&\n isOptionalString(value.reason) &&\n isStringArray(value.mechanisms)\n );\n}\n\n/**\n * Reports whether `value` is a {@link PayInDestinationDto}: an object with a string `asset` and `address`.\n */\nfunction isPayInDestinationDto(value: unknown): value is PayInDestinationDto {\n return isJsonObject(value) && typeof value.asset === \"string\" && typeof value.address === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link PayInLegDto}, per {@link isPayInDto}.\n */\nfunction isPayInLegDto(value: unknown): value is PayInLegDto {\n return (\n isJsonObject(value) &&\n Number.isSafeInteger(value.n) &&\n isNonEmptyString(value.status) &&\n isNonEmptyString(value.mechanism) &&\n typeof value.source_asset === \"string\" &&\n typeof value.input_amount === \"string\" &&\n typeof value.min_output === \"string\" &&\n isOptionalString(value.fee_usd) &&\n isOptionalString(value.source_tx) &&\n isOptionalString(value.destination_tx) &&\n isOptionalString(value.actual_output) &&\n isOptionalString(value.refund_tx) &&\n isOptionalString(value.refund_amount) &&\n isOptionalString(value.fail_reason) &&\n isOptionalString(value.drip)\n );\n}\n\n/**\n * Reports whether `value` has a pay-in step's base fields, per {@link isPayInDto}. Its `payload` is not checked.\n */\nfunction isPayInStepDto(value: unknown): value is PayInStepDto {\n return (\n isJsonObject(value) &&\n isNonEmptyString(value.id) &&\n Number.isSafeInteger(value.leg) &&\n isNonEmptyString(value.scheme) &&\n typeof value.chain === \"string\" &&\n isOptionalString(value.digest) &&\n typeof value.expires_at === \"string\" &&\n isNonEmptyString(value.status) &&\n isOptionalString(value.reason) &&\n isOptionalString(value.tx_hash)\n );\n}\n\n/**\n * Reports whether `value` is a {@link PayInUnspendableDto}: an object with a string `asset`, `amount` and `reason`.\n */\nfunction isPayInUnspendableDto(value: unknown): value is PayInUnspendableDto {\n return (\n isJsonObject(value) &&\n typeof value.asset === \"string\" &&\n typeof value.amount === \"string\" &&\n typeof value.reason === \"string\"\n );\n}\n\n/**\n * Reports whether every id in `requiredSteps` is the `id` of an entry of `steps`, so the step to do next can\n * always be found.\n */\nfunction namesListedSteps(requiredSteps: readonly string[], steps: readonly PayInStepDto[]): boolean {\n const listed = new Set(steps.map((step) => step.id));\n\n return requiredSteps.every((stepId) => listed.has(stepId));\n}\n\n/**\n * Reports whether `value` is a {@link RouteFeesDto}: an object with a string `platform` and `provider`.\n */\nfunction isRouteFeesDto(value: unknown): value is RouteFeesDto {\n return isJsonObject(value) && typeof value.platform === \"string\" && typeof value.provider === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link RouteEndDto}: an object with a string `asset` and `address`. Extra keys are\n * allowed, as in {@link isRouteQuoteDto}.\n */\nfunction isRouteEndDto(value: unknown): value is RouteEndDto {\n return isJsonObject(value) && typeof value.asset === \"string\" && typeof value.address === \"string\";\n}\n\n/**\n * Reports whether `value` is a {@link RouteStepDto} the client can sign: a known `role` and a\n * {@link RouteStepCallDto} `evm`.\n */\nfunction isRouteStepDto(value: unknown): value is RouteStepDto {\n return isListedRouteStepDto(value) && value.evm.chain_id === ROUTE_SOURCE_CHAIN_ID;\n}\n\n/**\n * Reports whether `value` is a step of a listed route: a known `role` and an `evm` call shaped as in\n * {@link isRouteStepCallDto}, on any chain.\n */\nfunction isListedRouteStepDto(value: unknown): value is RouteStepDto {\n return isJsonObject(value) && isMember(ROUTE_STEP_ROLES, value.role) && isRouteStepCallDto(value.evm);\n}\n\n/**\n * Reports whether `value` is shaped like a {@link RouteStepCallDto}: an object whose `chain_id` is a CAIP-2 EVM chain\n * (`eip155:` and digits), whose `to` is an EVM address, whose `data` is `0x` and whole bytes of hex, and whose `value`\n * is a decimal integer. Whether the chain is Tempo is {@link isRouteStepDto}'s check.\n */\nfunction isRouteStepCallDto(value: unknown): value is RouteStepCallDto {\n return (\n isJsonObject(value) &&\n typeof value.chain_id === \"string\" &&\n evmChainHex(value.chain_id) !== null &&\n typeof value.to === \"string\" &&\n EVM_ADDRESS_PATTERN.test(value.to) &&\n typeof value.data === \"string\" &&\n CALLDATA_PATTERN.test(value.data) &&\n typeof value.value === \"string\" &&\n DECIMAL_INTEGER_PATTERN.test(value.value)\n );\n}\n\n/**\n * Reports whether `value` is a string other than `\"\"`.\n */\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value !== \"\";\n}\n\n/**\n * Reports whether `value` is `null` or `undefined` (an absent key).\n */\nfunction isAbsent(value: unknown): value is null | undefined {\n return value === undefined || value === null;\n}\n\n/**\n * Reports whether `value` is a string, `null`, or `undefined` (an absent key).\n */\nfunction isOptionalString(value: unknown): value is string | null | undefined {\n return isAbsent(value) || typeof value === \"string\";\n}\n\n/**\n * Reports whether `value` is a string or `undefined` (an absent key), never `null`.\n */\nfunction isAbsentOrString(value: unknown): value is string | undefined {\n return value === undefined || typeof value === \"string\";\n}\n\n/**\n * Reports whether `value` is a safe integer from `min` to `max`, both included.\n */\nfunction isSafeIntegerFrom(value: unknown, min: number, max: number): value is number {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= min && value <= max;\n}\n\n/**\n * Reports whether `value` is an array of strings.\n */\nfunction isStringArray(value: unknown): value is string[] {\n return Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/**\n * Reports whether `value` is one of `members`.\n */\nfunction isMember<TMember extends string>(members: readonly TMember[], value: unknown): value is TMember {\n return members.some((member) => member === value);\n}\n\n/**\n * The registry list envelope before its entries are checked.\n */\nexport interface AssetListEnvelope {\n object: \"list\";\n data: unknown[];\n has_more: boolean;\n}\n\n/**\n * Checks the registry envelope and every entry, allowing absent or null logos.\n */\nexport function isAssetListDto(value: unknown): value is AssetListDto {\n return isAssetListEnvelope(value) && value.data.every(isAssetDto);\n}\n\n/**\n * Reports whether `value` is a registry list envelope: `object` `list`, a boolean `has_more`, and an array `data`\n * whose entries are not checked yet.\n */\nexport function isAssetListEnvelope(value: unknown): value is AssetListEnvelope {\n return isJsonObject(value) && value.object === \"list\" && typeof value.has_more === \"boolean\" && Array.isArray(value.data);\n}\n\n/**\n * Keeps only the envelope's entries that {@link isAssetDto} accepts. Spec C12: one bad row is dropped, and the rest\n * stays. A row's network name or logo that is malformed is dropped alone ({@link withValidNetworkFacts}): display facts\n * never decide whether a coin is listed.\n */\nexport function keepValidAssets(envelope: AssetListEnvelope): AssetListDto {\n return { object: \"list\", data: envelope.data.filter(isAssetDto).map(withValidNetworkFacts), has_more: envelope.has_more };\n}\n\n/**\n * `asset` without a `network_name` that is not a nonblank string or a `network_logo_url` that is not a string or null.\n * Returns `asset` itself when both are absent or valid.\n */\nfunction withValidNetworkFacts(asset: AssetDto): AssetDto {\n const nameValid =\n asset.network_name === undefined || (typeof asset.network_name === \"string\" && asset.network_name.trim() !== \"\");\n const logoValid = asset.network_logo_url === undefined || isOptionalString(asset.network_logo_url);\n if (nameValid && logoValid) return asset;\n const { network_name, network_logo_url, ...rest } = asset;\n return {\n ...rest,\n ...(nameValid && network_name !== undefined ? { network_name } : {}),\n ...(logoValid && network_logo_url !== undefined ? { network_logo_url } : {}),\n };\n}\n\n/**\n * Reports whether `value` is one {@link AssetDto} registry entry, allowing an absent or null logo.\n */\nfunction isAssetDto(value: unknown): value is AssetDto {\n return (\n isJsonObject(value) &&\n value.object === \"asset\" &&\n typeof value.asset === \"string\" &&\n typeof value.network === \"string\" &&\n typeof value.symbol === \"string\" &&\n isSafeIntegerFrom(value.decimals, 0, MAX_TOKEN_DECIMALS) &&\n isOptionalString(value.logo_url)\n );\n}\n\n/** Accept only coherent EVM checkout resolutions, with a nonzero destination. */\nexport function isCheckoutResolutionDto(value: unknown): value is CheckoutResolutionDto {\n if (\n !isJsonObject(value) ||\n value.object !== \"checkout_resolution\" ||\n typeof value.asset !== \"string\" ||\n !/^eip155:[1-9][0-9]*\\/(?:erc20:0x[0-9a-fA-F]{40}|slip44:[0-9]+)$/.test(value.asset) ||\n typeof value.address !== \"string\" ||\n !EVM_ADDRESS_PATTERN.test(value.address) ||\n /^0x0{40}$/i.test(value.address) ||\n !isNonEmptyString(value.symbol) ||\n typeof value.default !== \"boolean\" ||\n typeof value.registered !== \"boolean\" ||\n !(value.decimals === undefined || Number.isSafeInteger(value.decimals)) ||\n !isOptionalString(value.usd_price)\n )\n return false;\n if (!value.registered) return value.rule_id === null && value.payee === null && !value.default;\n return (\n typeof value.rule_id === \"string\" &&\n /^ckr_.+/.test(value.rule_id) &&\n isJsonObject(value.payee) &&\n isNonEmptyString(value.payee.name)\n );\n}\n","import type { ServerTimeSink } from \"#/time/types\";\n\nimport { UPSTREAM_DATE_HEADER } from \"./constants\";\n\n/**\n * The time a date header names, in ms since the epoch, or `null` when the header is absent or does not parse.\n */\nfunction parseDateHeader(value: string | null): number | null {\n if (value === null || value.trim() === \"\") {\n return null;\n }\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * The server's time a response carries: `X-Stridge-Upstream-Date` (the hub proxy's copy of the Coordinator's `Date`)\n * when it parses, else `Date`, else `null`.\n */\nexport function readServerTimeMs(headers: Headers): number | null {\n return parseDateHeader(headers.get(UPSTREAM_DATE_HEADER)) ?? parseDateHeader(headers.get(\"Date\"));\n}\n\n/**\n * Hands `sink` the server time `headers` carry, with the device's send and receipt times. Does nothing without a sink\n * or without a parseable date, and swallows what the sink throws, so a sink never fails a call.\n */\nexport function reportServerTime(\n sink: ServerTimeSink | undefined,\n headers: Headers,\n sentAtMs: number,\n receivedAtMs: number,\n): void {\n if (sink === undefined) {\n return;\n }\n const serverTimeMs = readServerTimeMs(headers);\n if (serverTimeMs === null) {\n return;\n }\n try {\n sink({ serverTimeMs, sentAtMs, receivedAtMs });\n } catch {\n return;\n }\n}\n","import { CsrfStoreError } from \"#/errors/CsrfStoreError\";\nimport { isErrorEnvelopeDto } from \"#/errors/guards\";\nimport { parseBody } from \"#/errors/json\";\nimport { toSuaError } from \"#/errors/parseSuaError\";\nimport { SuaNetworkError } from \"#/errors/SuaNetworkError\";\nimport type {\n CheckoutResolutionDto,\n CheckoutResolveRequestDto,\n AdjustPayInRequestDto,\n CheckoutQuoteRequestDto,\n ConfirmPayInRequestDto,\n ExternalBalancesDto,\n ExternalBalancesRequestDto,\n PayInChainCapabilitiesDto,\n PayInDto,\n TopUpQuoteRequestDto,\n PayInStepSignatureDto,\n PayInStepTxHashDto,\n PayInWalletDescriptorDto,\n PayInWalletsDto,\n AnswerWalletOfferRequestDto,\n ExternalAccountDto,\n GuestCookieScopeDto,\n GuestHandoffDto,\n GuestMergeRequestDto,\n GuestDto,\n MarkExternalAccountUsedRequestDto,\n OpenGuestRequestDto,\n RegisterKeypairRequestDto,\n RegisterKeypairResultDto,\n RelayRequestDto,\n RelayResponseDto,\n RoundDto,\n RouteDto,\n RouteListDto,\n RouteQuoteDto,\n RouteRequestDto,\n RouteSourceRequestDto,\n SaveExternalAccountRequestDto,\n SessionDto,\n StartRoundRequestDto,\n StartRoundResponseDto,\n VerifyRoundRequestDto,\n VerifyRoundResponseDto,\n WalletDto,\n} from \"#/models\";\nimport { ROUTE_STATES } from \"#/models/Route/entities/RouteStateDto\";\nimport { GUEST_COOKIE_ACCESS_HEADER, SESSION_HEADER, SESSION_HEADER_OMIT } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport type { ServerTimeSink } from \"#/time/types\";\n\nimport { APP_HEADER, CSRF_HEADER, IDEMPOTENCY_HEADER, MAX_IDEMPOTENCY_KEY_LENGTH, MAX_ROUTE_LIST_LIMIT } from \"./constants\";\nimport { hubTarget, type HubMethod } from \"./endpoints\";\nimport {\n isCheckoutResolutionDto,\n type AssetListEnvelope,\n isAssetListEnvelope,\n isExternalBalancesDto,\n isPayInDto,\n isRouteDto,\n isRouteListDto,\n isRouteQuoteDto,\n isRouteStateDto,\n keepValidAssets,\n} from \"./guards\";\nimport { reportServerTime } from \"./serverTime\";\n\nimport type {\n CoordinatorCallOptions,\n CoordinatorClient,\n CoordinatorClientOptions,\n CsrfAccessor,\n FetchLike,\n GuestCallOptions,\n GuestReadCallOptions,\n ListRoutesQuery,\n} from \"./types\";\n\n/**\n * Every request body the client sends: one request Dto per route that takes a body.\n */\ntype RequestBodyDto =\n | CheckoutResolveRequestDto\n | StartRoundRequestDto\n | VerifyRoundRequestDto\n | RegisterKeypairRequestDto\n | RelayRequestDto\n | SaveExternalAccountRequestDto\n | MarkExternalAccountUsedRequestDto\n | RouteRequestDto\n | RouteSourceRequestDto\n | GuestMergeRequestDto\n | OpenGuestRequestDto\n | AnswerWalletOfferRequestDto\n | ExternalBalancesRequestDto\n | TopUpQuoteRequestDto\n | ConfirmPayInRequestDto\n | AdjustPayInRequestDto;\n\n/**\n * The credentials one route sends. Every route states them, so a guest call can never carry the session token and the\n * offer answer can never carry the guest token.\n */\ntype RouteCredentials =\n /**\n * The cookies, and the stored session token as `X-CSRF-Token` on every `POST`, `PUT` and `DELETE`\n * (`omitCredentials` sends no token, and `X-Stridge-Session: omit` so the hub proxy drops the session cookie).\n */\n | { kind: \"session\" }\n /**\n * The cookies, and exactly this session token as `X-CSRF-Token`. The stored token is never read.\n */\n | { kind: \"pinned-session\"; token: string }\n /**\n * The cookies only. The stored token is never read.\n */\n | { kind: \"guest-open\" }\n /** The cookies and guest cookie scope only; reads never carry a CSRF token. */\n | { kind: \"guest-read\"; cookieAccess: GuestCookieScopeDto }\n /**\n * The cookies, the guest's token as `X-CSRF-Token` and its scope as `X-Stridge-Cookie-Access`. The stored session\n * token is never read.\n */\n | { kind: \"guest\"; token: string; cookieAccess: GuestCookieScopeDto };\n\n/**\n * The credentials of every session route.\n */\nconst SESSION: RouteCredentials = { kind: \"session\" };\n\n/**\n * The header names only the transport writes, from a route's {@link RouteCredentials}. A route header naming one is a\n * programming error.\n */\nconst CREDENTIAL_HEADERS: ReadonlySet<string> = new Set([\n CSRF_HEADER.toLowerCase(),\n GUEST_COOKIE_ACCESS_HEADER.toLowerCase(),\n SESSION_HEADER.toLowerCase(),\n]);\n\n/**\n * A transaction hash as `POST /wallet/v1/routes/{id}/source` takes it: `0x` and 32 bytes of hex, either case.\n */\nconst TX_HASH_PATTERN = /^0x[0-9a-fA-F]{64}$/;\n\n/**\n * An idempotency key the client sends: visible ASCII only (`!` through `~`), so its length in characters is its\n * length in bytes, which is what the Coordinator bounds, and no header rule trims or refuses it.\n */\nconst IDEMPOTENCY_KEY_PATTERN = /^[\\x21-\\x7E]+$/;\n\n/**\n * One call to a hub API route, as the methods describe it to {@link Transport.send}.\n */\ninterface RouteCall {\n /**\n * The HTTP verb.\n */\n method: HubMethod;\n\n /**\n * The path after `baseUrl` (`/wallet/v1/…` or `/pay/v1/…`, from `hubTarget`), ids already encoded, with its query\n * string when the route takes one.\n */\n path: string;\n\n /**\n * The JSON body, built key by key by the method. Omitted for a call without a body.\n */\n body?: RequestBodyDto;\n\n /**\n * Whether the route requires `X-Stridge-App`.\n */\n sendsApp?: boolean;\n\n /**\n * Headers the route takes beyond the shared ones (`Idempotency-Key` on `openRoute`), already checked by the\n * method. Never one the transport sets itself.\n */\n headers?: Readonly<Record<string, string>>;\n\n /**\n * The credentials the route sends, written after every other header.\n */\n credentials: RouteCredentials;\n\n /**\n * The shape check a `2xx` answer must pass, beyond being a JSON object. A body that fails it is an unusable\n * answer. Omitted on the routes whose fields are not validated.\n */\n isAnswer?: (value: unknown) => boolean;\n\n /**\n * Whether the caller ignores the route's answer (sign-out, mark a linked wallet used, the deletes, the warms). On such a route any `2xx`\n * that is not the error envelope resolves `undefined`; on every other route a `204` is an unusable answer.\n */\n noContent?: boolean;\n\n /**\n * The caller's per-call options: its abort signal, and whether to send the request without credentials (session\n * routes only).\n */\n callOptions?: CoordinatorCallOptions;\n}\n\n/**\n * The validated options every method closes over.\n */\ninterface Transport {\n /**\n * Sends one call and reads its answer per the rules on {@link CoordinatorClient}.\n */\n send(call: RouteCall): Promise<unknown>;\n}\n\n/**\n * Creates the Coordinator client: one method per hub API route the hub uses, with the shared request and answer rules\n * documented on {@link CoordinatorClient}.\n *\n * Validates the options once, up front:\n *\n * - `baseUrl` must parse with `new URL(baseUrl)` as an absolute `http:` or `https:` URL with no query and no fragment.\n * Trailing slashes are removed; any path prefix is kept.\n * - `appId` must be a non-empty string. Its format is not checked (the Coordinator answers `403 APP_SUSPENDED` for a\n * bad one).\n * - `csrf` must have `get` and `set` functions.\n * - `fetch` defaults to `globalThis.fetch`, read now. It is always called as a plain function, never as a method\n * of the options object.\n * - `onServerTime`, when given, must be a function. It too is called as a plain function.\n *\n * Creating the client sends nothing.\n *\n * @throws {TypeError} when an option breaks one of those rules, or no `fetch` is available.\n */\nexport function createCoordinatorClient(options: CoordinatorClientOptions): CoordinatorClient {\n if (!isJsonObject(options)) {\n throw new TypeError(\"createCoordinatorClient: options must be an object\");\n }\n\n const baseUrl = normaliseBaseUrl(options.baseUrl);\n const appId = options.appId;\n if (typeof appId !== \"string\" || appId === \"\") {\n throw new TypeError(\"createCoordinatorClient: appId must be a non-empty string\");\n }\n\n const csrf = options.csrf;\n if (!isJsonObject(csrf) || typeof csrf.get !== \"function\" || typeof csrf.set !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: csrf must have get and set functions\");\n }\n\n const fetchFn: FetchLike | undefined = options.fetch ?? globalThis.fetch;\n if (typeof fetchFn !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: no fetch is available; pass options.fetch\");\n }\n\n const onServerTime = options.onServerTime;\n if (onServerTime !== undefined && typeof onServerTime !== \"function\") {\n throw new TypeError(\"createCoordinatorClient: onServerTime must be a function\");\n }\n\n const transport = createTransport(baseUrl, appId, csrf, fetchFn, onServerTime);\n\n return {\n baseUrl,\n appId,\n\n async startRound(input, callOptions) {\n const body: StartRoundRequestDto = {};\n if (input.email !== undefined) {\n body.method = \"email\";\n body.email = input.email;\n }\n\n return (await transport.send({\n ...hubTarget(\"startRound\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as StartRoundResponseDto;\n },\n\n async getRound(roundId, callOptions) {\n return (await transport.send({\n ...hubTarget(\"getRound\", encodeURIComponent(roundId)),\n credentials: SESSION,\n\n callOptions,\n })) as RoundDto;\n },\n\n async verifyRound(roundId, request, callOptions) {\n const body: VerifyRoundRequestDto = { encrypted_otp_bundle: request.encrypted_otp_bundle };\n const answer = (await transport.send({\n ...hubTarget(\"verifyRound\", encodeURIComponent(roundId)),\n body,\n credentials: SESSION,\n\n callOptions,\n })) as VerifyRoundResponseDto;\n\n const token = answer.csrf_token;\n if (typeof token === \"string\" && token !== \"\") {\n try {\n await csrf.set(token);\n } catch (cause) {\n throw new CsrfStoreError(answer, cause);\n }\n }\n\n return answer;\n },\n\n async registerKeypair(request, callOptions) {\n const body: RegisterKeypairRequestDto = {\n round_id: request.round_id,\n stamped_body: request.stamped_body,\n attested_stamp: request.attested_stamp,\n };\n\n return (await transport.send({\n ...hubTarget(\"registerKeypair\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as RegisterKeypairResultDto;\n },\n\n async getSession(callOptions) {\n return (await transport.send({\n ...hubTarget(\"getSession\"),\n credentials: SESSION,\n\n callOptions,\n })) as SessionDto;\n },\n\n async getWallet(callOptions) {\n return (await transport.send({\n ...hubTarget(\"getWallet\"),\n sendsApp: true,\n credentials: SESSION,\n\n callOptions,\n })) as WalletDto;\n },\n\n async relay(request, callOptions) {\n const pinned = callOptions !== undefined && \"sessionCsrfToken\" in callOptions;\n const token: unknown = pinned ? callOptions.sessionCsrfToken : undefined;\n if (pinned && (typeof token !== \"string\" || token === \"\")) {\n throw new TypeError(\"relay: sessionCsrfToken must be a non-empty string\");\n }\n const body: RelayRequestDto = {\n body: request.body,\n stamp_header: {\n name: request.stamp_header.name,\n value: request.stamp_header.value,\n },\n purpose: request.purpose,\n };\n\n return (await transport.send({\n ...hubTarget(\"relay\"),\n body,\n sendsApp: true,\n credentials: typeof token === \"string\" ? { kind: \"pinned-session\", token } : SESSION,\n callOptions: pinned ? toSignalOnly(callOptions) : callOptions,\n })) as RelayResponseDto;\n },\n\n async signOut(callOptions) {\n await transport.send({\n ...hubTarget(\"signOut\"),\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async saveExternalAccount(request, callOptions) {\n const pinned = callOptions !== undefined && \"sessionCsrfToken\" in callOptions;\n const token: unknown = pinned ? callOptions.sessionCsrfToken : undefined;\n if (pinned && (typeof token !== \"string\" || token === \"\")) {\n throw new TypeError(\"saveExternalAccount: sessionCsrfToken must be a non-empty string\");\n }\n return (await transport.send({\n ...hubTarget(\"saveExternalAccount\"),\n body: buildSaveExternalAccountBody(request),\n sendsApp: true,\n credentials: typeof token === \"string\" ? { kind: \"pinned-session\", token } : SESSION,\n callOptions: pinned ? toSignalOnly(callOptions) : callOptions,\n })) as ExternalAccountDto;\n },\n\n async markExternalAccountUsed(walletId, request, callOptions) {\n const lastChainId = request?.last_chain_id;\n await transport.send({\n ...hubTarget(\"markExternalAccountUsed\", encodeURIComponent(walletId)),\n ...(lastChainId === undefined ? {} : { body: { last_chain_id: lastChainId } }),\n sendsApp: true,\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async removeExternalAccount(walletId, callOptions) {\n await transport.send({\n ...hubTarget(\"removeExternalAccount\", encodeURIComponent(walletId)),\n sendsApp: true,\n noContent: true,\n credentials: SESSION,\n\n callOptions,\n });\n },\n\n async quoteRoute(request, callOptions) {\n return (await transport.send({\n ...hubTarget(\"quoteRoute\"),\n body: buildRouteRequestBody(request),\n sendsApp: true,\n isAnswer: isRouteQuoteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteQuoteDto;\n },\n\n async openRoute(request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"openRoute\", callOptions?.idempotencyKey);\n\n return (await transport.send({\n ...hubTarget(\"openRoute\"),\n body: buildRouteOpenBody(request),\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async getRoute(routeId, callOptions) {\n return (await transport.send({\n ...hubTarget(\"getRoute\", encodePathId(\"getRoute\", \"routeId\", routeId)),\n sendsApp: true,\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async listAssets(callOptions) {\n return keepValidAssets(\n (await transport.send({\n ...hubTarget(\"listAssets\"),\n sendsApp: true,\n isAnswer: isAssetListEnvelope,\n credentials: SESSION,\n callOptions,\n })) as AssetListEnvelope,\n );\n },\n\n async listGuestAssets(callOptions) {\n return keepValidAssets(\n (await transport.send({\n ...hubTarget(\"listGuestAssets\"),\n sendsApp: true,\n isAnswer: isAssetListEnvelope,\n credentials: checkGuestReadCredentials(\"listGuestAssets\", callOptions),\n callOptions,\n })) as AssetListEnvelope,\n );\n },\n\n async listRoutes(query, callOptions) {\n return (await transport.send({\n ...hubTarget(\"listRoutes\", undefined, buildRouteListQuery(query)),\n sendsApp: true,\n isAnswer: isRouteListDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteListDto;\n },\n\n async reportRouteSource(routeId, request, callOptions) {\n const tx = request.tx;\n if (typeof tx !== \"string\" || !TX_HASH_PATTERN.test(tx)) {\n throw new TypeError(\"reportRouteSource: tx must be 0x followed by 64 hex digits\");\n }\n const body: RouteSourceRequestDto = { tx };\n\n return (await transport.send({\n ...hubTarget(\"reportRouteSource\", encodePathId(\"reportRouteSource\", \"routeId\", routeId)),\n body,\n sendsApp: true,\n isAnswer: isRouteDto,\n credentials: SESSION,\n\n callOptions,\n })) as RouteDto;\n },\n\n async openGuest(request, callOptions) {\n const body: OpenGuestRequestDto = { cookie_access: request.cookie_access };\n\n return (await transport.send({\n ...hubTarget(\"openGuest\"),\n body,\n sendsApp: true,\n credentials: { kind: \"guest-open\" },\n callOptions: toSignalOnly(callOptions),\n })) as GuestDto;\n },\n\n async createGuestHandoff(options) {\n return (await transport.send({\n ...hubTarget(\"createGuestHandoff\"),\n credentials: checkGuestCredentials(\"createGuestHandoff\", options),\n sendsApp: true,\n callOptions: toSignalOnly(options),\n })) as GuestHandoffDto;\n },\n\n async mergeGuestSession(request, options) {\n await transport.send({\n ...hubTarget(\"mergeGuestSession\"),\n body: { handoff: request.handoff },\n credentials: checkGuestCredentials(\"mergeGuestSession\", options),\n noContent: true,\n sendsApp: true,\n callOptions: toSignalOnly(options),\n });\n },\n\n async saveGuestWallet(request, callOptions) {\n const credentials = checkGuestCredentials(\"saveGuestWallet\", callOptions);\n\n return (await transport.send({\n ...hubTarget(\"saveGuestWallet\"),\n body: buildSaveExternalAccountBody(request),\n sendsApp: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalAccountDto;\n },\n\n async removeGuestWallet(walletId, callOptions) {\n const credentials = checkGuestCredentials(\"removeGuestWallet\", callOptions);\n await transport.send({\n ...hubTarget(\"removeGuestWallet\", encodeURIComponent(walletId)),\n sendsApp: true,\n noContent: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n });\n },\n\n async markGuestWalletUsed(walletId, request, callOptions) {\n const credentials = checkGuestCredentials(\"markGuestWalletUsed\", callOptions);\n const lastChainId = request?.last_chain_id;\n return (await transport.send({\n ...hubTarget(\"markGuestWalletUsed\", encodeURIComponent(walletId)),\n ...(lastChainId === undefined ? {} : { body: { last_chain_id: lastChainId } }),\n sendsApp: true,\n credentials,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalAccountDto;\n },\n\n async answerWalletOffer(request, callOptions) {\n const token: unknown = callOptions?.sessionCsrfToken;\n if (typeof token !== \"string\" || token === \"\") {\n throw new TypeError(\"answerWalletOffer: sessionCsrfToken must be a non-empty string\");\n }\n const accept = readWalletIds(\"accept_guest_accounts\", request?.accept_guest_accounts ?? null) ?? [];\n const discard = readWalletIds(\"discard_guest_accounts\", request?.discard_guest_accounts);\n const shown = readWalletIds(\"shown\", request?.shown);\n const body: AnswerWalletOfferRequestDto = { accept_guest_accounts: accept };\n if (discard !== undefined) body.discard_guest_accounts = discard;\n if (shown !== undefined) body.shown = shown;\n\n return (await transport.send({\n ...hubTarget(\"answerWalletOffer\"),\n body,\n sendsApp: true,\n credentials: { kind: \"pinned-session\", token },\n callOptions: toSignalOnly(callOptions),\n })) as SessionDto;\n },\n\n async resolveGuestCheckout(request, callOptions) {\n const body: CheckoutResolveRequestDto = {};\n if (request.asset !== undefined) body.asset = request.asset;\n if (request.destination !== undefined) body.destination = request.destination;\n return (await transport.send({\n ...hubTarget(\"resolveGuestCheckout\"),\n body,\n sendsApp: true,\n credentials: checkGuestCredentials(\"resolveGuestCheckout\", callOptions),\n isAnswer: isCheckoutResolutionDto,\n callOptions: toSignalOnly(callOptions),\n })) as CheckoutResolutionDto;\n },\n\n async resolveCheckout(request, callOptions) {\n const body: CheckoutResolveRequestDto = {};\n if (request.asset !== undefined) body.asset = request.asset;\n if (request.destination !== undefined) body.destination = request.destination;\n return (await transport.send({\n ...hubTarget(\"resolveCheckout\"),\n body,\n sendsApp: true,\n credentials: SESSION,\n isAnswer: isCheckoutResolutionDto,\n callOptions: callOptions,\n })) as CheckoutResolutionDto;\n },\n\n async warmGuestExternalBalances(request, callOptions) {\n await transport.send({\n credentials: checkGuestCredentials(\"warmGuestExternalBalances\", callOptions),\n ...hubTarget(\"warmGuestExternalBalances\"),\n body: buildExternalBalancesBody(request),\n sendsApp: true,\n noContent: true,\n callOptions: toSignalOnly(callOptions),\n });\n },\n\n async warmExternalBalances(request, callOptions) {\n await transport.send({\n credentials: SESSION,\n ...hubTarget(\"warmExternalBalances\"),\n body: buildExternalBalancesBody(request),\n sendsApp: true,\n noContent: true,\n callOptions,\n });\n },\n\n async getGuestExternalBalances(request, callOptions) {\n return (await transport.send({\n credentials: checkGuestReadCredentials(\"getGuestExternalBalances\", callOptions),\n ...hubTarget(\"getGuestExternalBalances\", undefined, buildExternalBalancesQuery(request)),\n sendsApp: true,\n isAnswer: isExternalBalancesDto,\n callOptions: toSignalOnly(callOptions),\n })) as ExternalBalancesDto;\n },\n\n async getExternalBalances(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"getExternalBalances\", undefined, buildExternalBalancesQuery(request)),\n sendsApp: true,\n isAnswer: isExternalBalancesDto,\n callOptions,\n })) as ExternalBalancesDto;\n },\n\n async quoteGuestPayIn(request, callOptions) {\n return (await transport.send({\n credentials: checkGuestCredentials(\"quoteGuestPayIn\", callOptions),\n ...hubTarget(\"quoteGuestPayIn\"),\n body: buildCheckoutQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async quoteCheckout(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"quoteCheckout\"),\n body: buildCheckoutQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async quoteTopUp(request, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"quoteTopUp\"),\n body: buildTopUpQuoteBody(request),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async confirmGuestPayIn(payInId, request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"confirmGuestPayIn\", callOptions?.idempotencyKey);\n const body: ConfirmPayInRequestDto = {\n signatures: buildSignatureBatch(\"confirmGuestPayIn\", request, { allowTxHash: false, allowEmpty: true }),\n };\n\n return (await transport.send({\n credentials: checkGuestCredentials(\"confirmGuestPayIn\", callOptions),\n ...hubTarget(\"confirmGuestPayIn\", encodePathId(\"confirmGuestPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async confirmPayIn(payInId, request, callOptions) {\n const idempotencyKey = checkIdempotencyKey(\"confirmPayIn\", callOptions?.idempotencyKey);\n const body: ConfirmPayInRequestDto = {\n signatures: buildSignatureBatch(\"confirmPayIn\", request, { allowTxHash: false, allowEmpty: true }),\n };\n\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"confirmPayIn\", encodePathId(\"confirmPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n headers: { [IDEMPOTENCY_HEADER]: idempotencyKey },\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async adjustGuestPayIn(payInId, request, callOptions) {\n const body: AdjustPayInRequestDto = {\n signatures: buildSignatureBatch(\"adjustGuestPayIn\", request, { allowTxHash: true, allowEmpty: false }),\n };\n\n return (await transport.send({\n credentials: checkGuestCredentials(\"adjustGuestPayIn\", callOptions),\n ...hubTarget(\"adjustGuestPayIn\", encodePathId(\"adjustGuestPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async adjustPayIn(payInId, request, callOptions) {\n const body: AdjustPayInRequestDto = {\n signatures: buildSignatureBatch(\"adjustPayIn\", request, { allowTxHash: true, allowEmpty: false }),\n };\n\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"adjustPayIn\", encodePathId(\"adjustPayIn\", \"payInId\", payInId)),\n body,\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async cancelGuestPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: checkGuestCredentials(\"cancelGuestPayIn\", callOptions),\n ...hubTarget(\"cancelGuestPayIn\", encodePathId(\"cancelGuestPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async cancelPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"cancelPayIn\", encodePathId(\"cancelPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n\n async getGuestPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: checkGuestReadCredentials(\"getGuestPayIn\", callOptions),\n ...hubTarget(\"getGuestPayIn\", encodePathId(\"getGuestPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions: toSignalOnly(callOptions),\n })) as PayInDto;\n },\n\n async getPayIn(payInId, callOptions) {\n return (await transport.send({\n credentials: SESSION,\n ...hubTarget(\"getPayIn\", encodePathId(\"getPayIn\", \"payInId\", payInId)),\n sendsApp: true,\n isAnswer: isPayInDto,\n callOptions,\n })) as PayInDto;\n },\n };\n}\n\n/**\n * Keeps only the caller's abort signal from per-call options: the guest and pinned routes take no other option.\n */\nfunction toSignalOnly(options: { signal?: AbortSignal } | undefined): CoordinatorCallOptions | undefined {\n return options?.signal === undefined ? undefined : { signal: options.signal };\n}\n\n/**\n * Checks a guest write's credentials and returns them.\n *\n * @throws {TypeError} when `guestCsrfToken` is not a non-empty string or `cookieAccess` is not a guest cookie scope.\n */\nfunction checkGuestCredentials(method: string, options: GuestCallOptions | undefined): RouteCredentials {\n const token: unknown = options?.guestCsrfToken;\n if (typeof token !== \"string\" || token === \"\") {\n throw new TypeError(`${method}: guestCsrfToken must be a non-empty string`);\n }\n const cookieAccess: unknown = options?.cookieAccess;\n if (cookieAccess !== \"unpartitioned\" && cookieAccess !== \"partitioned\") {\n throw new TypeError(`${method}: cookieAccess must be \"unpartitioned\" or \"partitioned\"`);\n }\n return { kind: \"guest\", token, cookieAccess };\n}\n\n/** Validates the cookie scope of a guest read without requiring or reading any token. */\nfunction checkGuestReadCredentials(method: string, options: GuestReadCallOptions | undefined): RouteCredentials {\n const cookieAccess: unknown = options?.cookieAccess;\n if (cookieAccess !== \"unpartitioned\" && cookieAccess !== \"partitioned\") {\n throw new TypeError(`${method}: cookieAccess must be \"unpartitioned\" or \"partitioned\"`);\n }\n return { kind: \"guest-read\", cookieAccess };\n}\n\n/**\n * Builds the body of `saveExternalAccount` and `saveGuestWallet` key by key: `chain_kind`, `address`, `wallet_brand`,\n * `connector`, `saved_via`, and the optional fields `display_name`, `last_chain_id` and `reconnect` when defined.\n */\nfunction buildSaveExternalAccountBody(request: SaveExternalAccountRequestDto): SaveExternalAccountRequestDto {\n return {\n chain_kind: request.chain_kind,\n address: request.address,\n wallet_brand: request.wallet_brand,\n connector: request.connector,\n ...(request.display_name === undefined ? {} : { display_name: request.display_name }),\n ...(request.last_chain_id === undefined ? {} : { last_chain_id: request.last_chain_id }),\n saved_via: request.saved_via,\n ...(request.reconnect === undefined ? {} : { reconnect: request.reconnect }),\n };\n}\n\n/**\n * A copy of one wallet-id list of the offer answer, or `undefined` when the caller left it out. Anything else that is\n * not an array of strings (`null` included) throws before sending.\n */\nfunction readWalletIds(field: string, value: unknown): string[] | undefined {\n if (value === undefined) return undefined;\n if (!Array.isArray(value) || !value.every((id) => typeof id === \"string\")) {\n throw new TypeError(`answerWalletOffer: ${field} must be an array of wallet ids`);\n }\n return [...value];\n}\n\n/**\n * Builds the body of `quoteRoute` key by key: `source.asset`, `source.amount`, `destination.asset`, then\n * `destination.address` only when it is defined. A quote never carries `purpose` or `payment_ref`.\n */\nfunction buildRouteRequestBody(request: RouteRequestDto): RouteRequestDto {\n const destination = request.destination;\n\n return {\n source: { asset: request.source.asset, amount: request.source.amount },\n destination:\n destination.address === undefined\n ? { asset: destination.asset }\n : { asset: destination.asset, address: destination.address },\n };\n}\n\n/**\n * Builds the body of `openRoute`: the quote body ({@link buildRouteRequestBody}), then `purpose` and `payment_ref`, each\n * only when it is defined. The key order is fixed: the Coordinator compares the body's bytes under one idempotency key.\n */\nfunction buildRouteOpenBody(request: RouteRequestDto): RouteRequestDto {\n return {\n ...buildRouteRequestBody(request),\n ...(request.purpose === undefined ? {} : { purpose: request.purpose }),\n ...(request.payment_ref === undefined ? {} : { payment_ref: request.payment_ref }),\n };\n}\n\n/**\n * Builds the body of `warmExternalBalances` and `warmGuestExternalBalances`: exactly `wallets`.\n */\nfunction buildExternalBalancesBody(request: ExternalBalancesRequestDto): ExternalBalancesRequestDto {\n return { wallets: buildPayInWallets(request.wallets) };\n}\n\n/**\n * Builds the query of `getExternalBalances` and `getGuestExternalBalances` from the request's `wallets`: `evm` and\n * `svm`, then JSON `wallet` and its optional checkout target. Each value is URI-encoded.\n */\nfunction buildExternalBalancesQuery(request: ExternalBalancesRequestDto): string {\n const wallets = buildPayInWallets(request.wallets);\n const parts: string[] = [];\n if (wallets.evm !== undefined) {\n parts.push(`evm=${encodeURIComponent(wallets.evm)}`);\n }\n if (wallets.svm !== undefined) {\n parts.push(`svm=${encodeURIComponent(wallets.svm)}`);\n }\n\n if (request.wallet !== undefined) {\n parts.push(`wallet=${encodeURIComponent(JSON.stringify(buildWalletDescriptor(request.wallet)))}`);\n if (request.asset !== undefined && request.destination !== undefined) {\n parts.push(`asset=${encodeURIComponent(request.asset)}`, `destination=${encodeURIComponent(request.destination)}`);\n }\n }\n\n return parts.length === 0 ? \"\" : `?${parts.join(\"&\")}`;\n}\n\n/**\n * Builds a pay-in call's `wallets` key by key: `evm` and `svm`, only when defined.\n */\nfunction buildPayInWallets(wallets: PayInWalletsDto): PayInWalletsDto {\n const body: PayInWalletsDto = {};\n if (wallets.evm !== undefined) {\n body.evm = wallets.evm;\n }\n\n if (wallets.svm !== undefined) {\n body.svm = wallets.svm;\n }\n\n return body;\n}\n\n/**\n * Builds `quoteTopUp`'s body key by key: `wallets`, then `wallet` only when it is defined, then `asset` and `amount`,\n * then `sources` and `source_chains` when defined. Never a `destination`.\n */\nfunction buildTopUpQuoteBody(request: TopUpQuoteRequestDto): TopUpQuoteRequestDto {\n return {\n wallets: buildPayInWallets(request.wallets),\n ...(request.wallet === undefined ? {} : { wallet: buildWalletDescriptor(request.wallet) }),\n asset: request.asset,\n amount: request.amount,\n ...(request.sources === undefined ? {} : { sources: [...request.sources] }),\n ...(request.source_chains === undefined ? {} : { source_chains: [...request.source_chains] }),\n };\n}\n\n/** Builds a checkout with an explicit destination and the wallet's complete capabilities answer. */\nfunction buildCheckoutQuoteBody(request: CheckoutQuoteRequestDto): CheckoutQuoteRequestDto {\n const wallet = request.wallet;\n return {\n wallets: buildPayInWallets(request.wallets),\n ...(wallet === undefined\n ? {}\n : {\n wallet: {\n kind: wallet.kind,\n ...(wallet.name === undefined ? {} : { name: wallet.name }),\n ...(wallet.capabilities === undefined ? {} : { capabilities: wallet.capabilities }),\n },\n }),\n asset: request.asset,\n amount: request.amount,\n ...(request.sources === undefined ? {} : { sources: [...request.sources] }),\n ...(request.source_chains === undefined ? {} : { source_chains: [...request.source_chains] }),\n destination: request.destination,\n };\n}\n\n/**\n * Builds a quote's `wallet` key by key: `kind`, then `name` and `capabilities` only when they are defined.\n */\nfunction buildWalletDescriptor(wallet: PayInWalletDescriptorDto): PayInWalletDescriptorDto {\n return {\n kind: wallet.kind,\n ...(wallet.name === undefined ? {} : { name: wallet.name }),\n ...(wallet.capabilities === undefined ? {} : { capabilities: buildCapabilities(wallet.capabilities) }),\n };\n}\n\n/**\n * Copies a `wallet_getCapabilities` answer chain by chain, in its own order, with {@link buildChainCapabilities}. The\n * answer comes from the wallet unchecked, so a `capabilities` that is not an object is sent as it is, for the\n * Coordinator to refuse as `400 WALLET_MALFORMED`; the quote then goes out again without `wallet`.\n */\nfunction buildCapabilities(\n capabilities: Record<string, PayInChainCapabilitiesDto | null>,\n): Record<string, PayInChainCapabilitiesDto | null> {\n const value: unknown = capabilities;\n if (!isJsonObject(value)) {\n return capabilities;\n }\n\n return Object.fromEntries(Object.entries(capabilities).map(([chainId, chain]) => [chainId, buildChainCapabilities(chain)]));\n}\n\n/**\n * Copies one chain's capabilities, keeping only the three the Coordinator reads, each only when it is defined:\n * `alternateGasFees` and `paymasterService` as `{ supported }`, and `atomic` as `{ status }`. A wallet reports many\n * more, which never reach the wire. A `null` chain stays `null`; a chain or a capability that is not an object is sent\n * as it is, for the Coordinator to refuse as `400 WALLET_MALFORMED`.\n */\nfunction buildChainCapabilities(chain: PayInChainCapabilitiesDto | null): PayInChainCapabilitiesDto | null {\n const value: unknown = chain;\n if (chain === null || !isJsonObject(value)) {\n return chain;\n }\n\n const copy: PayInChainCapabilitiesDto = {};\n if (chain.alternateGasFees !== undefined) {\n copy.alternateGasFees = buildSupportCapability(chain.alternateGasFees);\n }\n if (chain.paymasterService !== undefined) {\n copy.paymasterService = buildSupportCapability(chain.paymasterService);\n }\n if (chain.atomic !== undefined) {\n const atomic: unknown = chain.atomic;\n copy.atomic = isJsonObject(atomic) ? { status: chain.atomic.status } : chain.atomic;\n }\n\n return copy;\n}\n\n/**\n * Copies a `{ supported }` capability: exactly `supported`, or the value as it is when it is not an object.\n */\nfunction buildSupportCapability(capability: { supported: boolean }): { supported: boolean } {\n const value: unknown = capability;\n\n return isJsonObject(value) ? { supported: capability.supported } : capability;\n}\n\n/**\n * What a signature batch may hold: `confirmPayIn` takes signatures only and may be empty, `adjustPayIn` takes\n * signatures and sent transactions' hashes and may not.\n */\ninterface SignatureBatchRules {\n /**\n * Whether an item may carry a `tx_hash`.\n */\n allowTxHash: boolean;\n\n /**\n * Whether the batch may hold no item.\n */\n allowEmpty: boolean;\n}\n\n/**\n * Builds a confirm or adjust batch, item by item and key by key: `step_id` then `signature`, or `step_id` then\n * `tx_hash`. Nothing about a step's own signature is checked here beyond being a non-empty string; the Coordinator\n * checks the rest (`422 SIGNATURE_BATCH_INVALID`).\n *\n * @throws {TypeError} when `request.signatures` is not an array, or is empty where `rules` say it may not be, or an\n * item is not an object, has an empty `step_id`, carries both or neither of `signature` and `tx_hash`, carries an\n * empty `signature`, a `tx_hash` that is not `0x` followed by 64 hex digits, or a `tx_hash` where `rules` refuse\n * one.\n */\nfunction buildSignatureBatch(\n method: \"confirmPayIn\" | \"confirmGuestPayIn\",\n request: ConfirmPayInRequestDto,\n rules: SignatureBatchRules & { allowTxHash: false },\n): PayInStepSignatureDto[];\nfunction buildSignatureBatch(\n method: \"adjustPayIn\" | \"adjustGuestPayIn\",\n request: AdjustPayInRequestDto,\n rules: SignatureBatchRules & { allowTxHash: true },\n): (PayInStepSignatureDto | PayInStepTxHashDto)[];\nfunction buildSignatureBatch(\n method: string,\n request: unknown,\n rules: SignatureBatchRules,\n): (PayInStepSignatureDto | PayInStepTxHashDto)[] {\n const items: unknown = isJsonObject(request) ? request.signatures : undefined;\n if (!Array.isArray(items)) {\n throw new TypeError(`${method}: signatures must be an array`);\n }\n if (items.length === 0 && !rules.allowEmpty) {\n throw new TypeError(`${method}: signatures must hold at least one item`);\n }\n\n return Array.from(items, (item: unknown, index) =>\n buildSignatureItem(`${method}: signatures[${index}]`, item, rules.allowTxHash),\n );\n}\n\n/**\n * Builds one batch item key by key, per {@link buildSignatureBatch}. `label` names the item in a refusal.\n *\n * @throws {TypeError} when the item breaks a rule {@link buildSignatureBatch} lists.\n */\nfunction buildSignatureItem(label: string, item: unknown, allowTxHash: boolean): PayInStepSignatureDto | PayInStepTxHashDto {\n if (!isJsonObject(item)) {\n throw new TypeError(`${label} must be an object`);\n }\n\n const stepId = item.step_id;\n if (typeof stepId !== \"string\" || stepId === \"\") {\n throw new TypeError(`${label}.step_id must be a non-empty string`);\n }\n\n const signature = item.signature;\n const txHash = item.tx_hash;\n if ((signature === undefined) === (txHash === undefined)) {\n throw new TypeError(`${label} must carry exactly one of signature and tx_hash`);\n }\n\n if (txHash === undefined) {\n if (typeof signature !== \"string\" || signature === \"\") {\n throw new TypeError(`${label}.signature must be a non-empty string`);\n }\n\n return { step_id: stepId, signature };\n }\n\n if (!allowTxHash) {\n throw new TypeError(`${label} carries a tx_hash, which is never sent on confirm`);\n }\n if (typeof txHash !== \"string\" || !TX_HASH_PATTERN.test(txHash)) {\n throw new TypeError(`${label}.tx_hash must be 0x followed by 64 hex digits`);\n }\n\n return { step_id: stepId, tx_hash: txHash };\n}\n\n/**\n * Checks a route open or pay-in confirm's idempotency key: 1 to {@link MAX_IDEMPOTENCY_KEY_LENGTH} visible ASCII characters.\n *\n * @throws {TypeError} when it is anything else.\n */\nfunction checkIdempotencyKey(method: string, key: unknown): string {\n if (typeof key !== \"string\" || key.length > MAX_IDEMPOTENCY_KEY_LENGTH || !IDEMPOTENCY_KEY_PATTERN.test(key)) {\n throw new TypeError(`${method}: idempotencyKey must be 1 to ${MAX_IDEMPOTENCY_KEY_LENGTH} visible ASCII characters`);\n }\n\n return key;\n}\n\n/**\n * Checks a route id and encodes it for the path. `.` and `..` are refused: `encodeURIComponent` leaves them as they\n * are, and the URL parser would resolve them as dot segments, sending the call to another hub API path.\n *\n * @throws {TypeError} when it is not a non-empty string, or is `.` or `..`.\n */\nfunction encodePathId(method: string, field: string, routeId: unknown): string {\n if (typeof routeId !== \"string\" || routeId === \"\" || routeId === \".\" || routeId === \"..\") {\n throw new TypeError(`${method}: ${field} must be a non-empty string other than \".\" and \"..\"`);\n }\n\n return encodeURIComponent(routeId);\n}\n\n/**\n * Builds `listRoutes`' query string: `?status=a,b&limit=N`, each part only when it is sent, or `\"\"` when neither is.\n * The states need no encoding: every `ROUTE_STATES` member is lowercase letters and `_`.\n *\n * @throws {TypeError} when `query` is not an object, `states` is not an array of `ROUTE_STATES` members, or `limit`\n * is not an integer from 1 to {@link MAX_ROUTE_LIST_LIMIT}.\n */\nfunction buildRouteListQuery(query: ListRoutesQuery | undefined): string {\n if (query === undefined) {\n return \"\";\n }\n if (!isJsonObject(query)) {\n throw new TypeError(\"listRoutes: query must be an object\");\n }\n\n const parts: string[] = [];\n const states: unknown = query.states;\n if (states !== undefined) {\n if (!Array.isArray(states) || !states.every(isRouteStateDto)) {\n throw new TypeError(`listRoutes: states must hold only ${ROUTE_STATES.join(\", \")}`);\n }\n if (states.length > 0) {\n parts.push(`status=${states.join(\",\")}`);\n }\n }\n\n const limit: unknown = query.limit;\n if (limit !== undefined) {\n if (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1 || limit > MAX_ROUTE_LIST_LIMIT) {\n throw new TypeError(`listRoutes: limit must be an integer from 1 to ${MAX_ROUTE_LIST_LIMIT}`);\n }\n parts.push(`limit=${limit}`);\n }\n\n return parts.length === 0 ? \"\" : `?${parts.join(\"&\")}`;\n}\n\n/**\n * Validates `baseUrl` and removes its trailing slashes.\n *\n * @throws {TypeError} when it is not an absolute `http:` or `https:` URL without a query or fragment.\n */\nfunction normaliseBaseUrl(baseUrl: unknown): string {\n if (typeof baseUrl !== \"string\" || baseUrl === \"\") {\n throw new TypeError(\"createCoordinatorClient: baseUrl is required\");\n }\n\n let url: URL;\n try {\n url = new URL(baseUrl);\n } catch {\n throw new TypeError(`createCoordinatorClient: baseUrl must be an absolute URL, got \"${baseUrl}\"`);\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n throw new TypeError(`createCoordinatorClient: baseUrl must use http: or https:, got \"${url.protocol}\"`);\n }\n\n if (url.search !== \"\" || url.hash !== \"\" || baseUrl.includes(\"?\") || baseUrl.includes(\"#\")) {\n throw new TypeError(\"createCoordinatorClient: baseUrl must not carry a query or a fragment\");\n }\n\n return url.href.replace(/\\/+$/, \"\");\n}\n\n/**\n * Builds the request sender every method shares. Every response reports its server time to `onServerTime` before\n * its answer is read.\n *\n * The route's {@link RouteCredentials} are written after every other header. A session call with `omitCredentials`\n * goes out with `credentials: \"include\"`, `X-Stridge-Session: omit` and no `X-CSRF-Token`, and the token is not read:\n * the hub proxy drops the session cookie on such a request, and the token only proves the session that cookie names.\n * The browser still stores the cookies the answer sets, such as an email round's binder cookie. Only a session call\n * ever reads the stored token.\n *\n * @throws {TypeError} when a route header names `X-CSRF-Token`, `X-Stridge-Cookie-Access` or `X-Stridge-Session`,\n * which only the credentials write.\n */\nfunction createTransport(\n baseUrl: string,\n appId: string,\n csrf: CsrfAccessor,\n fetchFn: FetchLike,\n onServerTime: ServerTimeSink | undefined,\n): Transport {\n return {\n async send(call) {\n const signal = call.callOptions?.signal;\n const credentials = call.credentials;\n const omitCredentials = credentials.kind === \"session\" && call.callOptions?.omitCredentials === true;\n const headers: Record<string, string> = {};\n if (call.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n if (call.sendsApp === true) {\n headers[APP_HEADER] = appId;\n }\n if (call.headers !== undefined) {\n for (const name of Object.keys(call.headers)) {\n if (CREDENTIAL_HEADERS.has(name.toLowerCase())) {\n throw new TypeError(`a route header may not name ${name}`);\n }\n }\n Object.assign(headers, call.headers);\n }\n if (omitCredentials) {\n headers[SESSION_HEADER] = SESSION_HEADER_OMIT;\n }\n if (credentials.kind === \"session\" && call.method !== \"GET\" && !omitCredentials) {\n const token = await csrf.get();\n if (typeof token === \"string\" && token !== \"\") {\n headers[CSRF_HEADER] = token;\n }\n }\n if (credentials.kind === \"pinned-session\") {\n headers[CSRF_HEADER] = credentials.token;\n }\n if (credentials.kind === \"guest\") {\n headers[CSRF_HEADER] = credentials.token;\n }\n if (credentials.kind === \"guest\" || credentials.kind === \"guest-read\") {\n headers[GUEST_COOKIE_ACCESS_HEADER] = credentials.cookieAccess;\n }\n\n const init: RequestInit = {\n method: call.method,\n headers,\n credentials: \"include\",\n };\n if (call.body !== undefined) {\n init.body = JSON.stringify(call.body);\n }\n if (signal !== undefined) {\n init.signal = signal;\n }\n\n let response: Response;\n const sentAtMs = Date.now();\n try {\n response = await fetchFn(`${baseUrl}${call.path}`, init);\n } catch (cause) {\n if (signal?.aborted === true) {\n throw cause;\n }\n throw new SuaNetworkError(cause);\n }\n reportServerTime(onServerTime, response.headers, sentAtMs, Date.now());\n\n return readAnswer(response, signal, call.noContent === true, call.isAnswer);\n },\n };\n}\n\n/**\n * Reads an answer: an error envelope on any status and any non-`2xx` throw a `SuaError`. On a `noContent` route any\n * other `2xx` resolves `undefined`. On every other route a `2xx` whose body is not a JSON object (a `204` included),\n * or fails the route's `isAnswer` check, throws a `SuaError` with code `internal`, and any other `2xx` resolves its\n * parsed body.\n *\n * A body that fails to read rethrows the abort when the caller aborted. Otherwise it throws `SuaNetworkError` on a\n * `2xx` (no usable answer arrived) and counts as an empty body on a failure status.\n */\nasync function readAnswer(\n response: Response,\n signal: AbortSignal | undefined,\n noContent: boolean,\n isAnswer: ((value: unknown) => boolean) | undefined,\n): Promise<unknown> {\n if (response.status === 204) {\n if (noContent) {\n return undefined;\n }\n\n throw toSuaError({ status: 204, retryAfter: response.headers.get(\"Retry-After\"), body: \"\" });\n }\n\n let text: string;\n try {\n text = await response.text();\n } catch (cause) {\n if (signal?.aborted === true) {\n throw cause;\n }\n if (response.ok) {\n throw new SuaNetworkError(cause);\n }\n text = \"\";\n }\n\n const parsed = parseBody(text);\n const isEnvelope = parsed.kind === \"json\" && isErrorEnvelopeDto(parsed.value);\n const isSuccessBody =\n parsed.kind === \"json\" && isJsonObject(parsed.value) && (isAnswer === undefined || isAnswer(parsed.value));\n\n if (noContent && response.ok && !isEnvelope) {\n return undefined;\n }\n\n if (isEnvelope || !response.ok || !isSuccessBody) {\n throw toSuaError({\n status: response.status,\n retryAfter: response.headers.get(\"Retry-After\"),\n body: text,\n });\n }\n\n return parsed.value;\n}\n","const BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;\nconst BASE64_URL_PATTERN = /^[A-Za-z0-9_-]*$/;\nconst CHUNK_SIZE = 0x8000;\n\n/**\n * Builds a binary string (one character per byte, every code unit 0–255) from bytes, in chunks so a large input\n * never overflows the argument limit of `String.fromCharCode`. A binary string is the only input `btoa` handles\n * correctly.\n */\nfunction toBinaryString(bytes: Uint8Array): string {\n let out = \"\";\n for (let offset = 0; offset < bytes.length; offset += CHUNK_SIZE) {\n out += String.fromCharCode(...bytes.subarray(offset, offset + CHUNK_SIZE));\n }\n return out;\n}\n\n/**\n * Turns the binary string `atob` returns back into bytes.\n */\nfunction fromBinaryString(binary: string): Uint8Array {\n const out = new Uint8Array(binary.length);\n for (let index = 0; index < binary.length; index += 1) {\n out[index] = binary.charCodeAt(index);\n }\n return out;\n}\n\n/**\n * Encodes bytes as standard base64 (RFC 4648 §4: `+`, `/`, padded with `=`). This is the encoding of the\n * Coordinator's `[]byte` JSON fields (`body`, `stamp_header.value`, `provider_response`) and of\n * `session_public_key`.\n *\n * Works on bytes, never on text: to base64 a string, encode it with {@link utf8ToBytes} first. Calling `btoa` on\n * a string with any character above U+00FF throws, and on a Latin-1 string it silently encodes the wrong bytes.\n */\nexport function toBase64(bytes: Uint8Array): string {\n return btoa(toBinaryString(bytes));\n}\n\n/**\n * Decodes standard base64 (RFC 4648 §4). Padding may be present or omitted; whitespace and the URL-safe\n * alphabet (`-`, `_`) are refused.\n *\n * @throws {TypeError} when `value` is not standard base64.\n */\nexport function fromBase64(value: string): Uint8Array {\n if (typeof value !== \"string\" || !BASE64_PATTERN.test(value) || value.length % 4 === 1) {\n throw new TypeError(\"fromBase64: expected standard base64\");\n }\n try {\n return fromBinaryString(atob(value));\n } catch {\n throw new TypeError(\"fromBase64: expected standard base64\");\n }\n}\n\n/**\n * Encodes bytes as base64url without padding (RFC 4648 §5: `-`, `_`, no `=`). This is the encoding of the\n * Turnkey stamp string before it is wrapped in standard base64 for `stamp_header.value` (guide §7.2).\n */\nexport function toBase64Url(bytes: Uint8Array): string {\n return toBase64(bytes).replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/, \"\");\n}\n\n/**\n * Decodes base64url (RFC 4648 §5) without padding. Padding, whitespace and the standard alphabet (`+`, `/`) are\n * refused.\n *\n * @throws {TypeError} when `value` is not unpadded base64url.\n */\nexport function fromBase64Url(value: string): Uint8Array {\n if (typeof value !== \"string\" || !BASE64_URL_PATTERN.test(value) || value.length % 4 === 1) {\n throw new TypeError(\"fromBase64Url: expected unpadded base64url\");\n }\n return fromBase64(value.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\"));\n}\n","const HEX_PATTERN = /^(?:[0-9a-fA-F]{2})*$/;\n\n/**\n * Encodes bytes as lowercase hex, two characters per byte, with no `0x` prefix.\n *\n * @example toHex(new Uint8Array([0x02, 0x4e])) === \"024e\"\n */\nexport function toHex(bytes: Uint8Array): string {\n let out = \"\";\n for (const byte of bytes) {\n out += byte.toString(16).padStart(2, \"0\");\n }\n return out;\n}\n\n/**\n * Decodes hex into bytes. Accepts either case; refuses a `0x` prefix, an odd length and any non-hex character.\n *\n * @throws {TypeError} when `hex` is not an even-length string of hex digits.\n */\nexport function fromHex(hex: string): Uint8Array {\n if (typeof hex !== \"string\" || !HEX_PATTERN.test(hex)) {\n throw new TypeError(\"fromHex: expected an even-length hex string without a 0x prefix\");\n }\n const out = new Uint8Array(hex.length / 2);\n for (let index = 0; index < out.length; index += 1) {\n out[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16);\n }\n return out;\n}\n","const SEQUENCE_TAG = 0x30;\nconst INTEGER_TAG = 0x02;\nconst COORDINATE_LENGTH = 32;\nconst RAW_LENGTH = COORDINATE_LENGTH * 2;\nconst MAX_INTEGER_LENGTH = COORDINATE_LENGTH + 1;\nconst LONG_FORM_BIT = 0x80;\n\n/**\n * Encodes one 32-byte big-endian coordinate as a minimal, positive DER INTEGER: leading zeros stripped (at least one\n * byte kept), then one `0x00` prepended when the high bit of the first remaining byte is set.\n */\nfunction encodeInteger(value: Uint8Array): Uint8Array {\n let start = 0;\n while (start < value.length - 1 && value[start] === 0) {\n start += 1;\n }\n const digits = value.subarray(start);\n const pad = digits[0] >= 0x80 ? 1 : 0;\n const out = new Uint8Array(2 + pad + digits.length);\n out[0] = INTEGER_TAG;\n out[1] = pad + digits.length;\n out.set(digits, 2 + pad);\n return out;\n}\n\n/**\n * Converts a raw P-256 ECDSA signature (r‖s, 32 bytes each) to DER (X.690):\n * `0x30 <len> 0x02 <rlen> <r> 0x02 <slen> <s>`, where each integer is minimal and positive: leading `0x00` bytes are\n * stripped (keeping at least one byte), then one `0x00` is prepended when the first remaining byte is `≥ 0x80`.\n * Lengths are always short-form (the whole signature is at most 72 bytes).\n *\n * Example (§12.7): r `a364…d7f6` has its high bit set and becomes `022100a364…d7f6`; s `4199…556e` does not and\n * becomes `02204199…556e`, giving `3045022100a364f4…42556e`.\n *\n * @throws {TypeError} when `raw` is not exactly 64 bytes.\n */\nexport function rawSignatureToDer(raw: Uint8Array): Uint8Array {\n if (!(raw instanceof Uint8Array) || raw.length !== RAW_LENGTH) {\n throw new TypeError(\"rawSignatureToDer: expected a 64-byte r‖s signature\");\n }\n const r = encodeInteger(raw.subarray(0, COORDINATE_LENGTH));\n const s = encodeInteger(raw.subarray(COORDINATE_LENGTH));\n const out = new Uint8Array(2 + r.length + s.length);\n out[0] = SEQUENCE_TAG;\n out[1] = r.length + s.length;\n out.set(r, 2);\n out.set(s, 2 + r.length);\n return out;\n}\n\n/**\n * One DER INTEGER once read: its value without the sign-padding byte, and the offset just past it.\n */\ninterface DerInteger {\n value: Uint8Array;\n next: number;\n}\n\n/**\n * Reads one strict DER INTEGER at `offset`: tag `0x02`, a short-form length of 1–33 that ends at or before `end`, a\n * positive and minimal encoding, and a value of at most 32 bytes once the sign-padding byte is dropped.\n *\n * @throws {TypeError} when the INTEGER breaks any of those rules.\n */\nfunction readInteger(der: Uint8Array, offset: number, end: number): DerInteger {\n if (offset + 2 > end || der[offset] !== INTEGER_TAG) {\n throw new TypeError(\"derSignatureToRaw: expected an INTEGER\");\n }\n const length = der[offset + 1];\n if ((length & LONG_FORM_BIT) !== 0) {\n throw new TypeError(\"derSignatureToRaw: long-form lengths are not allowed\");\n }\n if (length < 1 || length > MAX_INTEGER_LENGTH) {\n throw new TypeError(\"derSignatureToRaw: INTEGER length out of range\");\n }\n const start = offset + 2;\n const next = start + length;\n if (next > end) {\n throw new TypeError(\"derSignatureToRaw: INTEGER runs past the end of the SEQUENCE\");\n }\n const first = der[start];\n if (first >= 0x80) {\n throw new TypeError(\"derSignatureToRaw: negative INTEGER\");\n }\n const padded = first === 0 && length > 1;\n if (padded && der[start + 1] < 0x80) {\n throw new TypeError(\"derSignatureToRaw: non-minimal INTEGER\");\n }\n const value = der.subarray(padded ? start + 1 : start, next);\n if (value.length > COORDINATE_LENGTH) {\n throw new TypeError(\"derSignatureToRaw: INTEGER is longer than 32 bytes\");\n }\n return { value, next };\n}\n\n/**\n * Converts a DER ECDSA signature to raw r‖s (64 bytes): each INTEGER is stripped of leading `0x00` bytes and\n * left-padded with zeros to 32 bytes. The exact inverse of {@link rawSignatureToDer} on its output.\n *\n * Strict: a `0x30` SEQUENCE with a short-form length equal to the rest of the input, holding exactly two `0x02`\n * INTEGERs with short-form lengths of 1–33 bytes, each positive (first byte `< 0x80`) and minimal (a leading `0x00`\n * only when the next byte is `≥ 0x80`), with a value of at most 32 bytes once stripped, and no trailing bytes.\n *\n * @throws {TypeError} when `der` breaks any of those rules.\n */\nexport function derSignatureToRaw(der: Uint8Array): Uint8Array {\n if (!(der instanceof Uint8Array) || der.length < 2 || der[0] !== SEQUENCE_TAG) {\n throw new TypeError(\"derSignatureToRaw: expected a DER SEQUENCE\");\n }\n const length = der[1];\n if ((length & LONG_FORM_BIT) !== 0) {\n throw new TypeError(\"derSignatureToRaw: long-form lengths are not allowed\");\n }\n if (length !== der.length - 2) {\n throw new TypeError(\"derSignatureToRaw: SEQUENCE length does not match the input\");\n }\n const r = readInteger(der, 2, der.length);\n const s = readInteger(der, r.next, der.length);\n if (s.next !== der.length) {\n throw new TypeError(\"derSignatureToRaw: trailing bytes after the two INTEGERs\");\n }\n const out = new Uint8Array(RAW_LENGTH);\n out.set(r.value, COORDINATE_LENGTH - r.value.length);\n out.set(s.value, RAW_LENGTH - s.value.length);\n return out;\n}\n","/**\n * Returns WebCrypto's `SubtleCrypto`, read from `globalThis` at call time so importing a module never touches it (a\n * server bundle may import the SDK on a runtime without WebCrypto).\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport function getSubtle(): SubtleCrypto {\n const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;\n if (!subtle) {\n throw new Error(\"WebCrypto is unavailable\");\n }\n return subtle;\n}\n","/**\n * A WebCrypto key pair. Structurally the DOM's `CryptoKeyPair`, declared here because the SDK compiles without the\n * DOM library; a `CryptoKeyPair` from `crypto.subtle.generateKey` is assignable to it.\n */\nexport interface CryptoKeyPairLike {\n /**\n * The public key. WebCrypto always allows exporting a public key, whatever `extractable` said.\n */\n readonly publicKey: CryptoKey;\n\n /**\n * The private key: ECDSA P-256, `extractable: false`, usages `[\"sign\"]`. It never leaves WebCrypto.\n */\n readonly privateKey: CryptoKey;\n}\n\n/**\n * The keypair: the browser-held P-256 key that signs (the glossary's \"keypair\"; the backend's \"session credential\").\n * Registered once per sign-in or renewal and valid for about 60 minutes.\n *\n * Every field survives a structured clone, so the whole object can be stored in IndexedDB as is.\n */\nexport interface Keypair {\n /**\n * The WebCrypto pair.\n */\n keys: CryptoKeyPairLike;\n\n /**\n * The 33-byte compressed SEC1 public key: `0x02` or `0x03` (the parity of Y), then the 32-byte X coordinate.\n */\n publicKey: Uint8Array;\n\n /**\n * `publicKey` as 66 lowercase hex characters. The form the stamps, the login activity and the code sealer use.\n */\n publicKeyHex: string;\n\n /**\n * `publicKey` as standard base64 (44 characters). Kept for stored keypairs; no request sends it.\n */\n publicKeyBase64: string;\n}\n\n/**\n * The WebCrypto parameters of the keypair: ECDSA on P-256.\n */\nexport const KEYPAIR_ALGORITHM = { name: \"ECDSA\", namedCurve: \"P-256\" } as const;\n\n/**\n * The WebCrypto parameters of every signature: ECDSA with SHA-256. WebCrypto hashes the message itself and returns\n * raw r‖s (IEEE P1363, 64 bytes).\n */\nexport const SIGNATURE_ALGORITHM = { name: \"ECDSA\", hash: \"SHA-256\" } as const;\n\n/**\n * The registration's activity type: the keypair's own login.\n */\nexport const STAMP_LOGIN_ACTIVITY_TYPE = \"ACTIVITY_TYPE_STAMP_LOGIN\";\n\n/**\n * The login window the registration asks for, as the decimal string the activity carries: one hour, the Coordinator's\n * `OWNER_SESSION_LIFETIME`. There is no server-side logout, so this is how long a registered keypair can sign.\n */\nexport const STAMP_LOGIN_EXPIRATION_SECONDS = \"3600\";\n\n/**\n * The stamp's `scheme`.\n */\nexport const STAMP_SCHEME = \"SIGNATURE_SCHEME_TK_API_P256\";\n\n/**\n * The stamp header's name.\n */\nexport const STAMP_HEADER_NAME = \"X-Stamp\";\n","import { toHex, utf8ToBytes } from \"#/encoding\";\n\nimport { rawSignatureToDer } from \"./der\";\nimport { getSubtle } from \"./subtle\";\nimport { SIGNATURE_ALGORITHM } from \"./types\";\n\n/**\n * Signs the UTF-8 bytes of `message` with ECDSA P-256 / SHA-256 and returns WebCrypto's raw r‖s bytes.\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nasync function signBytes(privateKey: CryptoKey, message: string): Promise<Uint8Array> {\n const subtle = getSubtle();\n return new Uint8Array(await subtle.sign(SIGNATURE_ALGORITHM, privateKey, utf8ToBytes(message)));\n}\n\n/**\n * Signs `message` with ECDSA P-256 and SHA-256 (`SIGNATURE_ALGORITHM`) over the UTF-8 bytes of `message`\n * (`utf8ToBytes`), returned as **raw r‖s**: the 64 bytes WebCrypto produces, as 128 lowercase hex characters. No DER,\n * no low-S normalisation. No Coordinator request takes this form; stamps use {@link signDer}.\n *\n * ECDSA is randomised, so two calls give different signatures; test by verifying, not by comparing.\n *\n * @param privateKey The keypair's private key.\n * @param message The message, verbatim.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function signRaw(privateKey: CryptoKey, message: string): Promise<string> {\n return toHex(await signBytes(privateKey, message));\n}\n\n/**\n * Signs `message` for the **stamp** (guide §7.2): the same ECDSA P-256 / SHA-256 signature over the UTF-8 bytes of\n * `message` as {@link signRaw}, converted with `rawSignatureToDer` and returned as lowercase DER hex (140–144\n * characters; 138 or fewer is possible but rare).\n *\n * @param privateKey The keypair's private key.\n * @param message The exact activity body string that the relay will forward.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function signDer(privateKey: CryptoKey, message: string): Promise<string> {\n return toHex(rawSignatureToDer(await signBytes(privateKey, message)));\n}\n","import { toBase64Url, utf8ToBytes } from \"#/encoding\";\nimport type { AttestationDto, CredentialDto, RegisterKeypairRequestDto } from \"#/models\";\n\nimport { signDer } from \"./sign\";\nimport { type Keypair, STAMP_LOGIN_ACTIVITY_TYPE, STAMP_LOGIN_EXPIRATION_SECONDS } from \"./types\";\n\nconst COMPRESSED_PUBLIC_KEY_HEX = /^0[23][0-9a-f]{64}$/;\n\n/**\n * Builds the keypair's login activity, once, as the exact string the stamp signs and the hub relays:\n *\n * `{\"type\":\"ACTIVITY_TYPE_STAMP_LOGIN\",\"timestampMs\":\"<nowMs>\",\"organizationId\":\"<organizationId>\",\"parameters\":{\"publicKey\":\"<publicKeyHex>\",\"expirationSeconds\":\"3600\",\"invalidateExisting\":false}}`\n *\n * The hub refuses any other key, casing or order of fields, a window above its own, and `invalidateExisting: true`\n * (which would sign the person out on every other device). Never re-serialise the result.\n *\n * @param organizationId The wallet's `provider_account_ref`.\n * @param publicKeyHex The keypair's compressed public key: 66 lowercase hex characters starting `02` or `03`.\n * @param nowMs The activity's timestamp, in milliseconds since the epoch.\n * @throws {TypeError} when `organizationId` is empty or `publicKeyHex` is not a lowercase compressed key.\n */\nexport function buildStampLogin(organizationId: string, publicKeyHex: string, nowMs: number = Date.now()): string {\n if (typeof organizationId !== \"string\" || organizationId === \"\") {\n throw new TypeError(\"buildStampLogin: expected a non-empty organization id\");\n }\n if (typeof publicKeyHex !== \"string\" || !COMPRESSED_PUBLIC_KEY_HEX.test(publicKeyHex)) {\n throw new TypeError(\"buildStampLogin: expected a 66-character lowercase compressed public key hex\");\n }\n return JSON.stringify({\n type: STAMP_LOGIN_ACTIVITY_TYPE,\n timestampMs: String(Math.trunc(nowMs)),\n organizationId,\n parameters: {\n publicKey: publicKeyHex,\n expirationSeconds: STAMP_LOGIN_EXPIRATION_SECONDS,\n invalidateExisting: false,\n },\n });\n}\n\n/**\n * Builds the `X-Stamp-Attested` value over `body`: the keypair's DER signature over the UTF-8 bytes of `body`\n * (`signDer`), in the JSON `{\"publicKeyAttestation\",\"scheme\",\"publicKey\",\"signature\"}` with the attestation verbatim,\n * then its UTF-8 bytes as **unpadded base64url**. Never log the result: it carries the attestation token.\n *\n * @param body The exact string to sign, from {@link buildStampLogin}.\n * @param keypair The keypair that sealed the code the attestation was issued for.\n * @param attestation The credential's `attestation`.\n */\nexport async function stampAttested(body: string, keypair: Keypair, attestation: AttestationDto): Promise<string> {\n const signature = await signDer(keypair.keys.privateKey, body);\n const stamp = JSON.stringify({\n publicKeyAttestation: attestation.token,\n scheme: attestation.scheme,\n publicKey: keypair.publicKeyHex,\n signature,\n });\n return toBase64Url(utf8ToBytes(stamp));\n}\n\n/**\n * Builds the registration body for a credential: the keypair's login for `organizationId` ({@link buildStampLogin})\n * and its attested stamp ({@link stampAttested}), as exactly `{ round_id: credential.round_id, stamped_body,\n * attested_stamp }`.\n *\n * @param organizationId The wallet's `provider_account_ref`.\n * @throws {TypeError} on the inputs {@link buildStampLogin} refuses.\n */\nexport async function createRegisterKeypairRequest(\n credential: CredentialDto,\n keypair: Keypair,\n organizationId: string,\n nowMs: number = Date.now(),\n): Promise<RegisterKeypairRequestDto> {\n const stampedBody = buildStampLogin(organizationId, keypair.publicKeyHex, nowMs);\n return {\n round_id: credential.round_id,\n stamped_body: stampedBody,\n attested_stamp: await stampAttested(stampedBody, keypair, credential.attestation),\n };\n}\n","import { toBase64, toHex } from \"#/encoding\";\n\nimport { getSubtle } from \"./subtle\";\nimport { type CryptoKeyPairLike, KEYPAIR_ALGORITHM, type Keypair } from \"./types\";\n\nconst UNCOMPRESSED_LENGTH = 65;\nconst COMPRESSED_LENGTH = 33;\nconst UNCOMPRESSED_PREFIX = 0x04;\n\n/**\n * Reports whether a key's algorithm is ECDSA on P-256.\n */\nfunction isEcdsaP256(key: CryptoKey): boolean {\n const algorithm = key.algorithm as { name?: unknown; namedCurve?: unknown } | undefined;\n return algorithm?.name === KEYPAIR_ALGORITHM.name && algorithm.namedCurve === KEYPAIR_ALGORITHM.namedCurve;\n}\n\n/**\n * Checks that `keys` is an ECDSA P-256 pair whose private half can sign.\n *\n * @throws {TypeError} when it is not.\n */\nfunction assertSigningPair(keys: CryptoKeyPairLike): void {\n const { publicKey, privateKey } = keys ?? {};\n if (!publicKey || publicKey.type !== \"public\" || !isEcdsaP256(publicKey)) {\n throw new TypeError(\"keypairFromKeys: the public key must be an ECDSA P-256 public key\");\n }\n if (\n !privateKey ||\n privateKey.type !== \"private\" ||\n !isEcdsaP256(privateKey) ||\n !Array.from(privateKey.usages ?? []).includes(\"sign\")\n ) {\n throw new TypeError(\"keypairFromKeys: the private key must be an ECDSA P-256 private key that can sign\");\n }\n}\n\n/**\n * Generates a new keypair (guide §3.3): `crypto.subtle.generateKey(KEYPAIR_ALGORITHM, false, [\"sign\"])`, so the\n * private key is ECDSA P-256, non-extractable and can only sign. Then derives the compressed public key forms through\n * {@link keypairFromKeys}.\n *\n * Reads `globalThis.crypto.subtle` at call time, never at module load.\n *\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function generateKeypair(): Promise<Keypair> {\n const keys = (await getSubtle().generateKey(KEYPAIR_ALGORITHM, false, [\"sign\"])) as CryptoKeyPairLike;\n return keypairFromKeys(keys);\n}\n\n/**\n * Builds a {@link Keypair} around an existing WebCrypto pair, for example one read back from storage: exports\n * `keys.publicKey` as `\"raw\"` (the 65-byte uncompressed point), compresses it with {@link compressPublicKey}, and fills\n * `publicKeyHex` (`toHex`, lowercase) and `publicKeyBase64` (`toBase64`, standard, padded). `keys` is kept by\n * reference.\n *\n * @throws {TypeError} when `keys.publicKey.algorithm` is not ECDSA on P-256, or `keys.privateKey` is not an ECDSA\n * private key whose usages include `\"sign\"`.\n * @throws {Error} with message `WebCrypto is unavailable` when `globalThis.crypto?.subtle` is missing.\n */\nexport async function keypairFromKeys(keys: CryptoKeyPairLike): Promise<Keypair> {\n const subtle = getSubtle();\n assertSigningPair(keys);\n const raw = new Uint8Array(await subtle.exportKey(\"raw\", keys.publicKey));\n const publicKey = compressPublicKey(raw);\n return {\n keys,\n publicKey,\n publicKeyHex: toHex(publicKey),\n publicKeyBase64: toBase64(publicKey),\n };\n}\n\n/**\n * Compresses an uncompressed SEC1 P-256 point (`0x04 ‖ X ‖ Y`, 65 bytes) into 33 bytes: prefix `0x02 + (Y[31] & 1)`,\n * then X (guide §3.3: `publicKey[0] = 2 + (raw[64] & 1)`). Returns a new array; the input is not modified.\n *\n * Only the encoding is checked, not that the point is on the curve (WebCrypto produced it).\n *\n * @throws {TypeError} when `uncompressed` is not 65 bytes starting with `0x04`.\n */\nexport function compressPublicKey(uncompressed: Uint8Array): Uint8Array {\n if (\n !(uncompressed instanceof Uint8Array) ||\n uncompressed.length !== UNCOMPRESSED_LENGTH ||\n uncompressed[0] !== UNCOMPRESSED_PREFIX\n ) {\n throw new TypeError(\"compressPublicKey: expected a 65-byte uncompressed point starting with 0x04\");\n }\n const out = new Uint8Array(COMPRESSED_LENGTH);\n out[0] = 0x02 + (uncompressed[UNCOMPRESSED_LENGTH - 1] & 1);\n out.set(uncompressed.subarray(1, COMPRESSED_LENGTH), 1);\n return out;\n}\n","import { toBase64, toBase64Url, utf8ToBytes } from \"#/encoding\";\nimport type { StampHeaderDto } from \"#/models\";\n\nimport { STAMP_HEADER_NAME, STAMP_SCHEME } from \"./types\";\n\nconst COMPRESSED_PUBLIC_KEY_HEX = /^0[23][0-9a-fA-F]{64}$/;\nconst NON_EMPTY_HEX = /^(?:[0-9a-fA-F]{2})+$/;\n\n/**\n * Builds the Turnkey API-key stamp string (guide §7.2; `router/internal/turnkey/stamp.go`): the compact JSON\n * `{\"publicKey\":\"<publicKeyHex>\",\"scheme\":\"SIGNATURE_SCHEME_TK_API_P256\",\"signature\":\"<signatureDerHex>\"}`, keys in\n * exactly that order and no whitespace (build it with `JSON.stringify` of an object literal in that order), then its\n * UTF-8 bytes as **unpadded base64url** (`toBase64Url`).\n *\n * Both hex inputs are lowercased before they are embedded.\n *\n * Vector (§12.7): public key `024e7fb37bf4a0c496da3d6ce2bd68f82b1a1c877a8f258a4bceb121bec94ba272` and the §12.7 DER\n * signature give the string whose standard base64 is the §12.7 `stamp_header.value`.\n *\n * @param publicKeyHex The keypair's compressed public key: 66 hex characters starting `02` or `03`.\n * @param signatureDerHex The DER signature over the body, as hex (from `signDer`).\n * @throws {TypeError} when `publicKeyHex` is not 66 hex characters starting `02` or `03`, or `signatureDerHex` is not\n * a non-empty even-length hex string.\n */\nexport function buildStamp(publicKeyHex: string, signatureDerHex: string): string {\n if (typeof publicKeyHex !== \"string\" || !COMPRESSED_PUBLIC_KEY_HEX.test(publicKeyHex)) {\n throw new TypeError(\"buildStamp: expected a 66-character compressed public key hex starting 02 or 03\");\n }\n if (typeof signatureDerHex !== \"string\" || !NON_EMPTY_HEX.test(signatureDerHex)) {\n throw new TypeError(\"buildStamp: expected a non-empty even-length DER signature hex\");\n }\n const stamp = JSON.stringify({\n publicKey: publicKeyHex.toLowerCase(),\n scheme: STAMP_SCHEME,\n signature: signatureDerHex.toLowerCase(),\n });\n return toBase64Url(utf8ToBytes(stamp));\n}\n\n/**\n * Builds the relay's `stamp_header`: `{ name: \"X-Stamp\", value }` where `value` is the **standard base64 (padded)**\n * of the UTF-8 bytes of {@link buildStamp}'s string, so base64 of base64url. The Coordinator decodes it once and\n * forwards the result as the `X-Stamp` header verbatim.\n *\n * Vector (§12.7): the §12.7 public key and DER signature give exactly the §12.7 `stamp_header.value`\n * (`ZXlKd2RXSnNhV05MWlhr…Wk5UVTJaU0o5`).\n *\n * @throws {TypeError} on the same inputs as {@link buildStamp}.\n */\nexport function buildStampHeader(publicKeyHex: string, signatureDerHex: string): StampHeaderDto {\n return {\n name: STAMP_HEADER_NAME,\n value: toBase64(utf8ToBytes(buildStamp(publicKeyHex, signatureDerHex))),\n };\n}\n\n/**\n * Encodes the activity body for the relay's `body` field (guide §7.3): the **standard base64 (padded)** of the exact\n * UTF-8 bytes of `body`, which are the bytes the stamp signed. `toBase64(utf8ToBytes(body))`; never `btoa(body)`,\n * which throws on any character above U+00FF and silently encodes Latin-1 wrongly.\n *\n * Vector (§12.7): the §12.7 body string encodes to the §12.7 request's `body`\n * (`eyJ0eXBlIjoiQUNUSVZJVFlfVFlQRV9TSUdOX1JBV19QQVlMT0FEX1YyIiwi…In19`).\n */\nexport function encodeRelayBody(body: string): string {\n return toBase64(utf8ToBytes(body));\n}\n","import type { RelayPurposeDto, RelayRequestDto } from \"#/models\";\n\nimport { signDer } from \"./sign\";\nimport { buildStampHeader, encodeRelayBody } from \"./stamp\";\n\nimport type { Keypair } from \"./types\";\n\n/**\n * Stamps an activity body and builds the relay request for it (guide §7.2–§7.3):\n *\n * 1. `signDer(keypair.keys.privateKey, body)` over the exact UTF-8 bytes of `body`.\n * 2. Returns exactly `{ body: encodeRelayBody(body), stamp_header: buildStampHeader(keypair.publicKeyHex,\n * signatureDer), purpose }`, with those keys in that order.\n *\n * `body` is the string `buildSignRawPayloadBody` returned; it is never parsed or re-serialised here.\n *\n * @param body The activity body string to sign and forward.\n * @param keypair The registered keypair.\n * @param purpose The relay's purpose. Defaults to `\"signing\"`.\n */\nexport async function createRelayRequest(\n body: string,\n keypair: Keypair,\n purpose: RelayPurposeDto = \"signing\",\n): Promise<RelayRequestDto> {\n const signatureDer = await signDer(keypair.keys.privateKey, body);\n return {\n body: encodeRelayBody(body),\n stamp_header: buildStampHeader(keypair.publicKeyHex, signatureDer),\n purpose,\n };\n}\n","import { DECIMAL_INTEGER_PATTERN } from \"#/shared/patterns\";\n\nimport { MAX_TOKEN_DECIMALS } from \"./constants\";\n\n/**\n * A decimal amount as text: digits with an optional fraction after a `.` (`12`, `12.`, `12.5`), or a fraction alone\n * (`.5`). No sign, exponent, grouping or spaces.\n */\nconst DECIMAL_TEXT_PATTERN = /^(?:([0-9]+)(?:\\.([0-9]*))?|\\.([0-9]+))$/;\n\n/**\n * A run of fraction digits that are all zeros, or none.\n */\nconst ZEROS_PATTERN = /^0*$/;\n\n/**\n * Reads an amount in base units as the API writes it (a holding's `amount`, a leg's `input_amount`, a pay-in's\n * `delivered`): a decimal integer without leading zeros, which may exceed 2^53. `null` when `text` is not one. Pure.\n *\n * @example parseBaseUnits(\"419397733767447402007014\") === 419397733767447402007014n\n * @example parseBaseUnits(\"012\") === null\n */\nexport function parseBaseUnits(text: string): bigint | null {\n return typeof text === \"string\" && DECIMAL_INTEGER_PATTERN.test(text) ? BigInt(text) : null;\n}\n\n/**\n * Reads a decimal amount of a token with `decimals` decimals into its base units, exactly: `toBaseUnits(\"20\", 6)` is\n * `20000000n`, the `amount` a 20 USDC.e quote sends. `null` when `text` is not a decimal amount (see the pattern above)\n * or names a fraction finer than one base unit: an amount is never rounded. Zeros past `decimals` are exact, so\n * `\"1.5000000\"` reads at 6 decimals. Pure.\n *\n * @example toBaseUnits(\"1096.08\", 6) === 1096080000n\n * @example toBaseUnits(\"0.0000001\", 6) === null\n *\n * @throws {TypeError} when `decimals` is not a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.\n */\nexport function toBaseUnits(text: string, decimals: number): bigint | null {\n checkDecimals(\"toBaseUnits\", decimals);\n if (typeof text !== \"string\") {\n return null;\n }\n const match = DECIMAL_TEXT_PATTERN.exec(text);\n if (match === null) {\n return null;\n }\n const fraction = match[2] ?? match[3] ?? \"\";\n if (!ZEROS_PATTERN.test(fraction.slice(decimals))) {\n return null;\n }\n const whole = BigInt(match[1] ?? \"0\");\n const kept = fraction.slice(0, decimals).padEnd(decimals, \"0\");\n\n return whole * 10n ** BigInt(decimals) + (kept === \"\" ? 0n : BigInt(kept));\n}\n\n/**\n * Writes base units of a token with `decimals` decimals as a decimal figure, rounded toward zero to\n * `maxFractionDigits` (every decimal by default) and without trailing zeros: `formatBaseUnits(20049318n, 6, 2)` is\n * `\"20.04\"`. No grouping and no symbol; the screens format it for display. A negative amount keeps its sign, unless it\n * rounds to zero. Pure.\n *\n * @example formatBaseUnits(1096076785n, 6) === \"1096.076785\"\n * @example formatBaseUnits(20000000n, 6) === \"20\"\n *\n * @throws {TypeError} when `units` is not a bigint, `decimals` is not a whole number from 0 to\n * {@link MAX_TOKEN_DECIMALS}, or `maxFractionDigits` is not a whole number from 0.\n */\nexport function formatBaseUnits(units: bigint, decimals: number, maxFractionDigits: number = decimals): string {\n if (typeof units !== \"bigint\") {\n throw new TypeError(\"formatBaseUnits: units must be a bigint\");\n }\n checkDecimals(\"formatBaseUnits\", decimals);\n if (!Number.isSafeInteger(maxFractionDigits) || maxFractionDigits < 0) {\n throw new TypeError(\"formatBaseUnits: maxFractionDigits must be a whole number from 0\");\n }\n const magnitude = units < 0n ? -units : units;\n const scale = 10n ** BigInt(decimals);\n const fraction = (magnitude % scale)\n .toString()\n .padStart(decimals, \"0\")\n .slice(0, Math.min(decimals, maxFractionDigits))\n .replace(/0+$/, \"\");\n const figure = fraction === \"\" ? (magnitude / scale).toString() : `${magnitude / scale}.${fraction}`;\n\n return units < 0n && figure !== \"0\" ? `-${figure}` : figure;\n}\n\n/**\n * Throws unless `decimals` is a whole number from 0 to {@link MAX_TOKEN_DECIMALS}.\n *\n * @throws {TypeError} naming `method` when it is not.\n */\nfunction checkDecimals(method: string, decimals: number): void {\n if (!Number.isSafeInteger(decimals) || decimals < 0 || decimals > MAX_TOKEN_DECIMALS) {\n throw new TypeError(`${method}: decimals must be a whole number from 0 to ${MAX_TOKEN_DECIMALS}`);\n }\n}\n","import { DEPOSIT_NATIVE_SELECTOR, PERMIT2_ADDRESS, RELAY_DEPOSITORY_ADDRESS } from \"#/client/constants\";\nimport {\n type Eip712StepDto,\n type EvmTransactionPayloadDto,\n type EvmTransactionStepDto,\n type SolanaTransactionStepDto,\n PAY_IN_TERMINAL_STATES,\n type PayInDestinationDto,\n type PayInDto,\n type PayInLegDto,\n type PayInStepBaseDto,\n type PayInStepDto,\n type PayInTerminalStateDto,\n} from \"#/models\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\nimport { CALLDATA_PATTERN } from \"#/shared/patterns\";\n\nimport { evmChainHex, parseCaip19, parseCaip2 } from \"./caip\";\nimport { parseBaseUnits } from \"./units\";\n\nimport type { PayInStepKind } from \"./types\";\n\n/**\n * A hex quantity as an `evm_transaction` payload writes its value, gas and fees: `0x` and at least one hex digit.\n */\nconst HEX_QUANTITY_PATTERN = /^0x[0-9a-fA-F]+$/;\n\n/**\n * The selector of ERC-20 `approve(address,uint256)`, lowercase with its `0x`.\n */\nconst APPROVE_SELECTOR = \"0x095ea7b3\";\n\nconst TRANSFER_SELECTOR = \"0xa9059cbb\";\n\nconst TEMPO_FEE_MANAGER = \"0xfeec000000000000000000000000000000000000\";\nconst SET_USER_TOKEN_SELECTOR = \"0xe7897444\";\nconst TEMPO_CHAIN_HEX = \"0x1079\";\n\n/**\n * The length of ERC-20 approval or transfer calldata: `0x`, the 4-byte selector and two 32-byte words.\n */\nconst ERC20_CALLDATA_LENGTH = 2 + 8 + 64 + 64;\n\n/**\n * The length of `depositNative(address,bytes32)` calldata as text: `0x`, the 4-byte selector and two 32-byte words.\n */\nconst DEPOSIT_NATIVE_CALLDATA_LENGTH = 2 + 8 + 64 + 64;\n\n/**\n * An ABI-encoded address word as text without `0x`: 12 zero bytes (24 zero digits), then 20 bytes of address.\n */\nconst ADDRESS_WORD_PATTERN = /^0{24}[0-9a-fA-F]{40}$/;\n\n/**\n * {@link PERMIT2_ADDRESS} as an ABI-encoded address word: 12 zero bytes, then the address, lowercase, without `0x`.\n */\nconst PERMIT2_SPENDER_WORD = `${\"0\".repeat(24)}${PERMIT2_ADDRESS.slice(2).toLowerCase()}`;\n\n/**\n * The `primaryType` of mechanism `V`'s one step: a plain Permit2 transfer with no witness, which Stridge's relayer\n * sends. Checked field by field ({@link isRelayedTransfer}), since no witness binds what the signature allows.\n */\nconst RELAYED_TRANSFER_TYPE = \"PermitTransferFrom\";\n\n/**\n * The exact `types` of a {@link RELAYED_TRANSFER_TYPE} step, each list as `[name, type]` in order, as core writes them.\n */\nconst RELAYED_TRANSFER_TYPES: Readonly<Record<string, readonly (readonly [string, string])[]>> = {\n EIP712Domain: [\n [\"name\", \"string\"],\n [\"chainId\", \"uint256\"],\n [\"verifyingContract\", \"address\"],\n ],\n [RELAYED_TRANSFER_TYPE]: [\n [\"permitted\", \"TokenPermissions\"],\n [\"spender\", \"address\"],\n [\"nonce\", \"uint256\"],\n [\"deadline\", \"uint256\"],\n ],\n TokenPermissions: [\n [\"token\", \"address\"],\n [\"amount\", \"uint256\"],\n ],\n};\n\n/**\n * A `uint256` as core writes it in typed data: a decimal string with no leading zero.\n */\nconst DECIMAL_UINT_PATTERN = /^(0|[1-9][0-9]*)$/;\n\n/**\n * The zero EVM address, lowercase.\n */\nconst ZERO_ADDRESS = `0x${\"0\".repeat(40)}`;\n\n/**\n * The `primaryType`s of the typed-data kinds whose type alone names them (pay-in guide §6.1). `Permit` is K3 or K4\n * depending on its fields, so it is told apart by {@link permitKind}.\n */\nconst EIP712_KINDS: Readonly<Record<string, PayInStepKind>> = {\n ReceiveWithAuthorization: \"K1\",\n PermitBatchWitnessTransferFrom: \"K2\",\n PermitWitnessTransferFrom: \"K2\",\n [RELAYED_TRANSFER_TYPE]: \"K2\",\n MetaTransaction: \"K5\",\n SignedBatchedCall: \"K6\",\n};\n\n/**\n * The fields of an EIP-2612 `Permit` (K3), in order.\n */\nconst EIP2612_PERMIT_FIELDS = [\"owner\", \"spender\", \"value\", \"nonce\", \"deadline\"] as const;\n\n/**\n * The fields of a DAI-style `Permit` (K4), in order.\n */\nconst DAI_PERMIT_FIELDS = [\"holder\", \"spender\", \"nonce\", \"expiry\", \"allowed\"] as const;\n\n/**\n * Reports whether the status closes ordinary pay-in actions. Use {@link isPayInSettled} to decide when to stop polling.\n */\nexport function isPayInTerminalState(state: unknown): state is PayInTerminalStateDto {\n return PAY_IN_TERMINAL_STATES.some((terminal) => terminal === state);\n}\n\n/** A canceled or failed pay-in can still complete while Core supplies a late-transfer poll hint. */\nexport function isPayInSettled(read: Pick<PayInDto, \"status\" | \"poll_after_ms\">): boolean {\n return (\n read.status === \"completed\" ||\n read.status === \"expired\" ||\n ((read.status === \"canceled\" || read.status === \"failed\") && read.poll_after_ms == null)\n );\n}\n\n/**\n * The step to do now (pay-in guide §5.6): the entry of `steps` that `required_steps[0]` names. `null` when the pay-in\n * is terminal, when nothing is required (a `processing` pay-in waiting on a chain, a bridge or the drip), or when no\n * step has that id. Never a step from history: only `required_steps` is acted on after confirm, one step at a time and\n * in order, since the next step often exists only once the previous one lands. Pure.\n */\nexport function nextRequiredStep(payIn: Pick<PayInDto, \"status\" | \"steps\" | \"required_steps\">): PayInStepDto | null {\n if (isPayInTerminalState(payIn.status)) {\n return null;\n }\n const stepId = payIn.required_steps[0];\n if (stepId === undefined) {\n return null;\n }\n\n return payIn.steps.find((step) => step.id === stepId) ?? null;\n}\n\n/**\n * Names a pay-in step's kind (pay-in guide §6.1): `K8` for `solana_transaction`, `K7` for `evm_transaction`, and\n * for an `eip712` the kind its payload's `primaryType` names, a `Permit` told apart by its fields. `\"unknown\"` for any\n * other scheme, a typed-data type outside the list, or a `Permit` with neither field list: such a step is never\n * signed. The kind is for choosing the copy and the wallet call; it says nothing about whether the payload is sound,\n * which {@link isSignablePayInStep} checks. Pure.\n */\nexport function payInStepKind(step: Pick<PayInStepBaseDto, \"scheme\" | \"payload\">): PayInStepKind | \"unknown\" {\n if (step.scheme === \"solana_transaction\") return \"K8\";\n if (step.scheme === \"evm_transaction\") {\n return \"K7\";\n }\n if (step.scheme !== \"eip712\" || !isJsonObject(step.payload) || typeof step.payload.primaryType !== \"string\") {\n return \"unknown\";\n }\n const { primaryType } = step.payload;\n if (primaryType === \"Permit\") {\n return permitKind(step.payload.types);\n }\n\n return Object.hasOwn(EIP712_KINDS, primaryType) ? EIP712_KINDS[primaryType] : \"unknown\";\n}\n\n/**\n * The instant, in epoch milliseconds, by which every one of `steps` must be signed or sent and submitted: the earliest\n * of their `expires_at` and, while the pay-in is `requires_confirmation`, its own `expires_at` (the confirm\n * deadline); after confirm, its `deadline` when it has one instead. At quote time pass every quote step (a Solana step\n * lives about 40 s, the quote 60 s); after confirm, the required step.\n *\n * `null` when there is no instant at all, or one does not parse: no deadline can be proven, so treat it as passed and\n * sign nothing. Compare it with a server-corrected clock, less a margin for the wallet prompt. Pure.\n */\nexport function earliestPayInExpiry(\n payIn: Pick<PayInDto, \"status\" | \"expires_at\" | \"deadline\">,\n steps: readonly Pick<PayInStepBaseDto, \"expires_at\">[],\n): number | null {\n const instants = steps.map((step) => step.expires_at);\n if (payIn.status === \"requires_confirmation\") {\n instants.push(payIn.expires_at);\n } else if (typeof payIn.deadline === \"string\") {\n instants.push(payIn.deadline);\n }\n if (instants.length === 0) {\n return null;\n }\n const times = instants.map((instant) => (typeof instant === \"string\" ? Date.parse(instant) : Number.NaN));\n if (times.some((time) => Number.isNaN(time))) {\n return null;\n }\n\n return Math.min(...times);\n}\n\n/**\n * Reports whether a wallet may be asked to sign or send `step` (pay-in guide §8): its scheme is known and its payload\n * holds what that wallet call needs, checked by value, since a pay-in answer is read without checking any payload.\n * The kit runs it before every wallet prompt; a step that fails it is never signed: cancel the pay-in and report it\n * (§8.4). Pure.\n *\n * - `eip712` — the step is on an `eip155` chain; the payload has an object `types` whose every entry is a list of\n * `{ name, type }` strings and which holds `EIP712Domain` and the `primaryType`; a `primaryType` whose kind is K1 to\n * K6 ({@link payInStepKind}); an object `domain` and `message`; and no number anywhere that is not a safe integer.\n * `JSON.parse` rounds a larger number, so the payload passed to the wallet would no longer be the one core sent, and\n * the step is refused rather than signed altered. A K2 `PermitTransferFrom` (mechanism `V`) has exactly core's\n * types, domain name and field shapes ({@link isRelayedTransfer}). Permit2 is bound where the kind says it must be, any case of\n * {@link PERMIT2_ADDRESS} accepted: a K2 transfer's `domain.verifyingContract` is Permit2, a K3 or K4 permit's\n * `message.spender` is Permit2, and a K5 meta-transaction's `message.functionSignature` is\n * `approve(PERMIT2_ADDRESS, amount)` calldata. Core puts a signed approval on chain without the user paying gas, so\n * one naming any other spender is never signed.\n * - `evm_transaction` — `from` and `to` are EVM addresses, `data` is `0x` and whole bytes of hex, `value`, `gas`,\n * `max_fee_per_gas` and `max_priority_fee_per_gas` are hex quantities, `chain_id` is exactly the step's chain as\n * {@link evmChainHex} writes it, and the call has the shape of a Permit2 approval, Tempo fee-coin step, coin send, or wallet transfer.\n * A wallet transfer must also pass {@link isWalletTransfer} against its leg and destination before a prompt.\n *\n * - `solana_transaction` — a Solana CAIP-2 chain and nonempty message/fee-payer strings. The hub's lazy signer\n * validates the v0 message bytes, sponsor, user and instructions before the Wallet Standard prompt.\n *\n * Whether the step is the one to do now, whether its signer is the connected wallet (and a coin send's depositor and\n * value its leg's), and whether it has expired are the caller's to check ({@link nextRequiredStep}, {@link earliestPayInExpiry}).\n */\nexport function isSignablePayInStep(\n step: PayInStepDto,\n): step is Eip712StepDto | EvmTransactionStepDto | SolanaTransactionStepDto {\n if (!isJsonObject(step) || !isJsonObject(step.payload) || typeof step.chain !== \"string\") {\n return false;\n }\n switch (step.scheme) {\n case \"solana_transaction\":\n return (\n parseCaip2(step.chain)?.namespace === \"solana\" &&\n typeof step.payload.message === \"string\" &&\n step.payload.message.length > 0 &&\n typeof step.payload.fee_payer === \"string\" &&\n step.payload.fee_payer.length > 0\n );\n case \"eip712\":\n return isSignableEip712(step.chain, step.payload, payInStepKind(step));\n case \"evm_transaction\":\n return isSendableEvmTransaction(step.chain, step.payload);\n default:\n return false;\n }\n}\n\n/**\n * Reports whether an `evm_transaction` payload is ERC-20 `approve(PERMIT2_ADDRESS, amount)` that sends no native\n * value (pay-in guide §8.3, K7): `data` is the `0x095ea7b3` selector and two 32-byte words, the first of them\n * {@link PERMIT2_ADDRESS}, and `value` is a hex zero. Any amount passes, core asking for the max; that `to` is the leg's\n * source token is the caller's to check. Pure.\n */\nexport function isPermit2Approval(payload: Pick<EvmTransactionPayloadDto, \"data\" | \"value\">): boolean {\n if (!isJsonObject(payload)) {\n return false;\n }\n const { data, value } = payload;\n\n return isPermit2ApproveCalldata(data) && isHexQuantity(value) && BigInt(value) === 0n;\n}\n\n/**\n * Reads the token from a zero-value Tempo FeeManager setUserToken call, or null for any other payload.\n * The caller binds the token and sender to the leg and connected wallet before sending.\n */\nexport function tempoFeeTokenOf(payload: unknown): string | null {\n if (!isJsonObject(payload)) return null;\n const { chain_id, to, data, value } = payload;\n if (\n chain_id !== TEMPO_CHAIN_HEX ||\n typeof to !== \"string\" ||\n to.toLowerCase() !== TEMPO_FEE_MANAGER ||\n typeof data !== \"string\" ||\n data.slice(0, 10).toLowerCase() !== SET_USER_TOKEN_SELECTOR ||\n !ADDRESS_WORD_PATTERN.test(data.slice(10)) ||\n !isHexQuantity(value) ||\n BigInt(value) !== 0n\n )\n return null;\n return `0x${data.slice(34).toLowerCase()}`;\n}\n\n/**\n * Reports whether an `evm_transaction` payload is a coin send (mechanism `W`): `to` is {@link RELAY_DEPOSITORY_ADDRESS}\n * in any case, `data` is exactly the {@link DEPOSIT_NATIVE_SELECTOR} and two 32-byte words, the first a zero-padded\n * address (the depositor), and `value` is a hex quantity above zero. That the depositor is the wallet and the value is\n * at most the leg's `input_amount` are the caller's to check. Pure.\n */\nexport function isCoinSend(payload: Pick<EvmTransactionPayloadDto, \"to\" | \"data\" | \"value\">): boolean {\n if (!isJsonObject(payload)) {\n return false;\n }\n const { to, data, value } = payload;\n\n return (\n typeof to === \"string\" &&\n to.toLowerCase() === RELAY_DEPOSITORY_ADDRESS.toLowerCase() &&\n coinSendDepositor(data) !== null &&\n isHexQuantity(value) &&\n BigInt(value) > 0n\n );\n}\n\n/**\n * Whether the calldata and value have the shape of a native or ERC-20 wallet transfer.\n */\nfunction isWalletTransferShape(data: string, value: string): boolean {\n if (!isHexQuantity(value)) return false;\n if (data === \"0x\") return BigInt(value) > 0n;\n return (\n data.length === ERC20_CALLDATA_LENGTH &&\n data.slice(0, 10).toLowerCase() === TRANSFER_SELECTOR &&\n CALLDATA_PATTERN.test(data) &&\n ADDRESS_WORD_PATTERN.test(data.slice(10, 74)) &&\n BigInt(value) === 0n\n );\n}\n\n/**\n * Binds an X, Y or U transfer to its leg's chain, asset and exact input, and to the pay-in's recipient. Y and U\n * move only ERC-20 tokens.\n * The caller checks the enclosing step, connected sender and reviewed destination separately.\n */\nexport function isWalletTransfer(\n payload: EvmTransactionPayloadDto,\n leg: Pick<PayInLegDto, \"mechanism\" | \"source_asset\" | \"input_amount\">,\n destination: PayInDestinationDto,\n): boolean {\n if ((leg.mechanism !== \"X\" && leg.mechanism !== \"Y\" && leg.mechanism !== \"U\") || !isJsonObject(payload)) return false;\n const source = parseCaip19(leg.source_asset);\n const chain = source === null ? null : evmChainHex(source.chain);\n const amount = parseBaseUnits(leg.input_amount);\n const { to, data, value, chain_id } = payload;\n if (\n source === null ||\n chain === null ||\n chain_id !== chain ||\n amount === null ||\n amount <= 0n ||\n !isEvmAddress(destination.address) ||\n !isEvmAddress(to) ||\n typeof data !== \"string\" ||\n !isWalletTransferShape(data, value)\n )\n return false;\n\n if (source.assetNamespace === \"slip44\") {\n return (\n leg.mechanism === \"X\" &&\n /^[0-9]+$/.test(source.assetReference) &&\n leg.source_asset === destination.asset &&\n data === \"0x\" &&\n to.toLowerCase() === destination.address.toLowerCase() &&\n BigInt(value) === amount\n );\n }\n const token = source.assetReference;\n const target = parseCaip19(destination.asset);\n return (\n source.assetNamespace === \"erc20\" &&\n isEvmAddress(token) &&\n target?.chain === source.chain &&\n target.assetNamespace === \"erc20\" &&\n isEvmAddress(target.assetReference) &&\n token.toLowerCase() === target.assetReference.toLowerCase() &&\n to.toLowerCase() === token.toLowerCase() &&\n data !== \"0x\" &&\n data.slice(34, 74).toLowerCase() === destination.address.slice(2).toLowerCase() &&\n BigInt(`0x${data.slice(74)}`) === amount\n );\n}\n\n/**\n * The depositor a coin send's `data` names (its first word), as `0x` and 40 lowercase hex digits, or `null` when\n * `data` is not coin-send calldata ({@link isCoinSend}). Pure.\n */\nexport function coinSendDepositor(data: unknown): string | null {\n if (\n typeof data !== \"string\" ||\n data.length !== DEPOSIT_NATIVE_CALLDATA_LENGTH ||\n data.slice(0, 10).toLowerCase() !== DEPOSIT_NATIVE_SELECTOR ||\n !CALLDATA_PATTERN.test(data) ||\n !ADDRESS_WORD_PATTERN.test(data.slice(10, 74))\n ) {\n return null;\n }\n\n return `0x${data.slice(34, 74).toLowerCase()}`;\n}\n\n/**\n * Reports whether `data` is ERC-20 `approve(PERMIT2_ADDRESS, amount)` calldata, any amount: the `0x095ea7b3` selector\n * and two 32-byte words, the first of them {@link PERMIT2_ADDRESS}, either case. A K7 transaction's `data` and a K5\n * meta-transaction's `functionSignature` are both read with it.\n */\nfunction isPermit2ApproveCalldata(data: unknown): data is string {\n return (\n typeof data === \"string\" &&\n data.length === ERC20_CALLDATA_LENGTH &&\n CALLDATA_PATTERN.test(data) &&\n data.slice(0, 10).toLowerCase() === APPROVE_SELECTOR &&\n data.slice(10, 74).toLowerCase() === PERMIT2_SPENDER_WORD\n );\n}\n\n/**\n * Reports whether `value` is {@link PERMIT2_ADDRESS}, in any case.\n */\nfunction isPermit2Address(value: unknown): boolean {\n return typeof value === \"string\" && value.toLowerCase() === PERMIT2_ADDRESS.toLowerCase();\n}\n\n/**\n * The kind of a typed-data `Permit`: K3 when `types.Permit` lists the EIP-2612 fields in order, K4 when it lists the\n * DAI-style ones, `\"unknown\"` otherwise.\n */\nfunction permitKind(types: unknown): PayInStepKind | \"unknown\" {\n if (!isJsonObject(types) || !Array.isArray(types.Permit)) {\n return \"unknown\";\n }\n const names = types.Permit.map((field: unknown) => (isJsonObject(field) ? field.name : undefined));\n if (hasFieldNames(names, EIP2612_PERMIT_FIELDS)) {\n return \"K3\";\n }\n if (hasFieldNames(names, DAI_PERMIT_FIELDS)) {\n return \"K4\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Reports whether `names` is exactly `expected`, in order.\n */\nfunction hasFieldNames(names: readonly unknown[], expected: readonly string[]): boolean {\n return names.length === expected.length && expected.every((name, index) => names[index] === name);\n}\n\n/**\n * The `eip712` rule of {@link isSignablePayInStep}.\n */\nfunction isSignableEip712(chain: string, payload: Record<string, unknown>, kind: PayInStepKind | \"unknown\"): boolean {\n const { types, primaryType, domain, message } = payload;\n\n return (\n evmChainHex(chain) !== null &&\n isEip712Types(types) &&\n Object.hasOwn(types, \"EIP712Domain\") &&\n typeof primaryType === \"string\" &&\n Object.hasOwn(types, primaryType) &&\n isJsonObject(domain) &&\n isJsonObject(message) &&\n isTypedDataKind(kind) &&\n bindsPermit2(kind, domain, message) &&\n (primaryType !== RELAYED_TRANSFER_TYPE || isRelayedTransfer(types, domain, message)) &&\n hasOnlySafeIntegers(payload)\n );\n}\n\n/**\n * Reports whether typed data of `kind` binds Permit2 where that kind must (pay-in guide §6.1): a K2 transfer's\n * `domain.verifyingContract` is Permit2, a K3 or K4 permit's `message.spender` is Permit2, and a K5\n * meta-transaction's `message.functionSignature` approves Permit2 ({@link isPermit2ApproveCalldata}). K1 and K6 name\n * no Permit2 and pass; any other kind fails.\n */\nfunction bindsPermit2(\n kind: PayInStepKind | \"unknown\",\n domain: Record<string, unknown>,\n message: Record<string, unknown>,\n): boolean {\n switch (kind) {\n case \"K1\":\n case \"K6\":\n return true;\n case \"K2\":\n return isPermit2Address(domain.verifyingContract);\n case \"K3\":\n case \"K4\":\n return isPermit2Address(message.spender);\n case \"K5\":\n return isPermit2ApproveCalldata(message.functionSignature);\n default:\n return false;\n }\n}\n\n/**\n * Reports whether a `PermitTransferFrom` is exactly core's relayed transfer: `types` holds only\n * {@link RELAYED_TRANSFER_TYPES}, field for field and in order; the domain, the message and `permitted` hold exactly\n * the declared keys, so a wallet that reads the keys signs the digest core issued; the domain is named `Permit2` with\n * a positive number `chainId`; `permitted` is one `{ token, amount }`; `spender` is a nonzero address; and the amount,\n * nonce and deadline are decimal `uint256` strings.\n * The spender is core's relayer, which differs by environment, so it is not pinned: which token, how much and until\n * when are the caller's to check against the leg.\n */\nfunction isRelayedTransfer(\n types: Record<string, unknown[]>,\n domain: Record<string, unknown>,\n message: Record<string, unknown>,\n): boolean {\n const { permitted } = message;\n return (\n Object.keys(types).length === Object.keys(RELAYED_TRANSFER_TYPES).length &&\n Object.entries(RELAYED_TRANSFER_TYPES).every(\n ([name, fields]) =>\n Object.hasOwn(types, name) &&\n types[name]!.length === fields.length &&\n fields.every(([field, type], index) => {\n const entry = types[name]![index];\n return isJsonObject(entry) && entry.name === field && entry.type === type;\n }),\n ) &&\n hasExactKeys(domain, [\"name\", \"chainId\", \"verifyingContract\"]) &&\n domain.name === \"Permit2\" &&\n Number.isSafeInteger(domain.chainId) &&\n (domain.chainId as number) > 0 &&\n hasExactKeys(message, [\"permitted\", \"spender\", \"nonce\", \"deadline\"]) &&\n isJsonObject(permitted) &&\n hasExactKeys(permitted, [\"token\", \"amount\"]) &&\n isEvmAddress(permitted.token) &&\n isDecimalUint(permitted.amount) &&\n isEvmAddress(message.spender) &&\n message.spender.toLowerCase() !== ZERO_ADDRESS &&\n isDecimalUint(message.nonce) &&\n isDecimalUint(message.deadline)\n );\n}\n\n/**\n * Reports whether `value` has exactly the keys `keys`, in any order.\n */\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n const own = Object.keys(value);\n return own.length === keys.length && keys.every((key) => Object.hasOwn(value, key));\n}\n\n/**\n * Reports whether `value` is a `uint256` as a decimal string ({@link DECIMAL_UINT_PATTERN}) below 2^256.\n */\nfunction isDecimalUint(value: unknown): value is string {\n return typeof value === \"string\" && DECIMAL_UINT_PATTERN.test(value) && BigInt(value) < 2n ** 256n;\n}\n\n/**\n * Reports whether `value` is a typed-data `types` object: every entry a list of `{ name, type }` with string values.\n */\nfunction isEip712Types(value: unknown): value is Record<string, unknown[]> {\n return (\n isJsonObject(value) &&\n Object.values(value).every(\n (fields) =>\n Array.isArray(fields) &&\n fields.every(\n (field: unknown) => isJsonObject(field) && typeof field.name === \"string\" && typeof field.type === \"string\",\n ),\n )\n );\n}\n\n/**\n * Reports whether `kind` is one the EVM wallet signs as typed data, K1 to K6.\n */\nfunction isTypedDataKind(kind: PayInStepKind | \"unknown\"): boolean {\n return [\"K1\", \"K2\", \"K3\", \"K4\", \"K5\", \"K6\"].includes(kind);\n}\n\n/**\n * Reports whether every number anywhere inside `root` is a safe integer. Walks with its own stack, so a deeply nested\n * payload cannot overflow the call stack, and visits each object once.\n */\nfunction hasOnlySafeIntegers(root: unknown): boolean {\n const pending: unknown[] = [root];\n const seen = new Set<object>();\n while (pending.length > 0) {\n const value = pending.pop();\n if (typeof value === \"number\" && !Number.isSafeInteger(value)) {\n return false;\n }\n if (typeof value === \"object\" && value !== null && !seen.has(value)) {\n seen.add(value);\n for (const child of Object.values(value)) {\n pending.push(child);\n }\n }\n }\n\n return true;\n}\n\n/**\n * The `evm_transaction` rule of {@link isSignablePayInStep}.\n */\nfunction isSendableEvmTransaction(chain: string, payload: Record<string, unknown>): boolean {\n const chainHex = evmChainHex(chain);\n\n return (\n chainHex !== null &&\n payload.chain_id === chainHex &&\n isEvmAddress(payload.from) &&\n isEvmAddress(payload.to) &&\n typeof payload.data === \"string\" &&\n CALLDATA_PATTERN.test(payload.data) &&\n isHexQuantity(payload.value) &&\n isHexQuantity(payload.gas) &&\n isHexQuantity(payload.max_fee_per_gas) &&\n isHexQuantity(payload.max_priority_fee_per_gas) &&\n (isPermit2Approval({ data: payload.data, value: payload.value }) ||\n isCoinSend({ to: payload.to, data: payload.data, value: payload.value }) ||\n tempoFeeTokenOf(payload) !== null ||\n isWalletTransferShape(payload.data, payload.value))\n );\n}\n\n/**\n * Reports whether `value` is an EVM address: `0x` and 40 hex digits, any case.\n */\nfunction isEvmAddress(value: unknown): value is string {\n return typeof value === \"string\" && EVM_ADDRESS_PATTERN.test(value);\n}\n\n/**\n * Reports whether `value` is a hex quantity: `0x` and at least one hex digit.\n */\nfunction isHexQuantity(value: unknown): value is string {\n return typeof value === \"string\" && HEX_QUANTITY_PATTERN.test(value);\n}\n","/**\n * The default `Sleep`: a `setTimeout` of `ms` (negative values count as `0`). When `signal` is already aborted it\n * rejects with `signal.reason` without scheduling anything; when `signal` aborts during the wait it clears the timer\n * and rejects with `signal.reason`. The abort listener is removed once the wait settles either way.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n\n const onAbort = (): void => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n reject(signal?.reason);\n };\n\n const timer = setTimeout(\n () => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n },\n ms > 0 ? ms : 0,\n );\n\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import { sleep as defaultSleep } from \"./sleep\";\n\nimport type { WaitForActiveWalletOptions, WaitForActiveWalletOutcome } from \"./types\";\n\n/**\n * Polls `GET /wallet/v1/account` until the wallet is active, closed, or the attempts run out (guide §5, §10).\n * Every read counts against the session's 120-a-minute limit, which the default 1.5 s\n * interval keeps well under.\n *\n * Since Coordinator rc.19 nothing is polled on the normal path: verify returns the wallet, and a keypair registration\n * waits on the server for it to become active. Use this only for a short, bounded read (a small `maxAttempts`), such\n * as fetching `provider_account_ref` once after the first registration.\n *\n * The loop, for `attempt` from 1 to `maxAttempts`:\n *\n * 1. `signal?.throwIfAborted()`.\n * 2. `wallet = await getWallet({ signal })`. The first read happens at once.\n * 3. `wallet.status === \"active\"`, and (when `requireWalletRef`) `wallet.provider_account_ref !== \"\"`\n * → resolve `{ kind: \"active\", wallet }`.\n * 4. `wallet.status === \"wound_down\"` → resolve `{ kind: \"wound-down\", wallet }`.\n * 5. `attempt === maxAttempts` → resolve `{ kind: \"timeout\", wallet }`.\n * 6. `await sleep(intervalMs, signal)` and continue.\n *\n * So `getWallet` is called at most `maxAttempts` times and `sleep` at most `maxAttempts - 1` times. An active wallet\n * with an empty `provider_account_ref` keeps polling. Errors from `getWallet` propagate at once, without a retry. An\n * abort rejects with `signal.reason`.\n *\n * @throws {TypeError} (as a rejection) when `maxAttempts` is not a positive integer or `intervalMs` is negative.\n */\nexport async function waitForActiveWallet(options: WaitForActiveWalletOptions): Promise<WaitForActiveWalletOutcome> {\n const { getWallet, signal, intervalMs = 1500, maxAttempts = 80, requireWalletRef = true, sleep = defaultSleep } = options;\n\n if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {\n throw new TypeError(\"waitForActiveWallet: maxAttempts must be a positive integer\");\n }\n if (!Number.isFinite(intervalMs) || intervalMs < 0) {\n throw new TypeError(\"waitForActiveWallet: intervalMs must be a non-negative finite number\");\n }\n\n for (let attempt = 1; ; attempt += 1) {\n signal?.throwIfAborted();\n const wallet = await getWallet({ signal });\n if (wallet.status === \"active\" && (!requireWalletRef || wallet.provider_account_ref !== \"\")) {\n return { kind: \"active\", wallet };\n }\n if (wallet.status === \"wound_down\") {\n return { kind: \"wound-down\", wallet };\n }\n if (attempt === maxAttempts) {\n return { kind: \"timeout\", wallet };\n }\n await sleep(intervalMs, signal);\n }\n}\n","import { sleep as defaultSleep } from \"./sleep\";\n\nimport type { WaitForRoundOptions, WaitForRoundOutcome } from \"./types\";\n\n/**\n * Whether `value` is a finite number above zero.\n */\nfunction isPositiveFinite(value: number): boolean {\n return Number.isFinite(value) && value > 0;\n}\n\n/**\n * Polls `GET /wallet/v1/auth-rounds/{id}` until the round is ready, failed, or ends (guide §3.2). Only an open that answered\n * `202` needs it: a `200` open already carries the ready round. A `202` (`status: \"opening\"`) means still opening;\n * that includes an unknown round and a decoy, so besides `ready` and `failed` the only stop is `expires_at`.\n *\n * The loop, with `attempt` starting at 0:\n *\n * 1. `signal?.throwIfAborted()`.\n * 2. `round = await getRound(roundId, { signal })`. The first read happens at once, with no initial wait.\n * 3. `round.status === \"ready\"` → resolve `{ kind: \"ready\", round }`; `round.status === \"failed\"` → resolve\n * `{ kind: \"failed\" }` at once, whatever time is left.\n * 4. `remaining = expiresAtMs - now()`. `remaining <= 0` → resolve `{ kind: \"expired\" }`.\n * 5. `await sleep(min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal)`, then\n * `attempt += 1` and go to 1. So with the defaults the waits are 250, 500, 1000, 1000, … ms, and the last read\n * lands at `expires_at`.\n *\n * Errors from `getRound` (a `SuaNetworkError`, say) propagate at once, without a retry; the caller may call again\n * for the same round. An abort rejects with `signal.reason`.\n *\n * Pure apart from the injected `getRound`, `sleep` and `now`.\n *\n * @throws {TypeError} (as a rejection, before the first read) when `expiresAt` does not parse with `Date.parse`,\n * `initialIntervalMs` or `maxIntervalMs` is not a positive finite number, or `backoffFactor` is below `1`.\n */\nexport async function waitForRound(options: WaitForRoundOptions): Promise<WaitForRoundOutcome> {\n const {\n getRound,\n roundId,\n expiresAt,\n signal,\n initialIntervalMs = 250,\n maxIntervalMs = 1000,\n backoffFactor = 2,\n sleep = defaultSleep,\n now = Date.now,\n } = options;\n\n const expiresAtMs = Date.parse(expiresAt);\n if (Number.isNaN(expiresAtMs)) {\n throw new TypeError(\"waitForRound: expiresAt must be an RFC 3339 instant\");\n }\n if (!isPositiveFinite(initialIntervalMs)) {\n throw new TypeError(\"waitForRound: initialIntervalMs must be a positive finite number\");\n }\n if (!isPositiveFinite(maxIntervalMs)) {\n throw new TypeError(\"waitForRound: maxIntervalMs must be a positive finite number\");\n }\n if (!(backoffFactor >= 1)) {\n throw new TypeError(\"waitForRound: backoffFactor must be at least 1\");\n }\n\n for (let attempt = 0; ; attempt += 1) {\n signal?.throwIfAborted();\n const round = await getRound(roundId, { signal });\n if (round.status === \"ready\") {\n return { kind: \"ready\", round };\n }\n if (round.status === \"failed\") {\n return { kind: \"failed\" };\n }\n const remaining = expiresAtMs - now();\n if (remaining <= 0) {\n return { kind: \"expired\" };\n }\n await sleep(Math.min(initialIntervalMs * backoffFactor ** attempt, maxIntervalMs, remaining), signal);\n }\n}\n","import { toHex } from \"#/encoding\";\nimport type { SignRawPayloadActivityDto } from \"#/models\";\nimport { EVM_ADDRESS_PATTERN } from \"#/protocol/constants\";\n\nimport type { SignRawPayloadInput } from \"./types\";\n\n/**\n * Builds the `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2` body for an EVM message signature (guide §7.1, §12.7): the exact\n * string to sign and relay, never re-serialised afterwards. Keep it: `settleRelay` compares the answer with it.\n *\n * Returns `JSON.stringify` of an object literal written in exactly this key order (a `SignRawPayloadActivityDto`):\n * `type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\"`, `timestampMs: String(input.signedAtMs)`, `organizationId:\n * input.walletRef`, `parameters: { signWith: input.evmAddress, payload: toHex(input.payload), encoding:\n * \"PAYLOAD_ENCODING_HEXADECIMAL\", hashFunction: \"HASH_FUNCTION_KECCAK256\" }`. The payload hex is lowercase with no\n * `0x`; the address is kept verbatim.\n *\n * Vector (§12.7): `{ walletRef: \"497b3e43-6b9d-4555-b839-5b791701aa43\", evmAddress:\n * \"0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716\", payload: utf8ToBytes(\"stridge relay smoke test\"), signedAtMs:\n * 1790000000000 }` returns the §12.7 body byte for byte.\n *\n * @throws {TypeError} when `walletRef` is empty, `evmAddress` is not `0x` plus 40 hex digits, `payload` is empty, or\n * `signedAtMs` is not a non-negative safe integer.\n */\nexport function buildSignRawPayloadBody(input: SignRawPayloadInput): string {\n const { walletRef, evmAddress, payload, signedAtMs } = input;\n if (typeof walletRef !== \"string\" || walletRef === \"\") {\n throw new TypeError(\"buildSignRawPayloadBody: walletRef must be a non-empty string\");\n }\n if (typeof evmAddress !== \"string\" || !EVM_ADDRESS_PATTERN.test(evmAddress)) {\n throw new TypeError(\"buildSignRawPayloadBody: evmAddress must be 0x followed by 40 hex digits\");\n }\n if (!(payload instanceof Uint8Array) || payload.length === 0) {\n throw new TypeError(\"buildSignRawPayloadBody: payload must be a non-empty Uint8Array\");\n }\n if (!Number.isSafeInteger(signedAtMs) || signedAtMs < 0) {\n throw new TypeError(\"buildSignRawPayloadBody: signedAtMs must be a non-negative safe integer\");\n }\n\n const activity: SignRawPayloadActivityDto = {\n type: \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\",\n timestampMs: String(signedAtMs),\n organizationId: walletRef,\n parameters: {\n signWith: evmAddress,\n payload: toHex(payload),\n encoding: \"PAYLOAD_ENCODING_HEXADECIMAL\",\n hashFunction: \"HASH_FUNCTION_KECCAK256\",\n },\n };\n return JSON.stringify(activity);\n}\n","/**\n * The EIP-191 version `0x45` (\"E\") prefix of a personal message, before the decimal byte length: the byte `0x19`, then\n * `Ethereum Signed Message:` and a line feed.\n */\nexport const PERSONAL_MESSAGE_PREFIX = \"\\x19Ethereum Signed Message:\\n\";\n\n/**\n * The order n of the secp256k1 group. A signature's `s` above `n / 2` is \"high\"; the low-s form is `n - s`.\n */\nexport const SECP256K1_ORDER = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n;\n\n/**\n * r and s of a secp256k1 signature: 32 bytes as 64 hex digits, either case.\n */\nexport const SCALAR_HEX_PATTERN = /^[0-9a-fA-F]{64}$/;\n","import { utf8ToBytes } from \"#/encoding\";\n\nimport { buildSignRawPayloadBody } from \"./buildSignRawPayloadBody\";\nimport { PERSONAL_MESSAGE_PREFIX } from \"./constants\";\n\nimport type { PersonalSignBody, PersonalSignInput } from \"./types\";\n\n/**\n * Builds the EIP-191 personal-message payload for a text message: the UTF-8 bytes of\n * `PERSONAL_MESSAGE_PREFIX + String(byteLength)` followed by the UTF-8 bytes of `message`, where `byteLength` is the\n * UTF-8 byte count of `message` written in decimal (`utf8ToBytes(message).length`, never `message.length`). The\n * message is always text: a `0x…` string is encoded as its characters.\n *\n * `keccak256` of the result equals viem's `hashMessage(message)`.\n *\n * Vectors:\n * - `\"hello world\"` → hex `19457468657265756d205369676e6564204d6573736167653a0a313168656c6c6f20776f726c64` (the\n * length is `11`); its keccak-256 is `d9eba16ed0ecae432b71fe008c98cc872bb4cc214d3220a36f365326cf807d68`.\n * - `\"héllo\"` has 6 UTF-8 bytes, so the length part is `\"6\"`.\n * - `\"0x1234\"` is 6 characters of text, so the length part is `\"6\"` and the bytes are `30 78 31 32 33 34`.\n *\n * @throws {TypeError} when `message` is not a non-empty string.\n */\nexport function buildPersonalSignPayload(message: string): Uint8Array {\n if (typeof message !== \"string\" || message === \"\") {\n throw new TypeError(\"buildPersonalSignPayload: message must be a non-empty string\");\n }\n const messageBytes = utf8ToBytes(message);\n const prefixBytes = utf8ToBytes(`${PERSONAL_MESSAGE_PREFIX}${String(messageBytes.length)}`);\n const payload = new Uint8Array(prefixBytes.length + messageBytes.length);\n payload.set(prefixBytes, 0);\n payload.set(messageBytes, prefixBytes.length);\n return payload;\n}\n\n/**\n * Builds the relay body for an app's `sign(message)`: the only path an app's message takes to a signature.\n *\n * 1. `payload = buildPersonalSignPayload(input.message)`.\n * 2. `body = buildSignRawPayloadBody({ walletRef: input.walletRef, evmAddress: input.evmAddress, payload, signedAtMs:\n * input.signedAtMs })`, so the body carries `PAYLOAD_ENCODING_HEXADECIMAL`, `HASH_FUNCTION_KECCAK256` and the\n * payload as lowercase hex without `0x`.\n * 3. Returns exactly `{ body, payload }`.\n *\n * Turnkey then signs `keccak256(payload)`, which is viem's `hashMessage(message)`, so the signature (after\n * `toEvmSignature`) is byte-identical to viem's `signMessage`.\n *\n * Vector: `{ walletRef: \"497b3e43-6b9d-4555-b839-5b791701aa43\", evmAddress: \"0xcD27bBba88329D4Ae8CCd0A16E4cD08f11226716\",\n * message: \"hello world\", signedAtMs: 1790000000000 }` gives a body whose `parameters.payload` is the\n * `buildPersonalSignPayload(\"hello world\")` hex above and whose other fields match the guide's relay example body.\n *\n * @throws {TypeError} when `message` is empty or not a string, and on every input `buildSignRawPayloadBody` refuses.\n */\nexport function buildPersonalSignBody(input: PersonalSignInput): PersonalSignBody {\n const payload = buildPersonalSignPayload(input.message);\n const body = buildSignRawPayloadBody({\n walletRef: input.walletRef,\n evmAddress: input.evmAddress,\n payload,\n signedAtMs: input.signedAtMs,\n });\n return { body, payload };\n}\n","import { bytesToUtf8, fromBase64 } from \"#/encoding\";\nimport type { RelayResponseDto } from \"#/models\";\nimport { isJsonObject } from \"#/shared/isJsonObject\";\n\nimport { SCALAR_HEX_PATTERN } from \"./constants\";\n\nimport type { RelayResult } from \"./types\";\n\n/**\n * The only recovery ids the hub can build an EVM signature from.\n */\nconst RECOVERY_IDS: ReadonlySet<string> = new Set([\"00\", \"01\"]);\n\n/**\n * The only activity type this decoder reads a result for.\n */\nconst SIGN_RAW_PAYLOAD_TYPE = \"ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2\";\n\n/**\n * gRPC codes that prove Turnkey refused the request before acting on it: `INVALID_ARGUMENT` (3), `NOT_FOUND` (5),\n * `ALREADY_EXISTS` (6), `PERMISSION_DENIED` (7), `RESOURCE_EXHAUSTED` (8), `FAILED_PRECONDITION` (9), `OUT_OF_RANGE`\n * (11), `UNIMPLEMENTED` (12) and `UNAUTHENTICATED` (16). Every other code (`CANCELLED`, `UNKNOWN`,\n * `DEADLINE_EXCEEDED`, `ABORTED`, `INTERNAL`, `UNAVAILABLE`, `DATA_LOSS`) is what a server-side failure looks like, and\n * SigningRouter reads a Turnkey `5xx` as ambiguous.\n */\nconst REFUSAL_CODES: ReadonlySet<number> = new Set([3, 5, 6, 7, 8, 9, 11, 12, 16]);\n\n/**\n * Reads `provider_response` as a JSON object: standard base64, then strict UTF-8, then JSON. Returns `null` when any\n * step fails or the value is not a JSON object. Never throws.\n */\nfunction readProviderObject(providerResponse: unknown): Record<string, unknown> | null {\n if (typeof providerResponse !== \"string\" || providerResponse === \"\") {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(bytesToUtf8(fromBase64(providerResponse)));\n return isJsonObject(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Parses the signed body string back into the fields the answer must echo, or `null` when it is not a\n * `SignRawPayloadActivityDto` JSON with string fields. Never throws.\n */\nfunction readSignedBody(signedBody: unknown): Record<string, string> | null {\n if (typeof signedBody !== \"string\") {\n return null;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(signedBody);\n } catch {\n return null;\n }\n if (!isJsonObject(parsed) || !isJsonObject(parsed.parameters)) {\n return null;\n }\n const fields: Record<string, unknown> = {\n type: parsed.type,\n organizationId: parsed.organizationId,\n signWith: parsed.parameters.signWith,\n payload: parsed.parameters.payload,\n encoding: parsed.parameters.encoding,\n hashFunction: parsed.parameters.hashFunction,\n };\n const strings: Record<string, string> = {};\n for (const [key, value] of Object.entries(fields)) {\n if (typeof value !== \"string\") {\n return null;\n }\n strings[key] = value;\n }\n return strings;\n}\n\n/**\n * Whether two values are the same string, ignoring ASCII case (an address's checksum case, a hex payload's case).\n */\nfunction sameIgnoringCase(actual: unknown, expected: string): boolean {\n return typeof actual === \"string\" && actual.toLowerCase() === expected.toLowerCase();\n}\n\n/**\n * Whether a completed activity is the one that was signed: the same type (a raw-payload signature), organization,\n * address, payload, encoding and hash function. The address and the payload hex compare without case; everything\n * else compares exactly.\n */\nfunction activityMatchesSignedBody(activity: Record<string, unknown>, signedBody: unknown): boolean {\n const expected = readSignedBody(signedBody);\n if (expected === null || expected.type !== SIGN_RAW_PAYLOAD_TYPE) {\n return false;\n }\n const intent = isJsonObject(activity.intent) ? activity.intent.signRawPayloadIntentV2 : undefined;\n if (!isJsonObject(intent)) {\n return false;\n }\n return (\n activity.type === expected.type &&\n activity.organizationId === expected.organizationId &&\n sameIgnoringCase(intent.signWith, expected.signWith) &&\n sameIgnoringCase(intent.payload, expected.payload) &&\n intent.encoding === expected.encoding &&\n intent.hashFunction === expected.hashFunction\n );\n}\n\n/**\n * The relay's verdicts this decoder reads.\n */\nconst VERDICTS: ReadonlySet<unknown> = new Set([\"signed\", \"rejected\", \"partially_approved\", \"ambiguous\"]);\n\n/**\n * Decodes a relay's `200` or `202` answer into its outcome (guide §7.4). A `200` is not proof of a signature.\n *\n * A response that carries the key `verdict` (rc.55's `RelayResult`) is read by the relay's verdict first, before any\n * guess from the provider's bytes:\n *\n * - `ambiguous` → `unknown` with cause `ambiguous`, whatever the bytes hold: the request may have reached the\n * provider, so it is never a refusal.\n * - `partially_approved` → `cosignature`, with `activity_ref`.\n * - `rejected` → `refused`, with the error body's numeric `code` and string `message` when the bytes hold them, else\n * `providerCode: null` and `providerMessage: \"\"`.\n * - `signed` → steps 3 to 8 below, except that an error body (step 4) is `unknown` with cause `provider-error`,\n * never `refused`.\n * - any other value → `unknown` with cause `unreadable`.\n *\n * A response with no `verdict` (an older Coordinator) runs every step, and the first that matches wins:\n *\n * 1. `response` is not an object → `unknown` with cause `unreadable`.\n * 2. `root_activity` is a non-null object → `cosignature`.\n * 3. `provider_response` is `null`, `\"\"`, not standard base64 (`fromBase64`), not UTF-8 (`bytesToUtf8`), not JSON, or\n * not a JSON object → `unknown` with cause `unreadable`.\n * 4. The object has no `activity` key, or `activity` is not a JSON object: Turnkey's error body. Its `code` is one of\n * the client-error gRPC codes (3, 5, 6, 7, 8, 9, 11, 12, 16) → `refused`, with `providerCode` and\n * `providerMessage` (its `message` when a string, else `\"\"`). Any other code, or none → `unknown` with cause\n * `provider-error`, since SigningRouter reads a Turnkey `5xx` as ambiguous and an older Coordinator drops that\n * verdict.\n * 5. `activity.status !== \"ACTIVITY_STATUS_COMPLETED\"` → `unknown` with cause `status` and `activityStatus` (the\n * status when a string, else `null`).\n * 6. The activity is not the one in `signedBody`: its `type` is not `ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2`, its\n * `organizationId` differs, or `intent.signRawPayloadIntentV2` is missing or differs in `signWith`, `payload` (both\n * without case), `encoding` or `hashFunction` → `unknown` with cause `mismatch`.\n * 7. `activity.result.signRawPayloadResult` has `r` and `s` of 64 hex digits and `v` exactly `\"00\"` or `\"01\"` →\n * `signed`, with `r` and `s` lowercased. Any other `v` (`\"1b\"`, `\"02\"`, `\"0\"`, a number) is refused here: the hub\n * can only build an EVM signature from those two recovery ids.\n * 8. Otherwise → `unknown` with cause `unreadable`.\n *\n * `activityRef` is `response.activity_ref` when it is a string, else `\"\"`; `activityStatus` is `null` except in step\n * 5. Does not recover the signer from the signature: the caller still checks it against the wallet's address. Pure;\n * never throws.\n *\n * Vectors (§12.7): with the §12.7 body as `signedBody`, the \"Response `200`\" body is `signed` with r\n * `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `00` and activityRef `01a0e31a-743d-7894-9edc-e00e87805a51`; the\n * \"waiting for a second approval\" body is `cosignature` even though its decoded activity says `COMPLETED`.\n *\n * @param response The relay's `200` or `202` body.\n * @param signedBody The exact activity body string that was signed and relayed (`buildSignRawPayloadBody`'s result).\n */\nexport function decodeRelayResponse(response: RelayResponseDto, signedBody: string): RelayResult {\n if (!isJsonObject(response)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef: \"\", activityStatus: null };\n }\n\n const activityRef = typeof response.activity_ref === \"string\" ? response.activity_ref : \"\";\n const hasVerdict = Object.hasOwn(response, \"verdict\");\n const verdict: unknown = response.verdict;\n\n if (hasVerdict) {\n if (!VERDICTS.has(verdict)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n if (verdict === \"ambiguous\") {\n return { kind: \"unknown\", cause: \"ambiguous\", activityRef, activityStatus: null };\n }\n if (verdict === \"partially_approved\") {\n return { kind: \"cosignature\", activityRef };\n }\n if (verdict === \"rejected\") {\n const body = readProviderObject(response.provider_response);\n const code = body?.code;\n const message = body?.message;\n return {\n kind: \"refused\",\n activityRef,\n providerCode: typeof code === \"number\" ? code : null,\n providerMessage: typeof message === \"string\" ? message : \"\",\n };\n }\n } else {\n const rootActivity: unknown = response.root_activity;\n if (typeof rootActivity === \"object\" && rootActivity !== null) {\n return { kind: \"cosignature\", activityRef };\n }\n }\n\n const provider = readProviderObject(response.provider_response);\n if (provider === null) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n const activity = provider.activity;\n if (!isJsonObject(activity)) {\n const { code, message } = provider;\n if (hasVerdict || typeof code !== \"number\" || !REFUSAL_CODES.has(code)) {\n return { kind: \"unknown\", cause: \"provider-error\", activityRef, activityStatus: null };\n }\n return {\n kind: \"refused\",\n activityRef,\n providerCode: code,\n providerMessage: typeof message === \"string\" ? message : \"\",\n };\n }\n\n const status = activity.status;\n if (status !== \"ACTIVITY_STATUS_COMPLETED\") {\n return {\n kind: \"unknown\",\n cause: \"status\",\n activityRef,\n activityStatus: typeof status === \"string\" ? status : null,\n };\n }\n\n if (!activityMatchesSignedBody(activity, signedBody)) {\n return { kind: \"unknown\", cause: \"mismatch\", activityRef, activityStatus: null };\n }\n\n const result = activity.result;\n const signature = isJsonObject(result) ? result.signRawPayloadResult : undefined;\n if (!isJsonObject(signature)) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n const { r, s, v } = signature;\n if (\n typeof r !== \"string\" ||\n typeof s !== \"string\" ||\n typeof v !== \"string\" ||\n !SCALAR_HEX_PATTERN.test(r) ||\n !SCALAR_HEX_PATTERN.test(s) ||\n !RECOVERY_IDS.has(v)\n ) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef, activityStatus: null };\n }\n\n return { kind: \"signed\", r: r.toLowerCase(), s: s.toLowerCase(), v, activityRef };\n}\n","import { isSuaError, isSuaNetworkError } from \"#/errors/guards\";\nimport type { RelayResponseDto } from \"#/models\";\n\nimport { decodeRelayResponse } from \"./decodeRelayResponse\";\n\nimport type { RelayResult } from \"./types\";\n\n/**\n * Sends a relay once and settles it into a {@link RelayResult}, folding in the outcomes that arrive as thrown errors.\n * Typical use: `settleRelay(() => client.relay(request), body)`, where `body` is the string that was signed.\n *\n * - `send` resolves → `decodeRelayResponse(response, signedBody)`.\n * - `send` rejects with a `SuaNetworkError` (`isSuaNetworkError`, so a copy from a second bundle counts) → `{ kind:\n * \"unknown\", cause: \"network\", activityRef: \"\", activityStatus: null }`.\n * - `send` rejects with a `SuaError` (`isSuaError`) whose `code` is `\"ambiguous\"` → `unknown` with cause\n * `ambiguous`.\n * - A `SuaError` with a `2xx` status (an unusable body: empty, not JSON, not an object, or a `204`) → `unknown` with\n * cause `unreadable`: the Coordinator answered success, so the request may have been signed.\n * - A `SuaError` with any status outside `4xx`, notably a `5xx` with or without the Coordinator's envelope → `unknown`\n * with cause `server`. A proxy in front of the Coordinator (nginx, Cloudflare, the hub proxy) can answer\n * `502`, `504` or `524` after the stamp was forwarded, and the Coordinator's own `500` can follow a provider call.\n * - Any other rejection is rethrown unchanged: a `4xx` `SuaError` (`401 CREDENTIAL_EXPIRED`, `409\n * WALLET_NOT_ACTIVE`, `429`, a proxy's `413`, …) is a refusal before anything reached the provider, and an abort is\n * the caller's.\n *\n * Calls `send` exactly once and never retries.\n *\n * @param send Sends the relay, typically `client.relay`.\n * @param signedBody The exact activity body string that was signed (`buildSignRawPayloadBody`'s result). A completed\n * activity that does not echo it settles as `unknown` with cause `mismatch`.\n */\nexport async function settleRelay(send: () => Promise<RelayResponseDto>, signedBody: string): Promise<RelayResult> {\n let response: RelayResponseDto;\n try {\n response = await send();\n } catch (error) {\n if (isSuaNetworkError(error)) {\n return { kind: \"unknown\", cause: \"network\", activityRef: \"\", activityStatus: null };\n }\n if (!isSuaError(error)) {\n throw error;\n }\n if (error.code === \"ambiguous\") {\n return { kind: \"unknown\", cause: \"ambiguous\", activityRef: \"\", activityStatus: null };\n }\n if (error.status >= 200 && error.status < 300) {\n return { kind: \"unknown\", cause: \"unreadable\", activityRef: \"\", activityStatus: null };\n }\n if (error.status < 400 || error.status >= 500) {\n return { kind: \"unknown\", cause: \"server\", activityRef: \"\", activityStatus: null };\n }\n throw error;\n }\n return decodeRelayResponse(response, signedBody);\n}\n","import { SCALAR_HEX_PATTERN, SECP256K1_ORDER } from \"./constants\";\n\n/**\n * The length of r or s as hex digits.\n */\nconst SCALAR_HEX_LENGTH = 64;\n\n/**\n * Half the secp256k1 order: an `s` above it is high.\n */\nconst HALF_ORDER = SECP256K1_ORDER / 2n;\n\n/**\n * What EVM adds to a recovery id to form `v` (27 or 28).\n */\nconst EVM_RECOVERY_OFFSET = 27;\n\n/**\n * Turns Turnkey's raw-payload result into the 65-byte EVM signature an app receives:\n * `0x` ‖ r ‖ s ‖ (27 + v), as 132 lowercase characters.\n *\n * 1. Refuses anything but `r` and `s` of exactly 64 hex digits (either case) and `v` exactly `\"00\"` or `\"01\"`.\n * 2. Low-s: when `BigInt(\"0x\" + s) > SECP256K1_ORDER / 2n`, replaces `s` with `SECP256K1_ORDER - s` (left-padded to 64\n * hex digits) and flips the recovery id (`0` ↔ `1`). A signature with `s` exactly `n / 2` or below is kept.\n * 3. Returns `\"0x\" + r.toLowerCase() + s.toLowerCase() + (27 + v).toString(16)`, so v is `1b` or `1c`.\n *\n * The caller recovers the signer from the **raw** `r`, `s`, `v` first and only then calls this; the output recovers to\n * the same address because flipping v compensates for negating s.\n *\n * Vectors:\n * - The guide's relay result (r `3f1c8a9e…0b2d4f6a`, s `5e2a7c9e…9b1d3f5a`, v `\"00\"`) has a low s, so the output is\n * `0x3f1c8a9e…0b2d4f6a5e2a7c9e…9b1d3f5a1b`.\n * - s = `SECP256K1_ORDER - 1` with v `\"00\"` becomes s = `…0001` (63 zeros, then `1`) with v `1c`.\n * - s = `SECP256K1_ORDER / 2n` exactly is not high: kept, v unchanged.\n *\n * @throws {TypeError} when `r`, `s` or `v` breaks rule 1.\n */\nexport function toEvmSignature(r: string, s: string, v: string): string {\n if (typeof r !== \"string\" || !SCALAR_HEX_PATTERN.test(r)) {\n throw new TypeError(\"toEvmSignature: r must be 64 hex digits\");\n }\n if (typeof s !== \"string\" || !SCALAR_HEX_PATTERN.test(s)) {\n throw new TypeError(\"toEvmSignature: s must be 64 hex digits\");\n }\n if (v !== \"00\" && v !== \"01\") {\n throw new TypeError('toEvmSignature: v must be \"00\" or \"01\"');\n }\n\n let sHex = s.toLowerCase();\n let recoveryId = v === \"01\" ? 1 : 0;\n const sValue = BigInt(`0x${sHex}`);\n if (sValue > HALF_ORDER) {\n sHex = (SECP256K1_ORDER - sValue).toString(16).padStart(SCALAR_HEX_LENGTH, \"0\");\n recoveryId = 1 - recoveryId;\n }\n\n return `0x${r.toLowerCase()}${sHex}${(EVM_RECOVERY_OFFSET + recoveryId).toString(16)}`;\n}\n","/**\n * How many recent samples the server clock keeps. Its offset is their median.\n */\nexport const SERVER_CLOCK_WINDOW = 5;\n\n/**\n * How close, in ms, the first two samples must agree before their offset is applied. One sample alone never moves\n * the offset.\n */\nexport const SERVER_CLOCK_AGREEMENT_MS = 2_000;\n\n/**\n * The longest round trip, in ms, a sample may have. A slower answer says too little about when the server wrote its\n * time, so it is discarded.\n */\nexport const SERVER_CLOCK_MAX_ROUND_TRIP_MS = 5_000;\n\n/**\n * The smallest offset, in ms, the server clock applies. `Date` has whole-second resolution, so a smaller offset is\n * noise and counts as 0.\n */\nexport const SERVER_CLOCK_MIN_OFFSET_MS = 1_000;\n","import {\n SERVER_CLOCK_AGREEMENT_MS,\n SERVER_CLOCK_MAX_ROUND_TRIP_MS,\n SERVER_CLOCK_MIN_OFFSET_MS,\n SERVER_CLOCK_WINDOW,\n} from \"./constants\";\n\nimport type { ServerClock, ServerClockOptions, ServerTimeSample } from \"./types\";\n\n/**\n * Whether a sample can be used: three finite times and a round trip from 0 to\n * {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} inclusive. A negative round trip means the device's clock moved during the\n * request.\n */\nfunction isUsableSample(sample: ServerTimeSample): boolean {\n const { serverTimeMs, sentAtMs, receivedAtMs } = sample;\n if (!Number.isFinite(serverTimeMs) || !Number.isFinite(sentAtMs) || !Number.isFinite(receivedAtMs)) {\n return false;\n }\n const roundTripMs = receivedAtMs - sentAtMs;\n return roundTripMs >= 0 && roundTripMs <= SERVER_CLOCK_MAX_ROUND_TRIP_MS;\n}\n\n/**\n * The middle value of a non-empty list; the mean of the two middle values when its length is even.\n */\nfunction median(values: readonly number[]): number {\n const sorted = [...values].sort((left, right) => left - right);\n const middle = Math.floor(sorted.length / 2);\n if (sorted.length % 2 === 1) {\n return sorted[middle] ?? 0;\n }\n return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;\n}\n\n/**\n * The offset the window yields: `0` with fewer than two samples, and with exactly two that differ by more than\n * {@link SERVER_CLOCK_AGREEMENT_MS}; otherwise their median, rounded to a whole ms, and `0` when that is smaller in\n * size than {@link SERVER_CLOCK_MIN_OFFSET_MS}.\n */\nfunction resolveOffset(offsets: readonly number[]): number {\n if (offsets.length < 2) {\n return 0;\n }\n const [first = 0, second = 0] = offsets;\n if (offsets.length === 2 && Math.abs(first - second) > SERVER_CLOCK_AGREEMENT_MS) {\n return 0;\n }\n const offset = Math.round(median(offsets));\n return Math.abs(offset) < SERVER_CLOCK_MIN_OFFSET_MS ? 0 : offset;\n}\n\n/**\n * Creates a {@link ServerClock}: the device's clock corrected by its offset from the server's, learnt from the\n * samples passed to `record` (the Coordinator client's `onServerTime`).\n *\n * - **A sample's offset** is `serverTimeMs` minus the midpoint of `sentAtMs` and `receivedAtMs`.\n * - **Discarded samples.** One with a non-finite time, a negative round trip, or a round trip longer than\n * {@link SERVER_CLOCK_MAX_ROUND_TRIP_MS} (too uncertain) is ignored.\n * - **The offset** is the median of the last {@link SERVER_CLOCK_WINDOW} kept samples. One sample alone never moves\n * it; two move it only when they agree within {@link SERVER_CLOCK_AGREEMENT_MS}; from three on, the median ignores a\n * lone outlier.\n * - **The floor.** An offset smaller in size than {@link SERVER_CLOCK_MIN_OFFSET_MS} counts as 0, since `Date` has\n * whole-second resolution.\n * - **Memory only.** Nothing is stored: a new clock (a reload) starts again at 0.\n *\n * Durations (sleeps, timeouts, polling intervals, the sign confirm's dwell) stay on the device's clock; this clock is\n * only for comparing the device's time with a time the server wrote.\n */\nexport function createServerClock(options: ServerClockOptions = {}): ServerClock {\n const deviceClock = options.deviceClock ?? Date.now;\n const offsets: number[] = [];\n let offsetMs = 0;\n\n return {\n now: () => deviceClock() + offsetMs,\n offsetMs: () => offsetMs,\n record(sample) {\n if (!isUsableSample(sample)) {\n return;\n }\n offsets.push(sample.serverTimeMs - (sample.sentAtMs + sample.receivedAtMs) / 2);\n if (offsets.length > SERVER_CLOCK_WINDOW) {\n offsets.shift();\n }\n offsetMs = resolveOffset(offsets);\n },\n };\n}\n"],"mappings":";;;;;AAGA,MAAa,oBAAoB;;;;AAKjC,MAAa,iBAAiB;;;;AAK9B,MAAa,mBAAsC,CAAC,mBAAmB,cAAc;;;;AAKrF,MAAa,cAAc;;;;;;;;AAS3B,MAAa,aAAa;;;;;;AAO1B,MAAa,qBAAqB;;;;AAKlC,MAAa,6BAA6B;;;;AAK1C,MAAa,uBAAuB;;;;;AAMpC,MAAa,wBAAwB;;;;;AAMrC,MAAa,uBAAuB;;;;;AAMpC,MAAa,kCAAkC;;;;;AAM/C,MAAa,+BAA+B;;;;;;AAO5C,MAAa,kBAAkB;;;;;AAM/B,MAAa,2BAA2B;;;;;AAMxC,MAAa,0BAA0B;;;;;;;;;;;;AC5EvC,IAAa,iBAAb,MAAa,uBAAuB,MAAM;;;;CAItC;;;;CAKA;;;;CAKA,YAAY,QAAgC,OAAgB;EACxD,MAAM,oCAAoC;EAC1C,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,OAAO,eAAe,MAAM,eAAe,SAAS;CACxD;AACJ;;;;;;;AC5BA,SAAgB,aAAa,OAAkD;CAC3E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E;;;;;;;;;;;;;;;;;;;;;;;ACiEA,IAAa,WAAb,MAAa,iBAAiB,MAAM;;;;CAIhC;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;CAKA;;;;;CAMA,YAAY,MAAoB;EAC5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