@coinlist-co/react 0.12.2-rc.bc20f5b → 0.12.2-rc.eea3be6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/{chunk-C6GF7MDF.js → chunk-335G7ZM5.js} +858 -762
  2. package/dist/chunk-335G7ZM5.js.map +1 -0
  3. package/dist/{chunk-3WW5FLT7.js → chunk-IUAGXUJY.js} +10 -10
  4. package/dist/chunk-IUAGXUJY.js.map +1 -0
  5. package/dist/chunk-MJ6YXZWH.js +22 -0
  6. package/dist/chunk-MJ6YXZWH.js.map +1 -0
  7. package/dist/{chunk-IZJ4JSSC.js → chunk-WBB6P6ZI.js} +152 -203
  8. package/dist/chunk-WBB6P6ZI.js.map +1 -0
  9. package/dist/client/index.d.ts +3129 -5675
  10. package/dist/client/index.js +10574 -10828
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/server/index.d.ts +2 -32
  13. package/dist/server/index.js +6 -4
  14. package/dist/server/index.js.map +1 -1
  15. package/dist/{time-CVZpAkGY.d.cts → time-qZW4aYYp.d.ts} +1922 -3181
  16. package/dist/{token-registry-snapshot-BkwA8KmD.d.ts → token-registry-snapshot-CMrhSBun.d.ts} +22 -58
  17. package/dist/universal/index.d.ts +92 -1067
  18. package/dist/universal/index.js +24 -46
  19. package/package.json +18 -14
  20. package/dist/chunk-3WW5FLT7.js.map +0 -1
  21. package/dist/chunk-C6GF7MDF.js.map +0 -1
  22. package/dist/chunk-IZJ4JSSC.js.map +0 -1
  23. package/dist/client/index.cjs +0 -20460
  24. package/dist/client/index.cjs.map +0 -1
  25. package/dist/client/index.d.cts +0 -8195
  26. package/dist/server/index.cjs +0 -4525
  27. package/dist/server/index.cjs.map +0 -1
  28. package/dist/server/index.d.cts +0 -382
  29. package/dist/time-CVZpAkGY.d.ts +0 -3987
  30. package/dist/token-registry-snapshot-bR14QehS.d.cts +0 -245
  31. package/dist/universal/index.cjs +0 -4562
  32. package/dist/universal/index.cjs.map +0 -1
  33. package/dist/universal/index.d.cts +0 -1362
@@ -9,7 +9,13 @@ import {
9
9
  getUUIDv4,
10
10
  internalLogger,
11
11
  viemChain
12
- } from "./chunk-C6GF7MDF.js";
12
+ } from "./chunk-335G7ZM5.js";
13
+
14
+ // src/universal/core/shared/effects.ts
15
+ var systemTime = { time: { now: EpochMillis.now } };
16
+ var systemDelay = {
17
+ delay: (duration) => new Promise((resolve) => setTimeout(resolve, duration))
18
+ };
13
19
 
14
20
  // src/universal/api/nabu/config.ts
15
21
  var NABU_BASE_URL = "https://asset.coinlist.co";
@@ -137,12 +143,6 @@ function transportFor(api, override, chain, logger) {
137
143
  return typeof override === "string" ? http(override) : override;
138
144
  }
139
145
 
140
- // src/universal/core/shared/effects.ts
141
- var systemTime = { time: { now: EpochMillis.now } };
142
- var systemDelay = {
143
- delay: (duration) => new Promise((resolve) => setTimeout(resolve, duration))
144
- };
145
-
146
146
  // src/universal/core/shared/observability/pino-logger.ts
147
147
  function toPinoRecord(event) {
148
148
  try {
@@ -427,12 +427,12 @@ function notifySessionExpired(onSessionExpired, log) {
427
427
  export {
428
428
  AuthenticatedApiClient,
429
429
  notifySessionExpired,
430
- NABU_BASE_URL,
431
- publicClients,
432
430
  systemTime,
433
431
  systemDelay,
432
+ NABU_BASE_URL,
433
+ publicClients,
434
434
  PINO_LEVEL,
435
435
  SDK_LOGGER_NAME,
436
436
  loggerOverPino
437
437
  };
438
- //# sourceMappingURL=chunk-3WW5FLT7.js.map
438
+ //# sourceMappingURL=chunk-IUAGXUJY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/universal/core/shared/effects.ts","../src/universal/api/nabu/config.ts","../src/universal/api/rpc/public-clients.ts","../src/universal/api/rpc/frontline-transport.ts","../src/universal/core/shared/observability/pino-logger.ts","../src/universal/api/middleware/attach-session-middleware.ts","../src/universal/api/middleware/idempotency-key.ts","../src/universal/api/middleware/request-retry.ts","../src/universal/api/middleware/session-renewal.ts","../src/universal/api/authenticated-api-client.ts","../src/universal/core/auth/session-expired.ts"],"sourcesContent":["import { EpochMillis, type Millis } from '@/universal/types/time';\n\n/**\n * Reading the clock, as an effect: code that takes a `TimeEff` can be driven\n * by a fake clock in specs instead of real time.\n */\nexport type TimeEff = {\n readonly time: { readonly now: () => EpochMillis };\n};\n\n/** Waiting, as an effect, for the same reason as {@link TimeEff}. */\nexport type DelayEff = {\n readonly delay: (duration: Millis) => Promise<void>;\n};\n\n/** The real clock, wired in at the construction edges. */\nexport const systemTime: TimeEff = { time: { now: EpochMillis.now } };\n\n/** Real waiting on `setTimeout`, wired in at the construction edges. */\nexport const systemDelay: DelayEff = {\n delay: (duration) => new Promise((resolve) => setTimeout(resolve, duration)),\n};\n","/**\n * Base URL of CoinList's public token registry (Nabu), a static CDN serving\n * token display metadata keyed by chain + contract address. Override per\n * environment via `Config.tokensBaseUrl`.\n */\nexport const NABU_BASE_URL = 'https://asset.coinlist.co';\n","import {\n createPublicClient,\n http,\n type PublicClient,\n type Transport,\n} from 'viem';\nimport type { Sender } from '@/universal/api/http-client';\nimport { frontlineTransport } from '@/universal/api/rpc/frontline-transport';\nimport { viemChain } from '@/universal/core/shared/blockchain/chain';\nimport type { EthereumChain } from '@/universal/types/blockchain/core';\nimport type { RpcConfig } from '@/universal/types/config';\nimport type { Logger } from '@/universal/types/logger';\n\n/**\n * Resolves a chain to the viem `PublicClient` the SDK reads it through.\n *\n * One function rather than a client per read, because the client is where the\n * batching lives: viem's multicall scheduler is keyed on the client's `uid`,\n * so two reads only ever share an `eth_call` if they share a client. Hence the\n * memoisation - it is correctness for batching, not a performance tweak.\n */\nexport type PublicClients = (chain: EthereumChain) => PublicClient;\n\n/**\n * Builds the per-chain `PublicClient` factory, lazily and once per chain.\n *\n * `batch: { multicall: true }` routes concurrent `eth_call`s through\n * Multicall3, whose address comes from viem's own chain definitions (see\n * `viemChain`). A checkout screen mounts several hooks that each read\n * independently - status, authorization, allowance, balance - and they collapse\n * into a single request. Per-call failures survive it: viem calls `aggregate3`\n * with `allowFailure: true` and re-throws each revert on its own call.\n *\n * **A read reached through these clients must take its subject as an\n * argument.** Batching makes `msg.sender` the Multicall3 address rather than\n * the caller, so a view that reads `msg.sender` would answer differently under\n * batching than without. Nothing the SDK reads does - `allowance(owner,\n * spender)`, `balanceOf(account)`, `authorized(user)` all name theirs - and a\n * new read must keep it that way.\n */\nexport function publicClients(\n api: Sender,\n config: RpcConfig | undefined,\n logger: Logger | null = null\n): PublicClients {\n const cache = new Map<EthereumChain, PublicClient>();\n\n return (chain) => {\n const cached = cache.get(chain);\n if (cached) return cached;\n\n const client = createPublicClient({\n chain: viemChain(chain),\n transport: transportFor(api, config?.[chain], chain, logger),\n batch: { multicall: true },\n });\n cache.set(chain, client);\n return client;\n };\n}\n\n/**\n * A host's override, or CoinList's proxy. A string is a URL the SDK wraps in\n * `http()`; a {@link Transport} is used as it stands, so `fallback([...])` and\n * a partner's own transport both pass through untouched.\n *\n * Only the proxy transport is given the logger. A host's own transport reports\n * however they built it, and viem's `http()` has no logging seam, so a host on\n * their own node gets whatever they wired up and nothing from the SDK.\n */\nfunction transportFor(\n api: Sender,\n override: string | Transport | undefined,\n chain: EthereumChain,\n logger: Logger | null\n): Transport {\n if (override === undefined) return frontlineTransport(api, chain, logger);\n return typeof override === 'string' ? http(override) : override;\n}\n","import { custom, RpcRequestError, type Transport } from 'viem';\nimport { HttpError } from '@/universal/api/http';\nimport { Attributes } from '@/universal/api/http-attributes';\nimport type { Sender } from '@/universal/api/http-client';\nimport {\n type InternalLogger,\n internalLogger,\n} from '@/universal/core/shared/observability/internal-logger';\nimport type { EthereumChain } from '@/universal/types/blockchain/core';\nimport type { Logger } from '@/universal/types/logger';\n\n/**\n * A viem {@link Transport} that speaks JSON-RPC to CoinList's proxy,\n * `POST /v1/chains/{chain}/rpc`.\n *\n * Built over the SDK's own {@link Sender} rather than viem's `http()`, so an\n * on-chain read is an SDK request like any other: it carries the bearer token,\n * renews a stale session on a 401 and retries, is stamped with a request id,\n * and is reported by `HttpClient` by construction. Pointing `http()` at the\n * same URL would mean a second HTTP path through the SDK with none of that.\n * Retrying is the `Sender`'s job alone: viem's own `retryCount` is set to `0`\n * here, because it would otherwise rerun that whole pipeline on top of itself.\n *\n * **This is where the session requirement lives**, and it is the proxy that\n * enforces it: the endpoint is OAuth-gated, so a logged-out read comes back\n * `401` and reaches the caller as viem's `ContractFunctionExecutionError`\n * wrapping the SDK's own `HttpError`. Deliberately *not* translated to\n * `NotAuthenticatedError` - viem re-wraps whatever a `Transport` throws, so the\n * translation would not survive to the caller anyway and would only buy a\n * promise the SDK cannot keep. `classifyLogCause` walks the chain, so the\n * failure still logs as the HTTP failure it is.\n *\n * A partner who supplies their own node via {@link RpcConfig} never reaches\n * this transport and correctly needs no CoinList session.\n *\n * **What its `RPC` lines add over the `HTTP` ones for the same request.** The\n * JSON-RPC method, which the path `/v1/chains/{chain}/rpc` does not carry; and\n * a JSON-RPC error, which usually arrives with HTTP 200 and is therefore an\n * `info` success as far as `HttpClient` can tell.\n *\n * **They do not name the contract call**, and cannot: `publicClients` batches\n * through Multicall3, so one `eth_call` here may be several reads and its `to`\n * is Multicall3 rather than any contract. What is available is on the `debug`\n * line - the raw params, so the target address and the calldata. Which method\n * asked for the read, and whether it reverted, come from the namespace above.\n */\nexport function frontlineTransport(\n api: Sender,\n chain: EthereumChain,\n logger: Logger | null = null\n): Transport {\n const log = internalLogger(logger, 'RPC');\n let nextId = 0;\n\n return custom(\n {\n async request({ method, params }) {\n const id = ++nextId;\n return sendRpc({ api, log, chain, id, method, params });\n },\n },\n // The `Sender` below already retries: `requestRetryMiddleware` makes three\n // attempts at a 5xx and `renewSessionMiddleware` re-sends once after a 401.\n // viem's own default is `retryCount: 3`, and it applies on top: an\n // `HttpError` carries no numeric `code`, so `buildRequest` wraps it in\n // `UnknownRpcError` (`code === -1`) and `shouldRetry` says yes. That reruns\n // the whole pipeline four times - twelve requests for one `eth_call`, and\n // with multicall batching one `eth_call` is a screen's worth of reads. The\n // SDK's retry policy is the one that applies, so viem's is turned off.\n { retryCount: 0 }\n );\n}\n\nasync function sendRpc({\n api,\n log,\n chain,\n id,\n method,\n params,\n}: {\n api: Sender;\n log: InternalLogger;\n chain: EthereumChain;\n /** The JSON-RPC envelope's `id`, unique per request within one transport. */\n id: number;\n method: string;\n /** The JSON-RPC method's own params, passed through untouched. */\n params: unknown;\n}): Promise<unknown> {\n const url = rpcPath(chain);\n const startedAt = Date.now();\n\n // `params` carries calldata, so the envelope is a `'debug'` disclosure.\n log.debug(() => ({\n msg: 'rpc call sent',\n fields: { id, method, chain, params },\n }));\n\n const response = await sendEnvelope(api, url, {\n jsonrpc: '2.0',\n id,\n method,\n params,\n });\n const elapsed = Date.now() - startedAt;\n\n // A JSON-RPC error usually arrives with HTTP 200, so the `Sender` hands it\n // back as a success. viem's own `http()` transport raises `RpcRequestError`\n // here, and every viem action above - `readContract`'s revert decoding\n // included - is written against that.\n if (response.error) {\n const error = new RpcRequestError({\n body: { method, params },\n error: response.error,\n url,\n });\n // `warn`: the node declined, and only the namespace above knows whether\n // that broke anything. The code is the node's own, not a message anyone\n // wrote about this request.\n //\n // The cause is stated rather than classified. viem's `buildRequest` maps a\n // `RpcRequestError` onto one of its `RpcError` subclasses on the way out,\n // which is what `classifyLogCause` recognises - but that happens *above*\n // this throw, so classifying here would answer `'unknown'` for every\n // rejection. This call site knows: the node answered with an error object.\n log.warning(\n () => ({\n msg: 'rpc call rejected',\n cause: { type: 'rpc', reason: 'node-rejected' },\n fields: {\n method,\n chain,\n duration_ms: elapsed,\n 'rpc.error_code': response.error?.code ?? null,\n },\n }),\n error\n );\n throw error;\n }\n\n log.info(() => ({\n msg: 'rpc call',\n fields: { method, chain, duration_ms: elapsed },\n }));\n return response.result;\n}\n\nfunction rpcPath(chain: EthereumChain): string {\n return `/v1/chains/${encodeURIComponent(chain)}/rpc`;\n}\n\n/**\n * Posts the envelope, and reads a JSON-RPC error out of a non-2xx as well.\n *\n * The proxy forwards the node's status alongside its body, so a node that\n * answers a JSON-RPC error with, say, a `400` reaches the `Sender` as an\n * {@link HttpError}. Left as that, the node's error code and any revert data\n * would be lost behind an opaque HTTP failure. An `HttpError` whose body is not\n * a JSON-RPC error - frontline's own `422` for an unsupported chain or a\n * disallowed method, a `401`, a `5xx` - is the HTTP failure it looks like and\n * propagates untouched.\n */\nasync function sendEnvelope(\n api: Sender,\n url: string,\n body: { jsonrpc: '2.0'; id: number; method: string; params: unknown }\n): Promise<JsonRpcResponse> {\n try {\n return await api.send<JsonRpcResponse>({\n method: 'POST',\n url,\n body,\n attributes: Attributes.protected(),\n });\n } catch (error) {\n if (error instanceof HttpError && isJsonRpcError(error.response.body)) {\n return error.response.body;\n }\n throw error;\n }\n}\n\nfunction isJsonRpcError(\n body: unknown\n): body is Required<Pick<JsonRpcResponse, 'error'>> {\n if (typeof body !== 'object' || body === null || !('error' in body)) {\n return false;\n }\n const { error } = body;\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n typeof error.code === 'number'\n );\n}\n\n/**\n * Only what the transport branches on. The SDK does not model the envelope as\n * a DTO: it is JSON-RPC's shape, not frontline's, and every field but these\n * two is handed straight back to viem.\n */\ntype JsonRpcResponse = {\n result?: unknown;\n error?: { code: number; message: string; data?: unknown };\n};\n","import type {\n DebugEvent,\n Logger,\n LogLevel,\n SafeEvent,\n} from '@/universal/types/logger';\n\n/**\n * The SDK's logging seam expressed over pino, minus the environment.\n *\n * Imports no pino - {@link PinoSink} is a structural type - so `@/universal`\n * stays pino-free and the `./universal` entry point costs a consumer nothing.\n * Both shipped implementations\n * ({@link pinoClientLogger}, {@link pinoServerLogger}) differ only in the pino\n * instance they construct; everything worth testing lives here.\n *\n * ## Nothing here may throw\n *\n * A {@link Logger} implementation is called inline, on the codepath of the\n * work it reports, and the SDK does not catch it - so a log line that fails to\n * render would turn a successful request into an exception. That risk is real\n * rather than theoretical: `'debug'` fields carry whatever the SDK was\n * handling, and this codebase routinely handles `bigint` (every uint256 on\n * every DTO), which `JSON.stringify` throws on. Response bodies may be\n * circular, params may hold functions, and a host's object may have a getter\n * that throws.\n *\n * So {@link toPinoRecord} is total by construction: every value is rendered\n * into something a JSON serialiser cannot refuse, every property read is\n * guarded, and the whole translation has a fallback. Pino is never handed a\n * value it could fail on.\n */\n\n/**\n * Flattens an event into the object pino merges into its output line.\n *\n * Flat rather than nested, because nesting is what a host has to un-nest\n * before they can facet on it: `scope`, the {@link LogBindings} and every\n * field sit at the top level, and only `cause` stays an object because its\n * arms are a closed union a host switches on.\n *\n * `msg` is **not** included: it is pino's own second argument.\n *\n * Never throws. A value it cannot render becomes a `<tag>` string rather than\n * an exception, and a translation that fails entirely degrades to a record\n * naming the failure.\n */\nexport function toPinoRecord(event: SafeEvent | DebugEvent): PinoRecord {\n try {\n const record: Record<string, unknown> = {};\n\n for (const key of ownKeys(event.fields)) {\n record[key] = readProperty(event.fields, key, 0, new WeakSet());\n }\n\n const cause = 'cause' in event ? event.cause : undefined;\n if (cause !== undefined) {\n record.cause = sanitize(cause, 0, new WeakSet());\n }\n\n // Last, so the stamped keys win. `scope` and the bindings are what a host\n // routes and filters on, and they are stamped by `internalLogger` rather\n // than written at a call site - so a field that happened to be named\n // `scope` or `op` must not be able to take their place.\n return { ...record, scope: event.scope, ...event.bindings };\n } catch (_) {\n // The event itself is malformed - a Proxy for `fields`, a frozen exotic\n // object. Report that rather than losing the line, and never rethrow.\n return { 'log.render': '<unrenderable event>' };\n }\n}\n\n/** What pino merges into one output line. */\nexport type PinoRecord = Readonly<Record<string, unknown>>;\n\n/**\n * The SDK's five levels in pino's vocabulary.\n *\n * `'none'` is pino's `'silent'`; the other four are the same word in both, and\n * deliberately so. The SDK does not adopt pino's seven because `'trace'` would\n * sit below `'debug'`, and the guarantee \"`debug` is unredacted and every\n * other level is not\" only closes while `'debug'` is the bottom.\n */\nexport const PINO_LEVEL = {\n none: 'silent',\n error: 'error',\n warn: 'warn',\n info: 'info',\n debug: 'debug',\n} as const satisfies Record<LogLevel, string>;\n\n/**\n * How deep a `'debug'` field is followed before it is summarised.\n *\n * A bound rather than a guess at what is deep enough: a self-referential\n * structure is already caught by the cycle check, but a legitimately deep DTO\n * would otherwise cost real time inside a log line.\n */\nconst MAX_DEPTH = 8;\n\n/**\n * Renders any value into something a JSON serialiser cannot refuse.\n *\n * `bigint` is the one that matters in practice - every uint256 the SDK handles\n * is one - but the rest are all reachable from a `'debug'` field: `undefined`\n * and functions from an operation's params, `NaN` from arithmetic, symbols\n * from a host's object.\n */\nfunction sanitize(\n value: unknown,\n depth: number,\n seen: WeakSet<object>\n): unknown {\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return value;\n case 'number':\n // `NaN` and the infinities serialise to `null`, which reads as \"absent\"\n // rather than \"not a number\". Name them instead.\n return Number.isFinite(value) ? value : String(value);\n case 'bigint':\n return value.toString();\n case 'undefined':\n return '<undefined>';\n case 'function':\n return '<function>';\n case 'symbol':\n return value.toString();\n case 'object':\n return value === null ? null : sanitizeObject(value, depth, seen);\n default:\n return '<unrenderable>';\n }\n}\n\nfunction sanitizeObject(\n value: object,\n depth: number,\n seen: WeakSet<object>\n): unknown {\n if (seen.has(value)) return '<circular>';\n if (depth >= MAX_DEPTH) return '<max depth>';\n\n // `name`, `message` and `stack` are all non-enumerable, so an `Error` handed\n // to a structured sink as an object serialises to `{}`.\n if (value instanceof Error) return describeError(value);\n if (value instanceof Date) return describeDate(value);\n\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return value.map((_item, index) =>\n readProperty(value, String(index), depth, seen)\n );\n }\n\n const out: Record<string, unknown> = {};\n for (const key of ownKeys(value)) {\n out[key] = readProperty(value, key, depth, seen);\n }\n return out;\n } finally {\n // Removed on the way out, so a value referenced twice in a tree renders\n // twice. Only a genuine cycle is `<circular>`.\n seen.delete(value);\n }\n}\n\n/**\n * One property read, guarded. A getter may throw, and a log line is not\n * allowed to be the reason a request fails.\n */\nfunction readProperty(\n owner: object,\n key: string,\n depth: number,\n seen: WeakSet<object>\n): unknown {\n try {\n return sanitize((owner as Record<string, unknown>)[key], depth + 1, seen);\n } catch (_) {\n return '<unreadable>';\n }\n}\n\n/** Own enumerable keys, guarded: an exotic object may refuse to be enumerated. */\nfunction ownKeys(value: object): readonly string[] {\n try {\n return Object.keys(value);\n } catch (_) {\n return [];\n }\n}\n\nfunction describeError(error: Error): Record<string, unknown> {\n return {\n name: safeRead(() => error.name),\n message: safeRead(() => error.message),\n stack: safeRead(() => error.stack),\n };\n}\n\nfunction describeDate(date: Date): unknown {\n // An invalid `Date` throws from `toISOString`.\n return safeRead(() => date.toISOString());\n}\n\nfunction safeRead(read: () => unknown): unknown {\n try {\n const value = read();\n return typeof value === 'string' ? value : '<unreadable>';\n } catch (_) {\n return '<unreadable>';\n }\n}\n\n/**\n * The part of a pino logger this adapter uses.\n *\n * Structural rather than `import type { Logger } from 'pino'`, so that\n * `@/universal` takes no dependency on pino at all. A real pino instance - node\n * or browser build - satisfies it.\n */\nexport type PinoSink = {\n debug(record: PinoRecord, msg: string): void;\n info(record: PinoRecord, msg: string): void;\n warn(record: PinoRecord, msg: string): void;\n error(record: PinoRecord, msg: string): void;\n};\n\n/**\n * The `name` binding every SDK line carries, so a partner can separate the\n * SDK's output from their own in a shared aggregator without matching on\n * `scope`.\n *\n * Applied through `pino.child({ name })` rather than pino's `name` *option*,\n * which its browser build ignores. The browser lane's spec is what caught\n * that, and is what keeps it caught.\n */\nexport const SDK_LOGGER_NAME = '@coinlist-co/react';\n\n/**\n * Adapts a pino instance into the {@link Logger} the SDK consumes.\n *\n * **Total, and that is the point.** The SDK calls a `Logger` inline and does\n * not catch it, so an exception raised while reporting a successful request\n * would fail that request. Three things could raise one - the event lambda\n * itself, rendering the event, and the sink - and all three are caught here.\n * A render failure is reported through the sink rather than swallowed, since a\n * log line that silently vanishes is a bug nobody finds; if the sink is what\n * broke, there is nowhere left to report it and the error stops here.\n *\n * **The level is fixed here, and that is this adapter's choice rather than the\n * seam's.** {@link InternalLogger} calls {@link Logger.level} before *every*\n * log call and caches nothing, so a host-implemented `Logger` reading a mutable\n * field has a level they can change at runtime. This adapter captures `level`\n * instead, and the pino instance it wraps is built with a fixed one - so\n * `Logger.level` is a constant lookup and two loggers never interfere. A host\n * who wants to turn `'debug'` on without rebuilding implements {@link Logger}\n * directly over their own pino instance; the port is four methods and this\n * function is the worked example.\n */\nexport function loggerOverPino(sink: PinoSink, level: LogLevel): Logger {\n return {\n level: () => level,\n debug: (event) => emit(sink, 'debug', event),\n info: (event) => emit(sink, 'info', event),\n warn: (event) => emit(sink, 'warn', event),\n error: (event) => emit(sink, 'error', event),\n };\n}\n\nfunction emit(\n sink: PinoSink,\n method: keyof PinoSink,\n event: () => SafeEvent | DebugEvent\n): void {\n try {\n const value = event();\n sink[method](toPinoRecord(value), value.msg);\n } catch (error) {\n reportRenderFailure(sink, error);\n }\n}\n\nfunction reportRenderFailure(sink: PinoSink, error: unknown): void {\n try {\n sink.error(\n { 'error.type': error instanceof Error ? error.name : typeof error },\n 'log event failed to render'\n );\n } catch (_) {\n // The sink itself threw. There is nowhere left to report this, and the SDK\n // is on the other side of the call that got us here.\n }\n}\n","import type { HttpRequest } from '@/universal/api/http';\nimport { Attributes } from '@/universal/api/http-attributes';\nimport type { BeforeRequestMiddleware } from '@/universal/api/http-client';\nimport {\n type InternalAccessTokenSource,\n TokenTrigger,\n} from '@/universal/api/internal-access-token-source';\n\nexport function attachSessionMiddleware(\n fetchAccessToken: InternalAccessTokenSource\n): BeforeRequestMiddleware {\n return async (request: HttpRequest): Promise<HttpRequest> => {\n if (!Attributes.isProtected(request.attributes)) {\n return request;\n }\n\n const userToken = await fetchAccessToken(TokenTrigger.beforeRequest);\n if (userToken !== null) {\n // Recorded so a 401 can name the token it refused: see `TokenTrigger`.\n return withBearer(\n {\n ...request,\n attributes: Attributes.concat(\n request.attributes ?? Attributes.empty,\n Attributes.sentWith(userToken)\n ),\n },\n userToken.value\n );\n }\n\n const clientCreds = Attributes.getClientCredentials(request.attributes);\n if (clientCreds) {\n return withBearer(request, clientCreds.value);\n }\n return request;\n };\n}\n\nfunction withBearer(request: HttpRequest, token: string): HttpRequest {\n return {\n ...request,\n headers: {\n ...(request.headers ?? {}),\n Authorization: `Bearer ${token}`,\n },\n };\n}\n","import { HEADER_IDEMPOTENCY_KEY } from '@/universal/api/frontline/config';\nimport type { HttpRequest } from '@/universal/api/http';\nimport { Attributes } from '@/universal/api/http-attributes';\nimport type { BeforeRequestMiddleware } from '@/universal/api/http-client';\nimport { getUUIDv4 } from '@/universal/core/shared/utils/crypto';\n\nexport const idempotencyKeyMiddleware: BeforeRequestMiddleware = async (\n request: HttpRequest\n): Promise<HttpRequest> => {\n if (!Attributes.isIdempotent(request.attributes)) {\n return request;\n }\n\n const existingHeaders = request.headers ?? {};\n if (existingHeaders[HEADER_IDEMPOTENCY_KEY]) {\n return request;\n }\n\n return {\n ...request,\n headers: {\n ...existingHeaders,\n [HEADER_IDEMPOTENCY_KEY]: getUUIDv4(),\n },\n };\n};\n","import { Request } from '@/universal/api/http';\nimport { Attributes } from '@/universal/api/http-attributes';\nimport type { AfterRequestMiddleware } from '@/universal/api/http-client';\n\nconst MAX_ATTEMPTS = 3;\nconst INITIAL_DELAY_MS = 300;\nconst MAX_DELAY_MS = 2000;\n\nconst RETRYABLE_4XX = new Set([408, 409, 429]);\n\nexport function isRetryableStatus(status: number): boolean {\n return (status >= 500 && status < 600) || RETRYABLE_4XX.has(status);\n}\n\nfunction getRetryDelayMs(attempt: number): number {\n return Math.min(INITIAL_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);\n}\n\nexport type RequestRetryMiddlewareOptions = {\n /**\n * Optional delay function. Defaults to real setTimeout-based delay.\n * Use a no-op (e.g. () => Promise.resolve()) in tests to avoid slow tests.\n */\n delayFn?: (ms: number) => Promise<void>;\n};\n\n/**\n * Creates the request retry after-request middleware. Inject a no-op delayFn\n * in tests to avoid real delays (unit testing best practice).\n */\nexport function createRequestRetryMiddleware(\n options: RequestRetryMiddlewareOptions = {}\n): AfterRequestMiddleware {\n const delayFn = options.delayFn ?? defaultDelay;\n\n return async ({ request, response, retry }) => {\n if (\n !isRetryableStatus(response.status) ||\n !Attributes.isRetryable(request.attributes)\n ) {\n return response;\n }\n\n const currentAttempt = Attributes.getRetryAttempt(request.attributes);\n if (currentAttempt >= MAX_ATTEMPTS - 1) {\n return response;\n }\n\n const nextAttempt = currentAttempt + 1;\n await delayFn(getRetryDelayMs(nextAttempt));\n\n const nextRequest = Request.concatAttributes(\n request,\n Attributes.retryAttempt(nextAttempt)\n );\n return retry(nextRequest);\n };\n}\n\nfunction defaultDelay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retries the request up to 3 times with exponential backoff when the response\n * has a retryable status (5xx server errors). Uses request.attributes.retryAttempt\n * to decide delay and whether to retry, so the middleware does not loop when\n * retry() runs the full HTTP middleware chain again.\n */\nexport const requestRetryMiddleware: AfterRequestMiddleware =\n createRequestRetryMiddleware();\n","import { Request } from '@/universal/api/http';\nimport { Attributes } from '@/universal/api/http-attributes';\nimport type { AfterRequestMiddleware } from '@/universal/api/http-client';\nimport {\n type InternalAccessTokenSource,\n TokenTrigger,\n} from '@/universal/api/internal-access-token-source';\n\n/**\n * On a 401 to a protected request, asks for a better token than the one the\n * request was sent with and replays the request once with it.\n *\n * Deduplication is the token source's job, not this middleware's: a burst of\n * N requests that all 401 calls it N times, and the source answers all of\n * them from one renewal.\n */\nexport function renewSessionMiddleware(\n fetchAccessToken: InternalAccessTokenSource\n): AfterRequestMiddleware {\n return async ({ request, response, retry }) => {\n if (response.status !== 401) {\n return response;\n }\n if (!Attributes.isProtected(request.attributes)) {\n return response;\n }\n if (Attributes.wasRenewAttempted(request.attributes)) {\n return response;\n }\n\n const newToken = await fetchAccessToken(\n TokenTrigger.after401(Attributes.getSentWith(request.attributes))\n );\n if (newToken) {\n const nextRequest = Request.concatAttributes(\n request,\n Attributes.renewAttempted(true)\n );\n return retry(nextRequest);\n } else {\n return response;\n }\n };\n}\n","import type { HttpClientConfig, HttpRequest } from '@/universal/api/http';\nimport { HttpError } from '@/universal/api/http';\nimport type { BeforeRequestMiddleware } from '@/universal/api/http-client';\nimport { HttpClient } from '@/universal/api/http-client';\nimport type { InternalAccessTokenSource } from '@/universal/api/internal-access-token-source';\nimport { attachSessionMiddleware } from '@/universal/api/middleware/attach-session-middleware';\nimport { idempotencyKeyMiddleware } from '@/universal/api/middleware/idempotency-key';\nimport { requestRetryMiddleware } from '@/universal/api/middleware/request-retry';\nimport { renewSessionMiddleware } from '@/universal/api/middleware/session-renewal';\nimport type { Logger } from '@/universal/types/logger';\n\n/**\n * Isomorphic HTTP client with session attachment, session renewal on 401,\n * idempotency key injection, and request retry. Works in both browser and\n * Node/server environments. Pass `additionalBeforeRequest` to inject\n * environment-specific middleware (e.g. `userAgentMiddleware` on the client).\n *\n * Pass `logger` through to have every request reported; the client logs\n * nothing without one.\n */\nexport class AuthenticatedApiClient {\n private readonly httpClient: HttpClient;\n\n constructor(\n config: HttpClientConfig,\n fetchAccessToken: InternalAccessTokenSource,\n additionalBeforeRequest: BeforeRequestMiddleware[] = [],\n logger: Logger | null = null\n ) {\n this.httpClient = new HttpClient(\n config,\n {\n beforeRequest: [\n attachSessionMiddleware(fetchAccessToken),\n ...additionalBeforeRequest,\n idempotencyKeyMiddleware,\n ],\n afterRequest: [\n renewSessionMiddleware(fetchAccessToken),\n requestRetryMiddleware,\n ],\n },\n logger\n );\n }\n\n async send<TResponse>(request: HttpRequest): Promise<TResponse> {\n const response = await this.httpClient.send<TResponse>(request);\n if (response.status >= 200 && response.status < 300) {\n return response.body as TResponse;\n } else {\n throw new HttpError(response);\n }\n }\n}\n","import type { InternalLogger } from '@/universal/core/shared/observability/internal-logger';\n\n/**\n * Calls the host's `Config.onSessionExpired`, without awaiting it and without\n * letting it fail the request that found out.\n *\n * Total: the handler runs on the next microtask, so a sync throw from untyped\n * JavaScript and an async rejection land on the same `catch`, and both are\n * logged and dropped.\n */\nexport function notifySessionExpired(\n onSessionExpired: (() => Promise<void>) | undefined,\n log: InternalLogger\n): void {\n if (onSessionExpired === undefined) {\n return;\n }\n Promise.resolve()\n .then(onSessionExpired)\n .catch((error: unknown) =>\n log.failure(() => ({ msg: 'onSessionExpired threw' }), error)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBO,IAAM,aAAsB,EAAE,MAAM,EAAE,KAAK,YAAY,IAAI,EAAE;AAG7D,IAAM,cAAwB;AAAA,EACnC,OAAO,CAAC,aAAa,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,QAAQ,CAAC;AAC7E;;;AChBO,IAAM,gBAAgB;;;ACL7B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;;;ACLP,SAAS,QAAQ,uBAAuC;AA8CjD,SAAS,mBACd,KACA,OACA,SAAwB,MACb;AACX,QAAM,MAAM,eAAe,QAAQ,KAAK;AACxC,MAAI,SAAS;AAEb,SAAO;AAAA,IACL;AAAA,MACE,MAAM,QAAQ,EAAE,QAAQ,OAAO,GAAG;AAChC,cAAM,KAAK,EAAE;AACb,eAAO,QAAQ,EAAE,KAAK,KAAK,OAAO,IAAI,QAAQ,OAAO,CAAC;AAAA,MACxD;AAAA,IACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASA,EAAE,YAAY,EAAE;AAAA,EAClB;AACF;AAEA,eAAe,QAAQ;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GASqB;AACnB,QAAM,MAAM,QAAQ,KAAK;AACzB,QAAM,YAAY,KAAK,IAAI;AAG3B,MAAI,MAAM,OAAO;AAAA,IACf,KAAK;AAAA,IACL,QAAQ,EAAE,IAAI,QAAQ,OAAO,OAAO;AAAA,EACtC,EAAE;AAEF,QAAM,WAAW,MAAM,aAAa,KAAK,KAAK;AAAA,IAC5C,SAAS;AAAA,IACT;AAAA,IACA;AAAA,I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UACb,wBAAwB,gBAAgB;AAAA,UACxC,GAAG;AAAA,UACH;AAAA,QACF;AAAA,QACA,cAAc;AAAA,UACZ,uBAAuB,gBAAgB;AAAA,UACvC;AAAA,QACF;AAAA,MACF;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,KAAgB,SAA0C;AAC9D,UAAM,WAAW,MAAM,KAAK,WAAW,KAAgB,OAAO;AAC9D,QAAI,SAAS,UAAU,OAAO,SAAS,SAAS,KAAK;AACnD,aAAO,SAAS;AAAA,IAClB,OAAO;AACL,YAAM,IAAI,UAAU,QAAQ;AAAA,IAC9B;AAAA,EACF;AACF;;;AC5CO,SAAS,qBACd,kBACA,KACM;AACN,MAAI,qBAAqB,QAAW;AAClC;AAAA,EACF;AACA,UAAQ,QAAQ,EACb,KAAK,gBAAgB,EACrB;AAAA,IAAM,CAAC,UACN,IAAI,QAAQ,OAAO,EAAE,KAAK,yBAAyB,IAAI,KAAK;AAAA,EAC9D;AACJ;","names":[]}
@@ -0,0 +1,22 @@
1
+ // src/universal/types/oauth-session.ts
2
+ var ClientCredentialsOAuth = (value) => value;
3
+ var OAuthRefreshToken = (value) => value;
4
+ var OAuthSession = {
5
+ fromDto: (dto) => {
6
+ const expiresAt = new Date(Date.now() + dto.expires_in * 1e3);
7
+ return {
8
+ accessToken: {
9
+ value: dto.access_token,
10
+ expiresAt
11
+ },
12
+ ...dto.refresh_token != null && dto.refresh_token !== "" ? { refreshToken: OAuthRefreshToken(dto.refresh_token) } : void 0
13
+ };
14
+ }
15
+ };
16
+
17
+ export {
18
+ ClientCredentialsOAuth,
19
+ OAuthRefreshToken,
20
+ OAuthSession
21
+ };
22
+ //# sourceMappingURL=chunk-MJ6YXZWH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/universal/types/oauth-session.ts"],"sourcesContent":["import type { OAuthSessionDto } from '@/universal/types/dto/oauth-session';\nimport type { Newtype } from '@/universal/types/newtype';\n\nexport type ClientCredentialsOAuth = Newtype<\n OAuthAccessToken,\n 'ClientCredentialsOAuth'\n>;\nexport const ClientCredentialsOAuth = (value: OAuthAccessToken) =>\n value as ClientCredentialsOAuth;\n\nexport type OAuthAccessToken = {\n value: string;\n expiresAt: Date;\n};\n\nexport type OAuthRefreshToken = Newtype<string, 'OAuthRefreshToken'>;\nexport const OAuthRefreshToken = (value: string) => value as OAuthRefreshToken;\n\nexport type OAuthSession = {\n accessToken: OAuthAccessToken;\n refreshToken?: OAuthRefreshToken;\n};\n\n/** @internal */\nexport const OAuthSession = {\n fromDto: (dto: OAuthSessionDto): OAuthSession => {\n const expiresAt = new Date(Date.now() + dto.expires_in * 1000);\n return {\n accessToken: {\n value: dto.access_token,\n expiresAt,\n },\n ...(dto.refresh_token != null && dto.refresh_token !== ''\n ? { refreshToken: OAuthRefreshToken(dto.refresh_token) }\n : undefined),\n };\n },\n};\n"],"mappings":";AAOO,IAAM,yBAAyB,CAAC,UACrC;AAQK,IAAM,oBAAoB,CAAC,UAAkB;AAQ7C,IAAM,eAAe;AAAA,EAC1B,SAAS,CAAC,QAAuC;AAC/C,UAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,IAAI,aAAa,GAAI;AAC7D,WAAO;AAAA,MACL,aAAa;AAAA,QACX,OAAO,IAAI;AAAA,QACX;AAAA,MACF;AAAA,MACA,GAAI,IAAI,iBAAiB,QAAQ,IAAI,kBAAkB,KACnD,EAAE,cAAc,kBAAkB,IAAI,aAAa,EAAE,IACrD;AAAA,IACN;AAAA,EACF;AACF;","names":[]}
@@ -9,19 +9,20 @@ import {
9
9
  MAX_UINT_256,
10
10
  MathError,
11
11
  NA_AMOUNT_ASSET_UI,
12
- SUPERSTATE_SWAP_ABI,
13
12
  StablecoinSymbol,
14
13
  apiErrorCode,
15
14
  arrayBufferToBase64Url,
16
15
  assertUint256,
16
+ contractOn,
17
17
  fetchOfferDetails,
18
18
  fetchOffers,
19
19
  fetchOffersPage,
20
20
  formattedUsdPrice,
21
21
  generateSecureRandomBase64Url,
22
22
  internalLogger,
23
+ pricePerShare,
23
24
  sha256
24
- } from "./chunk-C6GF7MDF.js";
25
+ } from "./chunk-335G7ZM5.js";
25
26
 
26
27
  // src/universal/types/oauth.ts
27
28
  var AuthorizationCode = (value) => value;
@@ -49,43 +50,10 @@ async function generatePKCEParams(config) {
49
50
  };
50
51
  }
51
52
 
52
- // src/universal/core/checkout/centrifuge/constants.ts
53
- var CENTRIFUGE_POLL_INTERVAL_MS = 15e3;
54
-
55
- // src/universal/core/checkout/centrifuge/vaults.ts
56
- function resolveCentrifugeVaults(offer, lookup) {
57
- return offer.vaultContracts.map((contract) => {
58
- const { chain } = contract;
59
- if (!isEthereumChain(chain)) {
60
- return { type: "unresolved", chain, missing: "evm-chain" };
61
- }
62
- const onChain = (role) => offer.tokens.filter(
63
- (token) => token.role === role && token.chain === chain
64
- );
65
- const share = firstKnown(onChain("vault"), lookup);
66
- if (share === null) {
67
- return { type: "unresolved", chain, missing: "share-token" };
68
- }
69
- const funding = firstKnown(onChain("funding"), lookup);
70
- if (funding === null) {
71
- return { type: "unresolved", chain, missing: "funding-token" };
72
- }
73
- return {
74
- type: "resolved",
75
- vault: { chain, proxy: contract.address, share, funding }
76
- };
77
- });
78
- }
79
- function firstKnown(tokens, lookup) {
80
- for (const token of tokens) {
81
- const metadata = lookup(token);
82
- if (metadata !== null) return metadata;
83
- }
84
- return null;
85
- }
86
- function isEthereumChain(chain) {
87
- return chain in ETHEREUM_CHAINS;
88
- }
53
+ // src/universal/types/blockchain/wallet-error.ts
54
+ var RedactedWalletError = {
55
+ fromWalletError: (error) => error.type === "unknown" ? { type: "unknown" } : error
56
+ };
89
57
 
90
58
  // src/universal/core/shared/blockchain/token-registry.ts
91
59
  var USDC_SYMBOL = StablecoinSymbol("USDC");
@@ -147,66 +115,41 @@ var TOKEN_REGISTRY = {
147
115
  * Base Sepolia today. The honest answer, never a fake address a balance
148
116
  * read would call.
149
117
  */
150
- usdtAddress: (chain) => USDT_ADDRESSES[chain]
151
- };
152
-
153
- // src/universal/core/checkout/ondo/constants.ts
154
- var ONDO_POLL_INTERVAL_MS = 15e3;
155
- var ONDO_QUOTE_MAX_TTL_MS = 15e3;
156
- var DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE = DecimalString("1000");
157
- var ONDO_SETTLEMENT_ASSET = USDC_SYMBOL;
158
- var DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE = 1;
159
- var ONDO_SUPPORTED_INPUT_ASSETS = [
160
- USDC_SYMBOL
161
- ];
162
-
163
- // src/universal/core/checkout/ondo/math.ts
164
- function computeOndoBuyPrice(transaction) {
165
- const { notionalValue, receiveOutputAmount } = transaction;
166
- return pricePerShare({
167
- usd: notionalValue,
168
- shares: receiveOutputAmount
169
- });
170
- }
171
- function computeOndoSellPrice(transaction) {
172
- const { expected, spendInputAmount } = transaction;
173
- return pricePerShare({
174
- usd: grossProceeds(expected),
175
- shares: spendInputAmount
176
- });
177
- }
178
- function ondoQuoteOfferDeadline(expiresAt, nowMs = Date.now()) {
179
- return new Date(Math.min(expiresAt.getTime(), nowMs + ONDO_QUOTE_MAX_TTL_MS));
180
- }
181
- function grossProceeds(expected) {
182
- const raw = expected.quantity.raw + expected.fee.raw;
183
- if (raw > MAX_UINT_256) {
184
- throw new MathError(`Ondo sell proceeds: out of uint256 bounds (${raw})`);
185
- }
186
- return BlockchainAmount.add(expected.quantity, expected.fee);
187
- }
188
- function pricePerShare({
189
- usd,
190
- shares
191
- }) {
192
- const price = BlockchainAmount.div(usd, shares);
193
- return BlockchainAmount({
194
- raw: assertPriceFits(price.raw),
195
- decimals: price.decimals
196
- });
197
- }
198
- function assertPriceFits(raw) {
199
- try {
200
- return assertUint256(raw);
201
- } catch {
202
- throw new MathError(`Ondo price: out of uint256 bounds (${raw})`);
118
+ usdtAddress: (chain) => USDT_ADDRESSES[chain],
119
+ /**
120
+ * `symbol`'s contract on `chain`, or `null` where it has none - one lookup
121
+ * over both tables, for a caller that holds the symbol as data.
122
+ */
123
+ address: (symbol, chain) => {
124
+ switch (symbol) {
125
+ case "USDC":
126
+ return USDC_ADDRESSES[chain];
127
+ case "USDT":
128
+ return USDT_ADDRESSES[chain];
129
+ default:
130
+ throw new InvariantError(`Unknown stablecoin symbol: ${symbol}`);
131
+ }
132
+ },
133
+ /**
134
+ * The stablecoin a backend asset code names, or `null` for a code the
135
+ * registry does not support. Matched exactly: frontline spells its codes
136
+ * the way the registry does, and a near miss is a different asset.
137
+ */
138
+ stablecoin: (code) => {
139
+ switch (code) {
140
+ case "USDC":
141
+ return USDC_SYMBOL;
142
+ case "USDT":
143
+ return USDT_SYMBOL;
144
+ default:
145
+ return null;
146
+ }
203
147
  }
204
- }
148
+ };
205
149
 
206
- // src/universal/core/checkout/ondo/not-tradable.ts
207
- var ONDO_NOT_TRADABLE_CODE = "not_tradable";
208
- function isOndoNotTradableError(error) {
209
- return apiErrorCode(error) === ONDO_NOT_TRADABLE_CODE;
150
+ // src/universal/core/offers/swap-contracts.ts
151
+ function swapSpender(swapContracts, chain) {
152
+ return contractOn(swapContracts, chain);
210
153
  }
211
154
 
212
155
  // src/universal/core/shared/blockchain/bps.ts
@@ -215,17 +158,13 @@ function applyBps(amount, bps) {
215
158
  return assertUint256(amount * bps / BPS_DENOM);
216
159
  }
217
160
 
218
- // src/universal/core/checkout/superstate/blockchain/math.ts
161
+ // src/universal/core/providers/checkout/superstate/blockchain/math.ts
219
162
  function computePrice({
220
163
  inputTokenAmount,
221
164
  outputTokenAmount
222
165
  }) {
223
166
  if (outputTokenAmount.raw === 0n) return null;
224
- const scale = 10n ** BigInt(outputTokenAmount.decimals);
225
- const raw = assertUint256(
226
- inputTokenAmount.raw * scale / outputTokenAmount.raw
227
- );
228
- return BlockchainAmount({ raw, decimals: inputTokenAmount.decimals });
167
+ return pricePerShare({ usd: inputTokenAmount, shares: outputTokenAmount });
229
168
  }
230
169
  function computeSlip(amount, slippage) {
231
170
  const retained = Bps(assertUint256(BPS_DENOM - slippage));
@@ -233,27 +172,7 @@ function computeSlip(amount, slippage) {
233
172
  return BlockchainAmount({ raw: slipRaw, decimals: amount.decimals });
234
173
  }
235
174
 
236
- // src/universal/core/checkout/superstate/blockchain/quote.ts
237
- var SwapQuote = {
238
- /**
239
- * Assembles a {@link SwapQuote} from a raw contract {@link SwapPreview}. The
240
- * input and fee are denominated in the input token; the output in the output
241
- * token.
242
- */
243
- fromPreview: (preview, inputDecimals, outputDecimals) => ({
244
- inputTokenAmount: BlockchainAmount({
245
- raw: preview.inputAmount,
246
- decimals: inputDecimals
247
- }),
248
- fee: BlockchainAmount({ raw: preview.fee, decimals: inputDecimals }),
249
- outputTokenAmount: BlockchainAmount({
250
- raw: preview.outputAmount,
251
- decimals: outputDecimals
252
- })
253
- })
254
- };
255
-
256
- // src/universal/core/checkout/superstate/blockchain/status.ts
175
+ // src/universal/core/providers/checkout/superstate/blockchain/status.ts
257
176
  var SWAP_LEVEL = 2;
258
177
  function isSwapAvailable(status) {
259
178
  switch (status.state) {
@@ -270,47 +189,6 @@ function isSwapAvailable(status) {
270
189
  }
271
190
  }
272
191
 
273
- // src/universal/core/checkout/superstate/blockchain/swapped-event.ts
274
- import { parseEventLogs } from "viem";
275
- function decodeSwappedOutputAmount(receipt, outputDecimals) {
276
- try {
277
- const [swapped] = parseEventLogs({
278
- abi: SUPERSTATE_SWAP_ABI,
279
- eventName: "Swapped",
280
- logs: receipt.logs
281
- });
282
- if (!swapped) return null;
283
- const raw = swapped.args.outputAmount;
284
- if (raw < 0n || raw > MAX_UINT_256) return null;
285
- return BlockchainAmount({ raw, decimals: outputDecimals });
286
- } catch {
287
- return null;
288
- }
289
- }
290
-
291
- // src/universal/core/checkout/superstate/constants.ts
292
- var SUPERSTATE_ISSUER_NAME = "Superstate";
293
- var SUPERSTATE_SUPPORTED_INPUT_ASSETS = [USDC_SYMBOL];
294
- var SWAP_POLL_INTERVAL_MS = 15e3;
295
- var DEFAULT_AMOUNT_TO_COMPUTE_PRICE = 1000000n;
296
- var SLIPPAGE_OPTIONS_BPS = [25n, 50n, 100n, 200n, 500n].map(
297
- (n) => Bps(n)
298
- );
299
- var DEFAULT_SLIPPAGE_BPS = Bps(50n);
300
- var SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA = EvmContractAddress("0x27E8CE9Ca1A1E98Bc4009F08Dc596bFcf88aCED1");
301
- var SUPERSTATE_SWAP_CONTRACT_ADDRESSES = {
302
- ethereum_sepolia: SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA
303
- };
304
- function superstateSwapContractAddress(chain) {
305
- return SUPERSTATE_SWAP_CONTRACT_ADDRESSES[chain] ?? null;
306
- }
307
-
308
- // src/universal/core/checkout/superstate/formatters.ts
309
- function formattedPricePerShare(quote, locale) {
310
- if (!quote) return NA_AMOUNT_ASSET_UI;
311
- return formattedUsdPrice(computePrice(quote), locale);
312
- }
313
-
314
192
  // src/universal/core/offers/offers-namespace.ts
315
193
  var OffersNamespaceImpl = class {
316
194
  constructor(ctx) {
@@ -337,11 +215,6 @@ var OffersNamespaceImpl = class {
337
215
  }
338
216
  };
339
217
 
340
- // src/universal/core/offers/swap-contracts.ts
341
- function swapSpender(swapContracts, chain) {
342
- return swapContracts.find((contract) => contract.chain === chain)?.address ?? null;
343
- }
344
-
345
218
  // src/universal/core/tokens/token-registry-snapshot.ts
346
219
  var TokenRegistrySnapshot = {
347
220
  /** Indexes a `tokens.list()` result. `[]` is a valid, empty snapshot. */
@@ -390,10 +263,70 @@ function registryKey(token) {
390
263
  return `${token.chain}:${token.address.toLowerCase()}`;
391
264
  }
392
265
 
393
- // src/universal/types/blockchain/wallet-error.ts
394
- var RedactedWalletError = {
395
- fromWalletError: (error) => error.type === "unknown" ? { type: "unknown" } : error
266
+ // src/universal/core/providers/checkout/ondo/not-tradable.ts
267
+ var ONDO_NOT_TRADABLE_CODE = "not_tradable";
268
+ function isOndoNotTradableError(error) {
269
+ return apiErrorCode(error) === ONDO_NOT_TRADABLE_CODE;
270
+ }
271
+
272
+ // src/universal/core/providers/checkout/ondo/constants.ts
273
+ var ONDO_POLL_INTERVAL_MS = 15e3;
274
+ var ONDO_QUOTE_MAX_TTL_MS = 15e3;
275
+ var DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE = DecimalString("1000");
276
+ var ONDO_SETTLEMENT_ASSET = USDC_SYMBOL;
277
+ var DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE = 1;
278
+ var ONDO_SUPPORTED_INPUT_ASSETS = [
279
+ USDC_SYMBOL
280
+ ];
281
+
282
+ // src/universal/core/providers/checkout/ondo/math.ts
283
+ function computeOndoBuyPrice(transaction) {
284
+ const { notionalValue, receiveOutputAmount } = transaction;
285
+ return pricePerShare({
286
+ usd: notionalValue,
287
+ shares: receiveOutputAmount
288
+ });
289
+ }
290
+ function computeOndoSellPrice(transaction) {
291
+ const { expected, spendInputAmount } = transaction;
292
+ return pricePerShare({
293
+ usd: grossProceeds(expected),
294
+ shares: spendInputAmount
295
+ });
296
+ }
297
+ function ondoQuoteOfferDeadline(expiresAt, nowMs = Date.now()) {
298
+ return new Date(Math.min(expiresAt.getTime(), nowMs + ONDO_QUOTE_MAX_TTL_MS));
299
+ }
300
+ function grossProceeds(expected) {
301
+ const raw = expected.quantity.raw + expected.fee.raw;
302
+ if (raw > MAX_UINT_256) {
303
+ throw new MathError(`Ondo sell proceeds: out of uint256 bounds (${raw})`);
304
+ }
305
+ return BlockchainAmount.add(expected.quantity, expected.fee);
306
+ }
307
+
308
+ // src/universal/core/providers/checkout/superstate/constants.ts
309
+ var SUPERSTATE_ISSUER_NAME = "Superstate";
310
+ var SUPERSTATE_SUPPORTED_INPUT_ASSETS = [USDC_SYMBOL];
311
+ var SWAP_POLL_INTERVAL_MS = 15e3;
312
+ var DEFAULT_AMOUNT_TO_COMPUTE_PRICE = 1000000n;
313
+ var SLIPPAGE_OPTIONS_BPS = [25n, 50n, 100n, 200n, 500n].map(
314
+ (n) => Bps(n)
315
+ );
316
+ var DEFAULT_SLIPPAGE_BPS = Bps(50n);
317
+ var SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA = EvmContractAddress("0x27E8CE9Ca1A1E98Bc4009F08Dc596bFcf88aCED1");
318
+ var SUPERSTATE_SWAP_CONTRACT_ADDRESSES = {
319
+ ethereum_sepolia: SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA
396
320
  };
321
+ function superstateSwapContractAddress(chain) {
322
+ return SUPERSTATE_SWAP_CONTRACT_ADDRESSES[chain] ?? null;
323
+ }
324
+
325
+ // src/universal/core/providers/checkout/superstate/formatters.ts
326
+ function formattedPricePerShare(quote, locale) {
327
+ if (!quote) return NA_AMOUNT_ASSET_UI;
328
+ return formattedUsdPrice(computePrice(quote), locale);
329
+ }
397
330
 
398
331
  // src/universal/types/blockchain/wallet-selection.ts
399
332
  var WalletSelection = {
@@ -416,15 +349,40 @@ var WalletSelection = {
416
349
  }
417
350
  };
418
351
 
419
- // src/universal/types/user.ts
420
- var UserId = (value) => value;
421
- var UserEmail = (value) => value;
422
- var User = {
423
- fromDto: (dto) => ({
424
- id: UserId(dto.id),
425
- email: UserEmail(dto.email)
426
- })
427
- };
352
+ // src/universal/core/providers/checkout/centrifuge/vaults.ts
353
+ function resolveCentrifugeVaults(offer, lookup) {
354
+ return offer.vaultContracts.map((contract) => {
355
+ const { chain } = contract;
356
+ if (!isEthereumChain(chain)) {
357
+ return { type: "unresolved", chain, missing: "evm-chain" };
358
+ }
359
+ const onChain = (role) => offer.tokens.filter(
360
+ (token) => token.role === role && token.chain === chain
361
+ );
362
+ const share = firstKnown(onChain("vault"), lookup);
363
+ if (share === null) {
364
+ return { type: "unresolved", chain, missing: "share-token" };
365
+ }
366
+ const funding = firstKnown(onChain("funding"), lookup);
367
+ if (funding === null) {
368
+ return { type: "unresolved", chain, missing: "funding-token" };
369
+ }
370
+ return {
371
+ type: "resolved",
372
+ vault: { chain, proxy: contract.address, share, funding }
373
+ };
374
+ });
375
+ }
376
+ function firstKnown(tokens, lookup) {
377
+ for (const token of tokens) {
378
+ const metadata = lookup(token);
379
+ if (metadata !== null) return metadata;
380
+ }
381
+ return null;
382
+ }
383
+ function isEthereumChain(chain) {
384
+ return chain in ETHEREUM_CHAINS;
385
+ }
428
386
 
429
387
  export {
430
388
  AuthorizationCode,
@@ -436,32 +394,29 @@ export {
436
394
  ClientSecret,
437
395
  generatePKCEParams,
438
396
  RedactedWalletError,
439
- CENTRIFUGE_POLL_INTERVAL_MS,
440
- resolveCentrifugeVaults,
441
397
  USDC_SYMBOL,
442
398
  USDC,
443
399
  USDT_SYMBOL,
444
400
  USDT,
445
401
  TOKEN_REGISTRY,
402
+ swapSpender,
403
+ computePrice,
404
+ computeSlip,
405
+ SWAP_LEVEL,
406
+ isSwapAvailable,
407
+ OffersNamespaceImpl,
408
+ TokenRegistrySnapshot,
409
+ offerDisplayTokens,
446
410
  ONDO_POLL_INTERVAL_MS,
447
- ONDO_QUOTE_MAX_TTL_MS,
448
411
  DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE,
449
412
  ONDO_SETTLEMENT_ASSET,
450
413
  DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE,
451
414
  ONDO_SUPPORTED_INPUT_ASSETS,
415
+ ONDO_NOT_TRADABLE_CODE,
416
+ isOndoNotTradableError,
452
417
  computeOndoBuyPrice,
453
418
  computeOndoSellPrice,
454
419
  ondoQuoteOfferDeadline,
455
- ONDO_NOT_TRADABLE_CODE,
456
- isOndoNotTradableError,
457
- BPS_DENOM,
458
- applyBps,
459
- computePrice,
460
- computeSlip,
461
- SwapQuote,
462
- SWAP_LEVEL,
463
- isSwapAvailable,
464
- decodeSwappedOutputAmount,
465
420
  SUPERSTATE_ISSUER_NAME,
466
421
  SUPERSTATE_SUPPORTED_INPUT_ASSETS,
467
422
  SWAP_POLL_INTERVAL_MS,
@@ -471,13 +426,7 @@ export {
471
426
  SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA,
472
427
  superstateSwapContractAddress,
473
428
  formattedPricePerShare,
474
- OffersNamespaceImpl,
475
- swapSpender,
476
- TokenRegistrySnapshot,
477
- offerDisplayTokens,
478
429
  WalletSelection,
479
- UserId,
480
- UserEmail,
481
- User
430
+ resolveCentrifugeVaults
482
431
  };
483
- //# sourceMappingURL=chunk-IZJ4JSSC.js.map
432
+ //# sourceMappingURL=chunk-WBB6P6ZI.js.map