@coinlist-co/react 0.12.1 → 0.12.2-rc.0ff2d03

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 (34) hide show
  1. package/README.md +10 -0
  2. package/dist/chunk-MJ6YXZWH.js +22 -0
  3. package/dist/chunk-MJ6YXZWH.js.map +1 -0
  4. package/dist/{chunk-VH34YC3Q.js → chunk-PWGUKS4Q.js} +199 -186
  5. package/dist/chunk-PWGUKS4Q.js.map +1 -0
  6. package/dist/{chunk-DCW7NQXH.js → chunk-QTBEDN7C.js} +52 -19
  7. package/dist/chunk-QTBEDN7C.js.map +1 -0
  8. package/dist/{chunk-MOE5S6CE.js → chunk-SVPFFLIT.js} +1314 -796
  9. package/dist/chunk-SVPFFLIT.js.map +1 -0
  10. package/dist/client/index.d.ts +3332 -4554
  11. package/dist/client/index.js +7374 -4387
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/server/index.d.ts +69 -71
  14. package/dist/server/index.js +327 -67
  15. package/dist/server/index.js.map +1 -1
  16. package/dist/{tokens-namespace-CIWBtgt2.d.cts → time-BDzqB806.d.ts} +1901 -2491
  17. package/dist/{token-registry-snapshot-CqI6dXM_.d.cts → token-registry-snapshot-cvLsnMo_.d.ts} +74 -42
  18. package/dist/universal/index.d.ts +100 -1001
  19. package/dist/universal/index.js +52 -36
  20. package/package.json +18 -14
  21. package/dist/chunk-DCW7NQXH.js.map +0 -1
  22. package/dist/chunk-MOE5S6CE.js.map +0 -1
  23. package/dist/chunk-VH34YC3Q.js.map +0 -1
  24. package/dist/client/index.cjs +0 -16840
  25. package/dist/client/index.cjs.map +0 -1
  26. package/dist/client/index.d.cts +0 -6592
  27. package/dist/server/index.cjs +0 -3878
  28. package/dist/server/index.cjs.map +0 -1
  29. package/dist/server/index.d.cts +0 -354
  30. package/dist/token-registry-snapshot-BNBNuDu1.d.ts +0 -179
  31. package/dist/tokens-namespace-CIWBtgt2.d.ts +0 -3301
  32. package/dist/universal/index.cjs +0 -4028
  33. package/dist/universal/index.cjs.map +0 -1
  34. package/dist/universal/index.d.cts +0 -1276
@@ -1,3878 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/server/index.ts
21
- var server_exports = {};
22
- __export(server_exports, {
23
- ServerAuthNamespaceImpl: () => ServerAuthNamespaceImpl,
24
- ServerOffersNamespaceImpl: () => ServerOffersNamespaceImpl,
25
- ServerRequirementsNamespaceImpl: () => ServerRequirementsNamespaceImpl,
26
- WritableSessionStoreRequiredError: () => WritableSessionStoreRequiredError,
27
- createCoinListServer: () => createCoinListServer,
28
- emptySessionStore: () => emptySessionStore,
29
- pinoServerLogger: () => pinoServerLogger
30
- });
31
- module.exports = __toCommonJS(server_exports);
32
-
33
- // src/universal/api/http-attributes.ts
34
- var empty = {};
35
- var concat = (left, right) => ({
36
- ...left,
37
- ...right
38
- });
39
- var concatAll = (...items) => {
40
- let result = empty;
41
- for (const item of items) {
42
- result = concat(result, item);
43
- }
44
- return result;
45
- };
46
- var protectedRequest = () => ({ protected: true });
47
- var userAgent = () => ({ userAgent: true });
48
- var idempotencyKey = () => ({
49
- idempotencyKey: true
50
- });
51
- var clientCredentials = (credentials) => ({
52
- clientCredentials: credentials
53
- });
54
- var retryAttempt = (attempt) => ({
55
- retryAttempt: attempt
56
- });
57
- var renewAttempted = (value) => ({
58
- renewAttempted: value
59
- });
60
- var requestId = (id) => ({ requestId: id });
61
- var getRequestId = (attrs) => attrs?.requestId ?? null;
62
- var isProtected = (attrs) => attrs?.protected === true;
63
- var needUserAgent = (attrs) => attrs?.userAgent === true;
64
- var isIdempotent = (attrs) => attrs?.idempotencyKey === true;
65
- var getRetryAttempt = (attrs) => attrs?.retryAttempt ?? 0;
66
- var wasRenewAttempted = (attrs) => attrs?.renewAttempted === true;
67
- var getClientCredentials = (attrs) => attrs?.clientCredentials;
68
- var Attributes = {
69
- empty,
70
- concat,
71
- concatAll,
72
- protected: protectedRequest,
73
- isProtected,
74
- userAgent,
75
- needUserAgent,
76
- idempotencyKey,
77
- isIdempotent,
78
- retryAttempt,
79
- getRetryAttempt,
80
- renewAttempted,
81
- wasRenewAttempted,
82
- clientCredentials,
83
- getClientCredentials,
84
- requestId,
85
- getRequestId
86
- };
87
-
88
- // src/universal/api/http.ts
89
- var HttpError = class extends Error {
90
- constructor(response) {
91
- super(`Request failed with ${response.status} status`);
92
- this.name = "HttpError";
93
- this.response = response;
94
- }
95
- /**
96
- * Correlates this failure with the `[HTTP]` log lines for the same request,
97
- * which carry the method, the URL, the duration and every retry. `null` when
98
- * the response did not come from an {@link HttpClient}.
99
- *
100
- * Worth quoting in a bug report: it is what makes a log excerpt readable.
101
- */
102
- get requestId() {
103
- return this.response.requestId ?? null;
104
- }
105
- };
106
- function apiErrorCode(error) {
107
- if (!(error instanceof HttpError)) return null;
108
- const body = error.response.body;
109
- if (typeof body !== "object" || body === null) return null;
110
- const code = body.code;
111
- return typeof code === "string" ? code : null;
112
- }
113
- async function makeRequest(request) {
114
- const headers = {
115
- Accept: "application/json",
116
- ...request.method === "POST" && request.body !== void 0 ? { "Content-Type": "application/json" } : {},
117
- ...request.headers ?? {}
118
- };
119
- const init = {
120
- method: request.method,
121
- headers,
122
- ...request.redirect !== void 0 ? { redirect: request.redirect } : {}
123
- };
124
- if (request.method === "POST" && request.body !== void 0) {
125
- init.body = JSON.stringify(request.body);
126
- }
127
- const response = await fetch(
128
- buildUrlWithQueryParams(request.url, request.queryParams),
129
- init
130
- );
131
- const responseHeaders = headersToRecord(response.headers);
132
- if (response.status === 204 || response.status === 205) {
133
- return {
134
- status: response.status,
135
- body: null,
136
- headers: responseHeaders
137
- };
138
- }
139
- if (response.status >= 300 && response.status < 400) {
140
- await response.text();
141
- return {
142
- status: response.status,
143
- body: null,
144
- headers: responseHeaders
145
- };
146
- }
147
- const text = await response.text();
148
- let body;
149
- try {
150
- body = text ? JSON.parse(text) : null;
151
- } catch (_) {
152
- throw new HttpError({
153
- status: response.status,
154
- headers: responseHeaders,
155
- body: text
156
- });
157
- }
158
- return {
159
- status: response.status,
160
- body,
161
- headers: responseHeaders
162
- };
163
- }
164
- function buildUrlWithQueryParams(url, queryParams) {
165
- if (!queryParams) {
166
- return url;
167
- }
168
- const searchParams = new URLSearchParams();
169
- for (const [key, value] of Object.entries(queryParams)) {
170
- if (value === void 0 || value === null) {
171
- continue;
172
- }
173
- if (Array.isArray(value)) {
174
- for (const item of value) {
175
- if (item === void 0 || item === null) {
176
- continue;
177
- }
178
- searchParams.append(key, String(item));
179
- }
180
- continue;
181
- }
182
- searchParams.append(key, String(value));
183
- }
184
- const queryString = searchParams.toString();
185
- if (!queryString) {
186
- return url;
187
- }
188
- return url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
189
- }
190
- function headersToRecord(headers) {
191
- const record = {};
192
- headers.forEach((value, key) => {
193
- record[key.toLowerCase()] = value;
194
- });
195
- return record;
196
- }
197
- function concatAttributes(request, attrs) {
198
- const nextAttributes = Attributes.concat(
199
- request.attributes ?? Attributes.empty,
200
- attrs
201
- );
202
- const nextRequest = {
203
- ...request,
204
- attributes: nextAttributes
205
- };
206
- return nextRequest;
207
- }
208
- var Request = {
209
- concatAttributes
210
- };
211
-
212
- // src/universal/api/frontline/config.ts
213
- var PUBLIC_API_BASE_URL = "https://api.coinlist.co";
214
- var HEADER_API_VERSION = "X-API-Version";
215
- var HEADER_IDEMPOTENCY_KEY = "Idempotency-Key";
216
- var API_VERSION = "2025-10-17";
217
-
218
- // src/universal/core/shared/observability/log-cause.ts
219
- var import_viem = require("viem");
220
-
221
- // src/universal/types/errors.ts
222
- var NotImplementedError = class extends Error {
223
- constructor(message = "Not implemented yet") {
224
- super(message);
225
- this.name = "NotImplementedError";
226
- }
227
- };
228
- var NotAuthenticatedError = class extends Error {
229
- constructor(message = "The user is not authenticated. Go through the OAuth flow first!") {
230
- super(message);
231
- this.name = "NotAuthenticatedError";
232
- }
233
- };
234
- var ValidationError = class extends Error {
235
- constructor(message) {
236
- super(message);
237
- this.name = "ValidationError";
238
- }
239
- };
240
- var InvariantError = class extends Error {
241
- constructor(message) {
242
- super(message);
243
- this.name = "InvariantError";
244
- }
245
- };
246
- var MathError = class extends Error {
247
- constructor(message) {
248
- super(message);
249
- this.name = "MathError";
250
- }
251
- };
252
-
253
- // src/universal/core/shared/observability/log-cause.ts
254
- function classifyLogCause(error) {
255
- if (error instanceof HttpError) {
256
- return httpCause(error);
257
- }
258
- if (error instanceof ValidationError) {
259
- return { type: "validation", message: error.message };
260
- }
261
- if (error instanceof InvariantError) {
262
- return { type: "invariant", message: error.message };
263
- }
264
- if (error instanceof MathError) {
265
- return { type: "math", message: error.message };
266
- }
267
- if (error instanceof NotAuthenticatedError) {
268
- return { type: "not-authenticated" };
269
- }
270
- if (error instanceof NotImplementedError) {
271
- return { type: "not-implemented" };
272
- }
273
- if (error instanceof import_viem.BaseError) {
274
- const http2 = error.walk((e) => e instanceof HttpError);
275
- if (http2 instanceof HttpError) {
276
- return httpCause(http2);
277
- }
278
- return { type: "rpc", reason: rpcFailureReason(error) };
279
- }
280
- return { type: "generic-error", name: errorName(error) };
281
- }
282
- function rpcFailureReason(error) {
283
- if (error.walk((e) => e instanceof import_viem.ContractFunctionRevertedError)) {
284
- return "reverted";
285
- }
286
- if (error.walk((e) => e instanceof import_viem.RpcError)) {
287
- return "node-rejected";
288
- }
289
- if (error.walk(
290
- (e) => e instanceof import_viem.HttpRequestError || e instanceof import_viem.WebSocketRequestError || e instanceof import_viem.SocketClosedError || e instanceof import_viem.TimeoutError
291
- )) {
292
- return "transport";
293
- }
294
- if (error instanceof import_viem.ContractFunctionExecutionError) {
295
- return "malformed-response";
296
- }
297
- return "unknown";
298
- }
299
- function describeErrorUnredacted(error) {
300
- if (error instanceof HttpError) {
301
- return describeHttpErrorRedacted(error);
302
- }
303
- if (error instanceof Error) {
304
- return `${error.name}: ${error.message}`;
305
- }
306
- return `thrown non-error: ${stringifyUnredacted(error)}`;
307
- }
308
- function stringifyUnredacted(value) {
309
- if (value === void 0) return "";
310
- try {
311
- return JSON.stringify(
312
- value,
313
- (_key, item) => typeof item === "bigint" ? `${item}` : item
314
- ) ?? String(value);
315
- } catch (_) {
316
- return "<unserializable>";
317
- }
318
- }
319
- function describeHttpErrorRedacted(error) {
320
- const code = apiErrorCode(error);
321
- const status = error.response.status;
322
- return code === null ? `HttpError ${status}` : `HttpError ${status} (${code})`;
323
- }
324
- function errorName(error) {
325
- return error instanceof Error ? error.name : `non-error ${typeof error}`;
326
- }
327
- function httpCause(error) {
328
- return {
329
- type: "http",
330
- requestId: error.requestId,
331
- status: error.response.status,
332
- code: apiErrorCode(error),
333
- eventId: apiErrorEventId(error)
334
- };
335
- }
336
- function apiErrorEventId(error) {
337
- const body = error.response.body;
338
- if (typeof body !== "object" || body === null) return null;
339
- const eventId = body.event_id;
340
- return typeof eventId === "string" ? eventId : null;
341
- }
342
-
343
- // src/universal/core/shared/observability/internal-logger.ts
344
- function internalLogger(logger, scope) {
345
- return logger ? scopedLogger(logger, scope, {}) : noopInternalLogger;
346
- }
347
- var LEVEL_RANK = {
348
- none: 0,
349
- error: 1,
350
- warn: 2,
351
- info: 3,
352
- debug: 4
353
- };
354
- function scopedLogger(logger, scope, bindings) {
355
- const admits = (level) => LEVEL_RANK[logger.level()] >= LEVEL_RANK[level];
356
- const safe = (event) => ({
357
- msg: event.msg,
358
- scope,
359
- bindings,
360
- fields: event.fields ?? {},
361
- ...event.cause === void 0 ? {} : { cause: event.cause }
362
- });
363
- const unredacted = (event) => ({
364
- msg: event.msg,
365
- scope,
366
- bindings,
367
- fields: event.fields ?? {}
368
- });
369
- const self = {
370
- child: (binding) => scopedLogger(logger, scope, { ...bindings, ...binding }),
371
- debug: (event) => {
372
- if (admits("debug")) logger.debug(() => unredacted(event()));
373
- },
374
- info: (event) => {
375
- if (admits("info")) logger.info(() => safe(event()));
376
- },
377
- warn: (event) => {
378
- if (admits("warn")) logger.warn(() => safe(event()));
379
- },
380
- error: (event) => {
381
- if (admits("error")) logger.error(() => safe(event()));
382
- },
383
- failure: (event, error) => {
384
- if (admits("debug"))
385
- logger.debug(() => unredacted(verbatim(event(), error)));
386
- if (admits("error")) logger.error(() => safe(classified(event(), error)));
387
- },
388
- warning: (event, error) => {
389
- if (admits("debug"))
390
- logger.debug(() => unredacted(verbatim(event(), error)));
391
- if (admits("warn")) logger.warn(() => safe(classified(event(), error)));
392
- },
393
- wrap: async (op, params, run) => {
394
- const opLog = self.child({ op });
395
- opLog.debug(() => ({ msg: "call", fields: { params } }));
396
- try {
397
- return await run();
398
- } catch (error) {
399
- opLog.failure(() => ({ msg: "call failed" }), error);
400
- throw error;
401
- }
402
- }
403
- };
404
- return self;
405
- }
406
- function verbatim(event, error) {
407
- return {
408
- msg: event.msg,
409
- fields: { ...event.fields, error: describeErrorUnredacted(error) }
410
- };
411
- }
412
- function classified(event, error) {
413
- return { ...event, cause: event.cause ?? classifyLogCause(error) };
414
- }
415
- var noopInternalLogger = {
416
- child: () => noopInternalLogger,
417
- debug: () => void 0,
418
- info: () => void 0,
419
- warn: () => void 0,
420
- error: () => void 0,
421
- failure: () => void 0,
422
- warning: () => void 0,
423
- wrap: (_op, _params, run) => run()
424
- };
425
-
426
- // src/universal/api/http-client.ts
427
- var HttpClient = class {
428
- constructor(config, middleware = {}, logger = null, options = {}) {
429
- this.config = config;
430
- this.middleware = middleware;
431
- this.log = internalLogger(logger, "HTTP");
432
- this.makeRequestId = options.makeRequestId ?? defaultMakeRequestId;
433
- }
434
- async send(request) {
435
- return this.runRequestWithAfterMiddleware(request);
436
- }
437
- /**
438
- * Runs beforeRequest, executeRequest, then the full afterRequest middleware
439
- * chain. Used by send() and by the retry() callback so that when a
440
- * middleware calls retry(), the retried response also goes through all
441
- * afterRequest middleware (e.g. session renewal, retry). Middleware
442
- * must use request.attributes.retryAttempt (or similar) to avoid infinite
443
- * recursion when they trigger retries.
444
- */
445
- async runRequestWithAfterMiddleware(request) {
446
- const preparedRequest = await this.runBeforeRequestMiddleware(
447
- this.withClientDefaults(request)
448
- );
449
- let response = await this.executeRequest(preparedRequest);
450
- for (const middleware of this.middleware.afterRequest ?? []) {
451
- response = await middleware({
452
- request: preparedRequest,
453
- response,
454
- retry: (nextRequest = preparedRequest) => this.runRequestWithAfterMiddleware(nextRequest)
455
- });
456
- }
457
- return response;
458
- }
459
- withClientDefaults(request) {
460
- const url = this.resolveUrl(request.url);
461
- const headers = {
462
- ...request.headers ?? {},
463
- ...this.config.xApiVersion !== void 0 ? { [HEADER_API_VERSION]: this.config.xApiVersion } : {}
464
- };
465
- return {
466
- ...request,
467
- url,
468
- headers,
469
- // Only when absent: a retry or a post-renewal re-send arrives with the
470
- // first attempt's id already on it, and keeping it is the whole point.
471
- attributes: Attributes.getRequestId(request.attributes) === null ? Attributes.concat(
472
- request.attributes ?? Attributes.empty,
473
- Attributes.requestId(this.makeRequestId())
474
- ) : request.attributes
475
- };
476
- }
477
- /**
478
- * Resolves a request URL against the client's baseUrl.
479
- *
480
- * @internal Public only for testing. Do not use in application code; use
481
- * {@link HttpClient.send} with a path and the client will resolve the URL.
482
- */
483
- resolveUrl(url) {
484
- if (url.startsWith("http://") || url.startsWith("https://")) {
485
- return url;
486
- }
487
- const base2 = this.config.baseUrl.replace(/\/$/, "");
488
- const path = url.startsWith("/") ? url : `/${url}`;
489
- return base2 + path;
490
- }
491
- async runBeforeRequestMiddleware(initialRequest) {
492
- let request = initialRequest;
493
- for (const middleware of this.middleware.beforeRequest ?? []) {
494
- request = await middleware(request);
495
- }
496
- return request;
497
- }
498
- /**
499
- * One physical attempt, logged as one line.
500
- *
501
- * A non-2xx is a `warn` rather than an `error` because the wire does not
502
- * know whether it is a failure: the retry middleware may turn a 503 into a
503
- * success, and the token registry reads a 404 as "not listed". The namespace
504
- * above decides, and logs the `error` when it does.
505
- */
506
- async executeRequest(request) {
507
- const requestId2 = Attributes.getRequestId(request.attributes);
508
- const log = requestId2 === null ? this.log : this.log.child({ requestId: requestId2 });
509
- const attempt = Attributes.getRetryAttempt(request.attributes) + 1;
510
- const startedAt = Date.now();
511
- log.debug(() => ({
512
- msg: "request sent",
513
- fields: describeRequestUnredacted(request)
514
- }));
515
- try {
516
- const response = await makeRequest(request);
517
- const elapsed = Date.now() - startedAt;
518
- const outcome = () => ({
519
- msg: "request completed",
520
- fields: {
521
- ...identifyRequest(request),
522
- "http.response.status_code": response.status,
523
- duration_ms: elapsed,
524
- attempt
525
- }
526
- });
527
- if (response.status >= 200 && response.status < 300) {
528
- log.info(outcome);
529
- } else {
530
- log.warn(outcome);
531
- }
532
- log.debug(() => ({
533
- msg: "response received",
534
- fields: { body: response.body }
535
- }));
536
- return requestId2 === null ? response : { ...response, requestId: requestId2 };
537
- } catch (error) {
538
- const elapsed = Date.now() - startedAt;
539
- log.warning(
540
- () => ({
541
- msg: "request threw",
542
- fields: {
543
- ...identifyRequest(request),
544
- duration_ms: elapsed,
545
- attempt
546
- }
547
- }),
548
- error
549
- );
550
- throw error;
551
- }
552
- }
553
- };
554
- function identifyRequest(request) {
555
- const { host, path } = splitUrl(request.url);
556
- return {
557
- "http.request.method": request.method,
558
- "server.address": host,
559
- "url.path": path
560
- };
561
- }
562
- function splitUrl(url) {
563
- try {
564
- const parsed = new URL(url);
565
- return { host: parsed.host, path: parsed.pathname };
566
- } catch (_) {
567
- return { host: null, path: url };
568
- }
569
- }
570
- function defaultMakeRequestId() {
571
- return Math.random().toString(36).slice(2, 10).padEnd(8, "0");
572
- }
573
- function describeRequestUnredacted(request) {
574
- return {
575
- "http.request.method": request.method,
576
- "url.full": buildUrlWithQueryParams(request.url, request.queryParams),
577
- headers: request.headers,
578
- ...request.method === "POST" ? { body: request.body } : {}
579
- };
580
- }
581
-
582
- // src/universal/api/middleware/attach-session-middleware.ts
583
- function attachSessionMiddleware(fetchAccessToken) {
584
- return async (request) => {
585
- if (!Attributes.isProtected(request.attributes)) {
586
- return request;
587
- }
588
- let accessToken = await fetchAccessToken(false);
589
- if (!accessToken) {
590
- const clientCreds = Attributes.getClientCredentials(request.attributes);
591
- if (clientCreds) {
592
- accessToken = clientCreds;
593
- }
594
- }
595
- if (accessToken === null) {
596
- return request;
597
- }
598
- return {
599
- ...request,
600
- headers: {
601
- ...request.headers ?? {},
602
- Authorization: `Bearer ${accessToken.value}`
603
- }
604
- };
605
- };
606
- }
607
-
608
- // src/universal/core/shared/utils/crypto.ts
609
- function getUUIDv4() {
610
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
611
- return crypto.randomUUID();
612
- }
613
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
614
- const bytes = new Uint8Array(16);
615
- crypto.getRandomValues(bytes);
616
- bytes[6] = bytes[6] & 15 | 64;
617
- bytes[8] = bytes[8] & 63 | 128;
618
- const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0"));
619
- return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
620
- }
621
- return `${Date.now()}-${Math.random().toString(36).slice(2, 12)}`;
622
- }
623
- function notBlankStringOrNull(value) {
624
- if (value?.trim()) {
625
- return value;
626
- } else {
627
- return null;
628
- }
629
- }
630
-
631
- // src/universal/api/middleware/idempotency-key.ts
632
- var idempotencyKeyMiddleware = async (request) => {
633
- if (!Attributes.isIdempotent(request.attributes)) {
634
- return request;
635
- }
636
- const existingHeaders = request.headers ?? {};
637
- if (existingHeaders[HEADER_IDEMPOTENCY_KEY]) {
638
- return request;
639
- }
640
- return {
641
- ...request,
642
- headers: {
643
- ...existingHeaders,
644
- [HEADER_IDEMPOTENCY_KEY]: getUUIDv4()
645
- }
646
- };
647
- };
648
-
649
- // src/universal/api/middleware/request-retry.ts
650
- var MAX_ATTEMPTS = 3;
651
- var INITIAL_DELAY_MS = 300;
652
- var MAX_DELAY_MS = 2e3;
653
- var RETRYABLE_4XX = /* @__PURE__ */ new Set([408, 409, 429]);
654
- function isRetryableStatus(status) {
655
- return status >= 500 && status < 600 || RETRYABLE_4XX.has(status);
656
- }
657
- function getRetryDelayMs(attempt) {
658
- return Math.min(INITIAL_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);
659
- }
660
- function createRequestRetryMiddleware(options = {}) {
661
- const delayFn = options.delayFn ?? defaultDelay;
662
- return async ({ request, response, retry }) => {
663
- if (!isRetryableStatus(response.status)) {
664
- return response;
665
- }
666
- const currentAttempt = Attributes.getRetryAttempt(request.attributes);
667
- if (currentAttempt >= MAX_ATTEMPTS - 1) {
668
- return response;
669
- }
670
- const nextAttempt = currentAttempt + 1;
671
- await delayFn(getRetryDelayMs(nextAttempt));
672
- const nextRequest = Request.concatAttributes(
673
- request,
674
- Attributes.retryAttempt(nextAttempt)
675
- );
676
- return retry(nextRequest);
677
- };
678
- }
679
- function defaultDelay(ms) {
680
- return new Promise((resolve) => setTimeout(resolve, ms));
681
- }
682
- var requestRetryMiddleware = createRequestRetryMiddleware();
683
-
684
- // src/universal/api/middleware/session-renewal.ts
685
- function renewSessionMiddleware(fetchAccessToken) {
686
- return async ({ request, response, retry }) => {
687
- if (response.status !== 401) {
688
- return response;
689
- }
690
- if (!Attributes.isProtected(request.attributes)) {
691
- return response;
692
- }
693
- if (Attributes.wasRenewAttempted(request.attributes)) {
694
- return response;
695
- }
696
- const newToken = await fetchAccessToken(true);
697
- if (newToken) {
698
- const nextRequest = Request.concatAttributes(
699
- request,
700
- Attributes.renewAttempted(true)
701
- );
702
- return retry(nextRequest);
703
- } else {
704
- return response;
705
- }
706
- };
707
- }
708
-
709
- // src/universal/api/authenticated-api-client.ts
710
- var AuthenticatedApiClient = class {
711
- constructor(config, fetchAccessToken, additionalBeforeRequest = [], logger = null) {
712
- this.httpClient = new HttpClient(
713
- config,
714
- {
715
- beforeRequest: [
716
- attachSessionMiddleware(fetchAccessToken),
717
- ...additionalBeforeRequest,
718
- idempotencyKeyMiddleware
719
- ],
720
- afterRequest: [
721
- renewSessionMiddleware(fetchAccessToken),
722
- requestRetryMiddleware
723
- ]
724
- },
725
- logger
726
- );
727
- }
728
- async send(request) {
729
- const response = await this.httpClient.send(request);
730
- if (response.status >= 200 && response.status < 300) {
731
- return response.body;
732
- } else {
733
- throw new HttpError(response);
734
- }
735
- }
736
- };
737
-
738
- // src/server/core/api/api-client.ts
739
- var ApiClient = class {
740
- constructor(config, fetchAccessToken, logger = null) {
741
- this.client = new AuthenticatedApiClient(
742
- config,
743
- fetchAccessToken,
744
- [],
745
- logger
746
- );
747
- }
748
- async send(request) {
749
- return this.client.send(request);
750
- }
751
- };
752
-
753
- // src/server/shared/errors.ts
754
- var WritableSessionStoreRequiredError = class extends Error {
755
- constructor(message = "This operation requires a writable SessionStore. Provide a `setSession` implementation in your SessionStore to persist or clear OAuth sessions.") {
756
- super(message);
757
- this.name = "WritableSessionStoreRequiredError";
758
- }
759
- };
760
-
761
- // src/universal/types/oauth-session.ts
762
- var ClientCredentialsOAuth = (value) => value;
763
- var OAuthRefreshToken = (value) => value;
764
- var OAuthSession = {
765
- fromDto: (dto) => {
766
- const expiresAt = new Date(Date.now() + dto.expires_in * 1e3);
767
- return {
768
- accessToken: {
769
- value: dto.access_token,
770
- expiresAt
771
- },
772
- ...dto.refresh_token != null && dto.refresh_token !== "" ? { refreshToken: OAuthRefreshToken(dto.refresh_token) } : void 0
773
- };
774
- }
775
- };
776
-
777
- // src/server/core/server-auth-namespace.ts
778
- function emptySessionStore() {
779
- return { getSession: async () => null };
780
- }
781
- var ServerAuthNamespaceImpl = class {
782
- constructor(api, config) {
783
- this.api = api;
784
- this.config = config;
785
- this.log = internalLogger(config.logger ?? null, "AUTH");
786
- }
787
- async completeOAuth(params) {
788
- return this.log.wrap("completeOAuth", void 0, async () => {
789
- const setSession = this.writableSessionStore();
790
- const sessionDto = await this.api.send({
791
- method: "POST",
792
- url: `/oauth/token`,
793
- body: {
794
- grant_type: "authorization_code",
795
- code: params.code,
796
- redirect_uri: this.config.redirectUri,
797
- client_id: this.config.clientId,
798
- client_secret: this.config.clientSecret,
799
- code_verifier: params.codeVerifier
800
- }
801
- });
802
- const session = OAuthSession.fromDto(sessionDto);
803
- await setSession(session);
804
- return session;
805
- });
806
- }
807
- async getAccessToken() {
808
- return this.log.wrap(
809
- "getAccessToken",
810
- void 0,
811
- () => this.readAccessToken()
812
- );
813
- }
814
- async readAccessToken() {
815
- const sessionStore = this.config.sessionStore;
816
- const session = await sessionStore.getSession();
817
- if (session == null) return null;
818
- const now = Date.now();
819
- const expiresAt = session.accessToken.expiresAt.getTime();
820
- const bufferMs = this.config.accessTokenExpiryBufferSeconds * 1e3;
821
- if (expiresAt > now + bufferMs) {
822
- return session.accessToken;
823
- }
824
- const setSession = sessionStore.setSession?.bind(sessionStore);
825
- if (!setSession) {
826
- this.log.child({ op: "getAccessToken" }).warn(() => ({
827
- msg: "serving an expired token: the session store is read-only, so it cannot be refreshed"
828
- }));
829
- return session.accessToken;
830
- }
831
- return this.refreshSession(session.refreshToken, setSession);
832
- }
833
- async refreshSession(refreshToken, setSession) {
834
- const log = this.log.child({ op: "refresh" });
835
- if (!refreshToken) {
836
- log.warn(() => ({
837
- msg: "clearing the session: it carries no refresh token"
838
- }));
839
- await setSession(null);
840
- return null;
841
- }
842
- try {
843
- const sessionDto = await this.api.send({
844
- method: "POST",
845
- url: `/oauth/token`,
846
- body: {
847
- grant_type: "refresh_token",
848
- refresh_token: refreshToken,
849
- client_id: this.config.clientId,
850
- client_secret: this.config.clientSecret
851
- }
852
- });
853
- const newSession = OAuthSession.fromDto(sessionDto);
854
- await setSession(newSession);
855
- log.info(() => ({ msg: "session renewed" }));
856
- return newSession.accessToken;
857
- } catch (error) {
858
- log.failure(
859
- () => ({ msg: "refresh failed; clearing the session" }),
860
- error
861
- );
862
- await setSession(null);
863
- return null;
864
- }
865
- }
866
- async clientCredentials() {
867
- return this.log.wrap("clientCredentials", void 0, async () => {
868
- const sessionDto = await this.api.send({
869
- method: "POST",
870
- url: `/oauth/token`,
871
- body: {
872
- grant_type: "client_credentials",
873
- client_id: this.config.clientId,
874
- client_secret: this.config.clientSecret
875
- }
876
- });
877
- const session = OAuthSession.fromDto(sessionDto);
878
- return ClientCredentialsOAuth(session.accessToken);
879
- });
880
- }
881
- async logout() {
882
- return this.log.wrap("logout", void 0, () => this.revokeAndClear());
883
- }
884
- async revokeAndClear() {
885
- const setSession = this.writableSessionStore();
886
- const session = await this.config.sessionStore.getSession();
887
- if (session == null) return;
888
- try {
889
- await this.api.send({
890
- method: "POST",
891
- url: `/oauth/revoke`,
892
- body: {
893
- token: session.accessToken.value,
894
- client_id: this.config.clientId,
895
- client_secret: this.config.clientSecret
896
- }
897
- });
898
- } catch (err) {
899
- if (!(err instanceof HttpError) || this.config.strict) {
900
- throw err;
901
- }
902
- this.log.child({ op: "logout" }).warn(() => ({
903
- msg: "the token was not revoked upstream; the local session is cleared regardless"
904
- }));
905
- }
906
- await setSession(null);
907
- }
908
- /**
909
- * Returns the store's `setSession`, or throws — the guard every
910
- * session-writing operation shares.
911
- */
912
- writableSessionStore() {
913
- const sessionStore = this.config.sessionStore;
914
- const setSession = sessionStore.setSession?.bind(sessionStore);
915
- if (!setSession) {
916
- throw new WritableSessionStoreRequiredError();
917
- }
918
- return setSession;
919
- }
920
- };
921
-
922
- // src/universal/api/pagination.ts
923
- async function fetchAllPages(fetchPage, baseParams) {
924
- const items = [];
925
- let cursor = null;
926
- do {
927
- const params = {
928
- ...baseParams ?? {},
929
- after: cursor ?? void 0
930
- };
931
- const page = await fetchPage(params);
932
- items.push(...page.data);
933
- cursor = page.startingAfter;
934
- } while (cursor);
935
- return items;
936
- }
937
-
938
- // src/universal/core/shared/utils/wire.ts
939
- function unknownTypeError(dto, model) {
940
- const type = dto.type;
941
- throw new ValidationError(
942
- `${model}.type: unknown type ${JSON.stringify(type)}`
943
- );
944
- }
945
- function requiredString(value, field) {
946
- const text = notBlankStringOrNull(value);
947
- if (text === null) {
948
- throw new ValidationError(
949
- `${field}: expected a non-blank string, got ${typeof value === "string" ? "a blank string" : String(value)}`
950
- );
951
- }
952
- return text;
953
- }
954
- function requiredDate(value, field) {
955
- const date = typeof value === "string" ? new Date(value) : null;
956
- if (date === null || Number.isNaN(date.getTime())) {
957
- throw new ValidationError(
958
- `${field}: expected a date, got ${JSON.stringify(value)}`
959
- );
960
- }
961
- return date;
962
- }
963
- function requiredArray(value, field) {
964
- if (!Array.isArray(value)) {
965
- throw new ValidationError(
966
- `${field}: expected an array, got ${typeof value}`
967
- );
968
- }
969
- return value;
970
- }
971
-
972
- // src/universal/types/blockchain/core.ts
973
- var ETHEREUM_CHAINS = {
974
- ethereum_mainnet: true,
975
- ethereum_sepolia: true,
976
- base_mainnet: true,
977
- base_sepolia: true
978
- };
979
- var EthereumChain = (value) => {
980
- if (!Object.keys(ETHEREUM_CHAINS).includes(value)) {
981
- throw new ValidationError(`Unsupported Ethereum chain: "${value}"`);
982
- }
983
- return value;
984
- };
985
- var SOLANA_CHAINS = {
986
- solana_mainnet: true,
987
- solana_devnet: true
988
- };
989
- var isChain = (value) => Object.keys(ETHEREUM_CHAINS).includes(value) || Object.keys(SOLANA_CHAINS).includes(value);
990
- var Chain = (value) => {
991
- if (!isChain(value)) {
992
- throw new ValidationError(`Unsupported chain: "${value}"`);
993
- }
994
- return value;
995
- };
996
- var EvmWalletAddress = (value) => value;
997
- var EvmContractAddress = (value) => value;
998
- var HexEncodedTransactionData = (value) => value;
999
- var MAX_ASSET_DECIMALS = 77;
1000
- var AssetDecimals = (value) => {
1001
- if (!Number.isInteger(value)) {
1002
- throw new ValidationError(`Asset decimals must be an integer: ${value}`);
1003
- }
1004
- if (value < 0 || value > MAX_ASSET_DECIMALS) {
1005
- throw new ValidationError(
1006
- `Asset decimals out of range [0, ${MAX_ASSET_DECIMALS}]: ${value}`
1007
- );
1008
- }
1009
- return value;
1010
- };
1011
- var STABLE_DECIMALS = AssetDecimals(6);
1012
- var DecimalString = (value) => value;
1013
- var MAX_UINT_256 = 2n ** 256n - 1n;
1014
- var assertUint256 = (value) => {
1015
- if (isUint256(value)) return value;
1016
- throw new InvariantError(`Value out of uint256 bounds: ${value}`);
1017
- };
1018
- var parseUint256 = (value, label) => {
1019
- if (isUint256(value)) return value;
1020
- throw new ValidationError(`${label}: out of uint256 bounds (${value})`);
1021
- };
1022
- var isUint256 = (value) => value >= 0n && value <= MAX_UINT_256;
1023
- var BlockchainAmount = Object.assign(
1024
- (value) => value,
1025
- {
1026
- add: (a, b) => combineAmounts(a, b, (x, y) => x + y),
1027
- sub: (a, b) => combineAmounts(a, b, (x, y) => x - y),
1028
- mul: multiplyAmounts,
1029
- div: divideAmounts
1030
- }
1031
- );
1032
- function multiplyAmounts(a, b) {
1033
- const product = a.raw * b.raw;
1034
- return BlockchainAmount({
1035
- raw: product / 10n ** BigInt(b.decimals),
1036
- decimals: a.decimals
1037
- });
1038
- }
1039
- function divideAmounts(a, b) {
1040
- if (b.raw === 0n) {
1041
- throw new MathError("Cannot divide a BlockchainAmount by zero");
1042
- }
1043
- const scaled = a.raw * 10n ** BigInt(b.decimals);
1044
- return BlockchainAmount({ raw: scaled / b.raw, decimals: a.decimals });
1045
- }
1046
- function combineAmounts(a, b, op) {
1047
- if (a.decimals !== b.decimals) {
1048
- throw new InvariantError(
1049
- `Cannot combine BlockchainAmounts with different decimals: ${a.decimals} vs ${b.decimals}`
1050
- );
1051
- }
1052
- const raw = op(a.raw, b.raw);
1053
- if (raw < 0n || raw > MAX_UINT_256) {
1054
- throw new InvariantError(`BlockchainAmount out of uint256 bounds: ${raw}`);
1055
- }
1056
- return BlockchainAmount({ raw, decimals: a.decimals });
1057
- }
1058
- var AssetSymbol = (value) => value;
1059
-
1060
- // src/universal/types/offer.ts
1061
- var OfferId = (value) => value;
1062
- var OfferSlug = (value) => value;
1063
- var OFFER_TYPES = {
1064
- "coinlist::token_sale": true,
1065
- "superstate::swap": true,
1066
- "ondo::swap": true
1067
- };
1068
- var isOfferType = (value) => Object.keys(OFFER_TYPES).includes(value);
1069
- var OfferEditorial = {
1070
- /**
1071
- * `model` prefixes the field in the error (`'Offer'`, `'OfferDetail'`), so
1072
- * the same three checks name the payload that failed them.
1073
- */
1074
- fromDto: (dto, model) => ({
1075
- tagline: requiredString(dto.tagline, `${model}.tagline`),
1076
- bannerUrl: requiredString(dto.banner_url, `${model}.banner_url`),
1077
- startsAt: requiredDate(dto.starts_at, `${model}.starts_at`)
1078
- })
1079
- };
1080
- var Offer = {
1081
- fromDto: (dto) => {
1082
- const tokens = requiredArray(dto.tokens, "Offer.tokens");
1083
- const base2 = {
1084
- id: OfferId(dto.id),
1085
- slug: OfferSlug(dto.slug),
1086
- endsAt: dto.ends_at ? new Date(dto.ends_at) : null,
1087
- tokens: OfferToken.listFromDto(tokens)
1088
- };
1089
- switch (dto.type) {
1090
- case "coinlist::token_sale":
1091
- return {
1092
- ...base2,
1093
- ...OfferEditorial.fromDto(dto, "Offer"),
1094
- type: dto.type,
1095
- logoUrl: requiredString(dto.logo_url, "Offer.logo_url")
1096
- };
1097
- case "superstate::swap":
1098
- return {
1099
- ...base2,
1100
- ...OfferEditorial.fromDto(dto, "Offer"),
1101
- type: dto.type,
1102
- logoUrl: notBlankStringOrNull(dto.logo_url)
1103
- };
1104
- // `tagline`, `banner_url` and `starts_at` arrive as `null` and are left
1105
- // on the wire: copying them would hand every consumer a `startsAt` that
1106
- // is 1970 for one variant and a date for the others.
1107
- case "ondo::swap":
1108
- return {
1109
- ...base2,
1110
- type: dto.type,
1111
- logoUrl: notBlankStringOrNull(dto.logo_url)
1112
- };
1113
- default:
1114
- return unknownTypeError(dto, "Offer");
1115
- }
1116
- },
1117
- /**
1118
- * Maps a page of offers, dropping every offer whose `type` this SDK does not
1119
- * name. The same reasoning as {@link OfferToken.listFromDto}: a plain `.map`
1120
- * would throw out of `fromDto` and, through `PaginatedResponse.fromDto`,
1121
- * reject the whole page, so one offer of an unknown type would blank the
1122
- * grid for every offer beside it. A single offer fetched by id still
1123
- * throws, because there is nothing beside it to keep.
1124
- */
1125
- listFromDto: (dtos) => dtos.filter((dto) => isOfferType(dto.type)).map(Offer.fromDto)
1126
- };
1127
- var OfferToken = {
1128
- fromDto: (dto) => ({
1129
- role: dto.role,
1130
- chain: Chain(dto.chain),
1131
- address: EvmContractAddress(dto.address)
1132
- }),
1133
- /**
1134
- * Maps an offer's token list, dropping every token on a chain this SDK does
1135
- * not name. Frontline's chain registry runs ahead of {@link Chain}, and a
1136
- * plain `.map` would throw out of `Offer.fromDto` and, through
1137
- * `PaginatedResponse.fromDto`, reject the whole offers page - which is how
1138
- * one Base token blanked production's offers list. Dropping costs that
1139
- * token's metadata alone: `coinlist.tokens.get` takes an `EthereumChain`,
1140
- * so nobody could have looked it up anyway.
1141
- *
1142
- * Same shape as `TokenMetadata.fromRegistryDto`.
1143
- */
1144
- listFromDto: (dtos) => dtos.filter((dto) => isChain(dto.chain)).map(OfferToken.fromDto)
1145
- };
1146
-
1147
- // src/universal/types/asset.ts
1148
- var AssetId = (value) => value;
1149
- var AssetCode = (value) => value;
1150
- var Asset = {
1151
- fromDto: (dto) => ({
1152
- id: AssetId(dto.id),
1153
- code: AssetCode(dto.code),
1154
- name: dto.name,
1155
- fractionalDigits: dto.fractional_digits
1156
- })
1157
- };
1158
-
1159
- // src/universal/types/trading.ts
1160
- var Ticker = (value) => value;
1161
- var Isin = (value) => value;
1162
-
1163
- // src/universal/types/offer-detail.ts
1164
- var OfferOptionId = (value) => value;
1165
- var OfferOptionSlug = (value) => value;
1166
- var OfferSwapContract = {
1167
- fromDto: (dto) => ({
1168
- chain: Chain(dto.chain),
1169
- address: EvmContractAddress(dto.address)
1170
- })
1171
- };
1172
- var OfferDetail = {
1173
- fromDto: (dto) => {
1174
- const fundingAssets = requiredArray(
1175
- dto.funding_assets,
1176
- "OfferDetail.funding_assets"
1177
- );
1178
- const options = requiredArray(dto.options, "OfferDetail.options");
1179
- const terms = requiredArray(dto.terms, "OfferDetail.terms");
1180
- const links = requiredArray(dto.links, "OfferDetail.links");
1181
- const faqs = requiredArray(dto.faqs, "OfferDetail.faqs");
1182
- const milestones = requiredArray(dto.milestones, "OfferDetail.milestones");
1183
- const tokens = requiredArray(dto.tokens, "OfferDetail.tokens");
1184
- const isin = notBlankStringOrNull(dto.isin);
1185
- const ticker = notBlankStringOrNull(dto.ticker);
1186
- const base2 = {
1187
- id: OfferId(dto.id),
1188
- slug: OfferSlug(dto.slug),
1189
- name: dto.name,
1190
- asset: Asset.fromDto(dto.asset),
1191
- fundingAssets: fundingAssets.map(Asset.fromDto),
1192
- tokens: OfferToken.listFromDto(tokens),
1193
- about: notBlankStringOrNull(dto.about),
1194
- category: dto.category,
1195
- issuer: notBlankStringOrNull(dto.issuer),
1196
- isin: isin === null ? null : Isin(isin),
1197
- ticker: ticker === null ? null : Ticker(ticker),
1198
- instrumentType: notBlankStringOrNull(dto.instrument_type),
1199
- listingVenue: notBlankStringOrNull(dto.listing_venue),
1200
- endsAt: dto.ends_at ? new Date(dto.ends_at) : null,
1201
- faqs: faqs.map(FaqItem.fromDto),
1202
- links: links.map(Link.fromDto),
1203
- milestones: milestones.map(Milestone.fromDto),
1204
- options: options.map(OfferOption.fromDto),
1205
- terms: terms.map(TermItem.fromDto)
1206
- };
1207
- switch (dto.type) {
1208
- case "coinlist::token_sale":
1209
- return {
1210
- ...base2,
1211
- ...OfferEditorial.fromDto(dto, "OfferDetail"),
1212
- type: dto.type,
1213
- logoUrl: requiredString(dto.logo_url, "OfferDetail.logo_url")
1214
- };
1215
- case "superstate::swap":
1216
- return {
1217
- ...base2,
1218
- ...OfferEditorial.fromDto(dto, "OfferDetail"),
1219
- type: dto.type,
1220
- logoUrl: notBlankStringOrNull(dto.logo_url)
1221
- };
1222
- // `tagline`, `banner_url` and `starts_at` arrive as `null` and are left
1223
- // on the wire, as in `Offer.fromDto`.
1224
- case "ondo::swap":
1225
- return {
1226
- ...base2,
1227
- type: dto.type,
1228
- logoUrl: notBlankStringOrNull(dto.logo_url),
1229
- swapContracts: requiredArray(
1230
- dto.swap_contracts,
1231
- "OfferDetail.swap_contracts"
1232
- ).map(OfferSwapContract.fromDto)
1233
- };
1234
- default:
1235
- return unknownTypeError(dto, "OfferDetail");
1236
- }
1237
- }
1238
- };
1239
- var OfferOption = {
1240
- fromDto: (dto) => ({
1241
- id: OfferOptionId(dto.id),
1242
- slug: OfferOptionSlug(dto.slug),
1243
- bidIncrement: dto.bid_increment,
1244
- floorPriceUsd: dto.floor_price_usd,
1245
- minimumPurchaseUsd: dto.minimum_purchase_usd,
1246
- priceUsd: dto.price_usd,
1247
- saleAgreementUrl: notBlankStringOrNull(dto.sale_agreement_url),
1248
- totalTokenSupply: dto.total_token_supply
1249
- })
1250
- };
1251
- var FaqItem = {
1252
- fromDto: (dto) => ({
1253
- question: notBlankStringOrNull(dto.question),
1254
- answer: notBlankStringOrNull(dto.answer)
1255
- })
1256
- };
1257
- var Link = {
1258
- fromDto: (dto) => ({
1259
- label: notBlankStringOrNull(dto.label),
1260
- url: notBlankStringOrNull(dto.url)
1261
- })
1262
- };
1263
- var TermItem = {
1264
- fromDto: (dto) => ({
1265
- key: notBlankStringOrNull(dto.key),
1266
- value: notBlankStringOrNull(dto.value)
1267
- })
1268
- };
1269
- var Milestone = {
1270
- fromDto: (dto) => ({
1271
- name: notBlankStringOrNull(dto.name),
1272
- schedule: notBlankStringOrNull(dto.schedule),
1273
- status: dto.status
1274
- })
1275
- };
1276
-
1277
- // src/universal/types/pagination.ts
1278
- var Cursor = (value) => value;
1279
- var PaginatedResponse = {
1280
- fromDto: (dto, itemMapper) => PaginatedResponse.fromDtoPage(dto, (items) => items.map(itemMapper)),
1281
- /**
1282
- * For a mapper that decides the page as a whole - one that drops items it
1283
- * cannot map, such as `Offer.listFromDto` - rather than item by item. The
1284
- * cursors are the wire's either way: dropping an item changes what the
1285
- * page holds, not where the next page starts.
1286
- */
1287
- fromDtoPage: (dto, pageMapper) => ({
1288
- data: pageMapper(dto.data),
1289
- startingAfter: dto.starting_after ? Cursor(dto.starting_after) : null,
1290
- startingBefore: dto.starting_before ? Cursor(dto.starting_before) : null
1291
- })
1292
- };
1293
- var PaginationParams = {
1294
- toQueryParams: (params) => {
1295
- const queryParams = {};
1296
- if (params.after) {
1297
- queryParams.starting_after = params.after;
1298
- }
1299
- if (params.before) {
1300
- queryParams.starting_before = params.before;
1301
- }
1302
- if (params.limit) {
1303
- queryParams.limit = params.limit;
1304
- }
1305
- return queryParams;
1306
- }
1307
- };
1308
-
1309
- // src/universal/api/frontline/offers.ts
1310
- async function fetchOffers(api, clientCreds) {
1311
- return fetchAllPages((params) => fetchOffersPage(api, params, clientCreds));
1312
- }
1313
- async function fetchOffersPage(api, params, clientCreds) {
1314
- const queryParams = PaginationParams.toQueryParams(params);
1315
- const pageDto = await api.send({
1316
- method: "GET",
1317
- url: "/v1/offers",
1318
- queryParams,
1319
- attributes: Attributes.concat(
1320
- Attributes.protected(),
1321
- Attributes.clientCredentials(clientCreds)
1322
- )
1323
- });
1324
- return PaginatedResponse.fromDtoPage(pageDto, Offer.listFromDto);
1325
- }
1326
- async function fetchOfferDetails(api, id, clientCreds) {
1327
- const dto = await api.send({
1328
- method: "GET",
1329
- url: `/v1/offers/${id}`,
1330
- attributes: Attributes.concat(
1331
- Attributes.protected(),
1332
- Attributes.clientCredentials(clientCreds)
1333
- )
1334
- });
1335
- return OfferDetail.fromDto(dto);
1336
- }
1337
-
1338
- // src/server/core/server-offers-namespace.ts
1339
- var ServerOffersNamespaceImpl = class {
1340
- constructor(ctx) {
1341
- this.ctx = ctx;
1342
- this.log = internalLogger(ctx.logger, "OFFERS");
1343
- }
1344
- async list(clientCreds) {
1345
- return this.log.wrap("list", clientCreds, async () => {
1346
- await this.ctx.ensureAuthenticated(clientCreds);
1347
- return fetchOffers(this.ctx.api, clientCreds);
1348
- });
1349
- }
1350
- async listPage(params, clientCreds) {
1351
- return this.log.wrap("listPage", { params, clientCreds }, async () => {
1352
- await this.ctx.ensureAuthenticated(clientCreds);
1353
- return fetchOffersPage(this.ctx.api, params, clientCreds);
1354
- });
1355
- }
1356
- async get(id, clientCreds) {
1357
- return this.log.wrap("get", { id, clientCreds }, async () => {
1358
- await this.ctx.ensureAuthenticated(clientCreds);
1359
- return fetchOfferDetails(this.ctx.api, id, clientCreds);
1360
- });
1361
- }
1362
- };
1363
-
1364
- // src/universal/types/requirement.ts
1365
- var RequirementId = (value) => value;
1366
- var Requirement = {
1367
- fromDto: (dto) => ({
1368
- id: RequirementId(dto.id),
1369
- type: dto.type,
1370
- details: dto.details
1371
- })
1372
- };
1373
- var RequirementStatusInfo = {
1374
- fromStatusesDto: (dto) => Object.entries(dto.statuses).map(
1375
- ([id, value]) => typeof value === "string" ? { id: RequirementId(id), status: value, action: null } : {
1376
- id: RequirementId(id),
1377
- status: value.status,
1378
- action: value.action ?? null,
1379
- kycLevel: value.kyc_level,
1380
- kycReset: value.kyc_reset
1381
- }
1382
- )
1383
- };
1384
-
1385
- // src/universal/api/frontline/requirements.ts
1386
- async function fetchOfferRequirements(api, offerId, clientCreds) {
1387
- const response = await api.send({
1388
- method: "GET",
1389
- url: `/v1/offers/${offerId}/requirements`,
1390
- attributes: Attributes.concat(
1391
- Attributes.protected(),
1392
- Attributes.clientCredentials(clientCreds)
1393
- )
1394
- });
1395
- return Object.fromEntries(
1396
- Object.entries(response.options).map(([optionId, list]) => [
1397
- optionId,
1398
- list.data.map(Requirement.fromDto)
1399
- ])
1400
- );
1401
- }
1402
- async function fetchRequirementStatuses(api, offerId) {
1403
- const response = await api.send({
1404
- method: "GET",
1405
- url: `/v1/offers/${offerId}/requirements/statuses`,
1406
- attributes: Attributes.protected()
1407
- });
1408
- return RequirementStatusInfo.fromStatusesDto(response);
1409
- }
1410
-
1411
- // src/universal/types/document-submission.ts
1412
- var DocumentSubmission = {
1413
- fromDto: (dto) => ({
1414
- status: dto.status,
1415
- formType: dto.form_type
1416
- })
1417
- };
1418
-
1419
- // src/universal/api/frontline/documents.ts
1420
- async function submitDocument(api, documentType, fields) {
1421
- const dto = await api.send({
1422
- method: "POST",
1423
- url: `/v1/documents/${documentType}/submission`,
1424
- body: fields,
1425
- attributes: Attributes.protected()
1426
- });
1427
- return DocumentSubmission.fromDto(dto);
1428
- }
1429
-
1430
- // src/universal/types/kyc.ts
1431
- var KycToken = {
1432
- fromDto: (dto) => ({
1433
- token: dto.token
1434
- })
1435
- };
1436
-
1437
- // src/universal/api/frontline/kyc.ts
1438
- async function createKycToken(api, levelName, reset) {
1439
- const dto = await api.send({
1440
- method: "POST",
1441
- url: "/v1/kyc-token",
1442
- body: {
1443
- ...levelName === void 0 ? {} : { level_name: levelName },
1444
- ...reset === void 0 ? {} : { reset }
1445
- },
1446
- attributes: Attributes.protected()
1447
- });
1448
- return KycToken.fromDto(dto);
1449
- }
1450
-
1451
- // src/universal/types/pii.ts
1452
- var Iso2CountryCode = (value) => value;
1453
- var PiiJurisdiction = {
1454
- fromDto: (dto) => ({
1455
- iso2: Iso2CountryCode(dto.iso_2),
1456
- name: dto.name
1457
- })
1458
- };
1459
- var PiiAddress = {
1460
- fromDto: (dto) => ({
1461
- street: dto.street,
1462
- city: dto.city,
1463
- state: dto.state,
1464
- postalCode: dto.postal_code,
1465
- country: dto.country
1466
- })
1467
- };
1468
- var Pii = {
1469
- fromDto: (dto) => ({
1470
- kind: dto.kind,
1471
- fullLegalName: dto.full_legal_name,
1472
- dateOfBirth: dto.date_of_birth,
1473
- jurisdiction: dto.jurisdiction ? PiiJurisdiction.fromDto(dto.jurisdiction) : null,
1474
- taxId: dto.tax_id,
1475
- permanentAddress: PiiAddress.fromDto(dto.permanent_address)
1476
- })
1477
- };
1478
-
1479
- // src/universal/api/frontline/pii.ts
1480
- async function fetchPii(api) {
1481
- const dto = await api.send({
1482
- method: "GET",
1483
- url: "/v1/pii",
1484
- attributes: Attributes.protected()
1485
- });
1486
- return Pii.fromDto(dto);
1487
- }
1488
-
1489
- // src/universal/core/requirements/requirements-namespace.ts
1490
- var RequirementsNamespaceImpl = class {
1491
- constructor(ctx) {
1492
- this.ctx = ctx;
1493
- this.log = internalLogger(ctx.logger, "REQUIREMENTS");
1494
- }
1495
- async forOffer(offerId) {
1496
- return this.log.wrap("forOffer", offerId, async () => {
1497
- await this.ctx.ensureUserAuthenticated();
1498
- return fetchOfferRequirements(
1499
- this.ctx.api,
1500
- offerId,
1501
- void 0
1502
- );
1503
- });
1504
- }
1505
- async statuses(offerId) {
1506
- return this.log.wrap("statuses", offerId, async () => {
1507
- await this.ctx.ensureUserAuthenticated();
1508
- return fetchRequirementStatuses(this.ctx.api, offerId);
1509
- });
1510
- }
1511
- async createKycToken(params) {
1512
- return this.log.wrap("createKycToken", params, async () => {
1513
- await this.ctx.ensureUserAuthenticated();
1514
- return createKycToken(
1515
- this.ctx.api,
1516
- params?.levelName,
1517
- params?.reset
1518
- );
1519
- });
1520
- }
1521
- async getPii() {
1522
- return this.log.wrap("getPii", void 0, async () => {
1523
- await this.ctx.ensureUserAuthenticated();
1524
- return fetchPii(this.ctx.api);
1525
- });
1526
- }
1527
- async submitDocument(params) {
1528
- return this.log.wrap("submitDocument", params, async () => {
1529
- await this.ctx.ensureUserAuthenticated();
1530
- return submitDocument(
1531
- this.ctx.api,
1532
- params.documentType,
1533
- params.fields
1534
- );
1535
- });
1536
- }
1537
- };
1538
-
1539
- // src/server/core/server-requirements-namespace.ts
1540
- var ServerRequirementsNamespaceImpl = class extends RequirementsNamespaceImpl {
1541
- constructor(serverCtx) {
1542
- super(serverCtx);
1543
- this.serverCtx = serverCtx;
1544
- }
1545
- async forOffer(offerId, clientCreds) {
1546
- return this.log.wrap("forOffer", { offerId, clientCreds }, async () => {
1547
- await this.serverCtx.ensureAuthenticated(clientCreds);
1548
- return fetchOfferRequirements(
1549
- this.serverCtx.api,
1550
- offerId,
1551
- clientCreds
1552
- );
1553
- });
1554
- }
1555
- };
1556
-
1557
- // src/universal/api/nabu/config.ts
1558
- var NABU_BASE_URL = "https://asset.coinlist.co";
1559
-
1560
- // src/universal/api/rpc/public-clients.ts
1561
- var import_viem3 = require("viem");
1562
-
1563
- // src/universal/api/rpc/frontline-transport.ts
1564
- var import_viem2 = require("viem");
1565
- function frontlineTransport(api, chain, logger = null) {
1566
- const log = internalLogger(logger, "RPC");
1567
- let nextId = 0;
1568
- return (0, import_viem2.custom)(
1569
- {
1570
- async request({ method, params }) {
1571
- const id = ++nextId;
1572
- return sendRpc({ api, log, chain, id, method, params });
1573
- }
1574
- },
1575
- // The `Sender` below already retries: `requestRetryMiddleware` makes three
1576
- // attempts at a 5xx and `renewSessionMiddleware` re-sends once after a 401.
1577
- // viem's own default is `retryCount: 3`, and it applies on top: an
1578
- // `HttpError` carries no numeric `code`, so `buildRequest` wraps it in
1579
- // `UnknownRpcError` (`code === -1`) and `shouldRetry` says yes. That reruns
1580
- // the whole pipeline four times - twelve requests for one `eth_call`, and
1581
- // with multicall batching one `eth_call` is a screen's worth of reads. The
1582
- // SDK's retry policy is the one that applies, so viem's is turned off.
1583
- { retryCount: 0 }
1584
- );
1585
- }
1586
- async function sendRpc({
1587
- api,
1588
- log,
1589
- chain,
1590
- id,
1591
- method,
1592
- params
1593
- }) {
1594
- const url = rpcPath(chain);
1595
- const startedAt = Date.now();
1596
- log.debug(() => ({
1597
- msg: "rpc call sent",
1598
- fields: { id, method, chain, params }
1599
- }));
1600
- const response = await sendEnvelope(api, url, {
1601
- jsonrpc: "2.0",
1602
- id,
1603
- method,
1604
- params
1605
- });
1606
- const elapsed = Date.now() - startedAt;
1607
- if (response.error) {
1608
- const error = new import_viem2.RpcRequestError({
1609
- body: { method, params },
1610
- error: response.error,
1611
- url
1612
- });
1613
- log.warning(
1614
- () => ({
1615
- msg: "rpc call rejected",
1616
- cause: { type: "rpc", reason: "node-rejected" },
1617
- fields: {
1618
- method,
1619
- chain,
1620
- duration_ms: elapsed,
1621
- "rpc.error_code": response.error?.code ?? null
1622
- }
1623
- }),
1624
- error
1625
- );
1626
- throw error;
1627
- }
1628
- log.info(() => ({
1629
- msg: "rpc call",
1630
- fields: { method, chain, duration_ms: elapsed }
1631
- }));
1632
- return response.result;
1633
- }
1634
- function rpcPath(chain) {
1635
- return `/v1/chains/${encodeURIComponent(chain)}/rpc`;
1636
- }
1637
- async function sendEnvelope(api, url, body) {
1638
- try {
1639
- return await api.send({
1640
- method: "POST",
1641
- url,
1642
- body,
1643
- attributes: Attributes.protected()
1644
- });
1645
- } catch (error) {
1646
- if (error instanceof HttpError && isJsonRpcError(error.response.body)) {
1647
- return error.response.body;
1648
- }
1649
- throw error;
1650
- }
1651
- }
1652
- function isJsonRpcError(body) {
1653
- if (typeof body !== "object" || body === null || !("error" in body)) {
1654
- return false;
1655
- }
1656
- const { error } = body;
1657
- return typeof error === "object" && error !== null && "code" in error && typeof error.code === "number";
1658
- }
1659
-
1660
- // src/universal/core/shared/blockchain/chain.ts
1661
- var import_chains = require("viem/chains");
1662
-
1663
- // src/universal/types/blockchain/ui.ts
1664
- var FormattedAmountAssetUi = (value) => value;
1665
-
1666
- // src/universal/core/shared/blockchain/chain.ts
1667
- var VIEM_CHAINS = {
1668
- ethereum_mainnet: import_chains.mainnet,
1669
- ethereum_sepolia: import_chains.sepolia,
1670
- base_mainnet: import_chains.base,
1671
- base_sepolia: import_chains.baseSepolia
1672
- };
1673
- function viemChain(chain) {
1674
- return VIEM_CHAINS[chain];
1675
- }
1676
- function chainFromId(chainId) {
1677
- const chains = Object.keys(VIEM_CHAINS);
1678
- const chain = chains.find((c) => String(VIEM_CHAINS[c].id) === chainId);
1679
- if (!chain) {
1680
- throw new ValidationError(`Unsupported EIP-155 chain id: "${chainId}"`);
1681
- }
1682
- return chain;
1683
- }
1684
-
1685
- // src/universal/api/rpc/public-clients.ts
1686
- function publicClients(api, config, logger = null) {
1687
- const cache = /* @__PURE__ */ new Map();
1688
- return (chain) => {
1689
- const cached = cache.get(chain);
1690
- if (cached) return cached;
1691
- const client = (0, import_viem3.createPublicClient)({
1692
- chain: viemChain(chain),
1693
- transport: transportFor(api, config?.[chain], chain, logger),
1694
- batch: { multicall: true }
1695
- });
1696
- cache.set(chain, client);
1697
- return client;
1698
- };
1699
- }
1700
- function transportFor(api, override, chain, logger) {
1701
- if (override === void 0) return frontlineTransport(api, chain, logger);
1702
- return typeof override === "string" ? (0, import_viem3.http)(override) : override;
1703
- }
1704
-
1705
- // src/universal/types/providers/coin-list/token-sale.ts
1706
- var ParticipationId = (value) => value;
1707
- var Blockchain = (value) => value;
1708
- var WalletAddress = (value) => value;
1709
- var ParticipationsPaginationParams = {
1710
- toQueryParams: (params) => {
1711
- const queryParams = PaginationParams.toQueryParams(params);
1712
- if (params.offerId) {
1713
- queryParams["filters[0][field]"] = "offer_id";
1714
- queryParams["filters[0][op]"] = "==";
1715
- queryParams["filters[0][value]"] = params.offerId;
1716
- }
1717
- return queryParams;
1718
- }
1719
- };
1720
- var Participation = {
1721
- /** Maps API DTO shape into the SDK participation domain model. */
1722
- fromDto: (dto) => {
1723
- const walletAddress = notBlankStringOrNull(dto.wallet_address);
1724
- return {
1725
- id: ParticipationId(dto.id),
1726
- offerId: OfferId(dto.offer_id),
1727
- offerOptionId: OfferOptionId(dto.offer_option_id),
1728
- status: dto.status,
1729
- amount: dto.amount,
1730
- displayAmount: dto.amount_string,
1731
- asset: Asset.fromDto(dto.asset),
1732
- chain: Blockchain(dto.chain),
1733
- insertedAt: dto.inserted_at ? new Date(dto.inserted_at) : null,
1734
- updatedAt: dto.updated_at ? new Date(dto.updated_at) : null,
1735
- walletAddress: walletAddress ? WalletAddress(walletAddress) : null
1736
- };
1737
- }
1738
- };
1739
- var CreateParticipationParams = {
1740
- /** Maps participation creation params into API DTO payload. */
1741
- toDto: (params) => ({
1742
- offer_id: params.offerId,
1743
- offer_option_id: params.offerOptionId,
1744
- chain: params.chain,
1745
- wallet_address: params.walletAddress,
1746
- amount: params.amount,
1747
- asset_id: params.assetId,
1748
- approval_transaction_hash: params.approvalTransactionHash
1749
- })
1750
- };
1751
-
1752
- // src/universal/api/frontline/providers/coin-list/token-sale.ts
1753
- async function fetchParticipations(api, offerId) {
1754
- return fetchAllPages(
1755
- (params) => fetchParticipationsPage(api, params),
1756
- { offerId }
1757
- );
1758
- }
1759
- async function fetchParticipationsPage(api, params) {
1760
- const pageDto = await api.send({
1761
- method: "GET",
1762
- url: "/v1/participations",
1763
- queryParams: ParticipationsPaginationParams.toQueryParams(params),
1764
- attributes: Attributes.protected()
1765
- });
1766
- return PaginatedResponse.fromDto(pageDto, Participation.fromDto);
1767
- }
1768
- async function fetchParticipation(api, id) {
1769
- const dto = await api.send({
1770
- method: "GET",
1771
- url: `/v1/participations/${id}`,
1772
- attributes: Attributes.protected()
1773
- });
1774
- return Participation.fromDto(dto);
1775
- }
1776
- async function createParticipation(api, params) {
1777
- const dto = await api.send({
1778
- method: "POST",
1779
- url: "/v1/participations",
1780
- body: CreateParticipationParams.toDto(params),
1781
- attributes: Attributes.protected()
1782
- });
1783
- return Participation.fromDto(dto);
1784
- }
1785
-
1786
- // src/universal/core/checkout/coin-list/token-sale-namespace.ts
1787
- var CoinListTokenSaleNamespaceImpl = class {
1788
- constructor(ctx) {
1789
- this.ctx = ctx;
1790
- this.log = internalLogger(ctx.logger, "TOKEN_SALE");
1791
- }
1792
- async list(offerId) {
1793
- return this.log.wrap("list", offerId, async () => {
1794
- await this.ctx.ensureUserAuthenticated();
1795
- return fetchParticipations(this.ctx.api, offerId);
1796
- });
1797
- }
1798
- async listPage(params) {
1799
- return this.log.wrap("listPage", params, async () => {
1800
- await this.ctx.ensureUserAuthenticated();
1801
- return fetchParticipationsPage(this.ctx.api, params);
1802
- });
1803
- }
1804
- async get(id) {
1805
- return this.log.wrap("get", id, async () => {
1806
- await this.ctx.ensureUserAuthenticated();
1807
- return fetchParticipation(this.ctx.api, id);
1808
- });
1809
- }
1810
- async createParticipation(params) {
1811
- return this.log.wrap("createParticipation", params, async () => {
1812
- await this.ctx.ensureUserAuthenticated();
1813
- return createParticipation(this.ctx.api, params);
1814
- });
1815
- }
1816
- };
1817
-
1818
- // src/universal/core/shared/blockchain/formatters.ts
1819
- var import_viem4 = require("viem");
1820
- function formatRawAmount(amount) {
1821
- return (0, import_viem4.formatUnits)(amount.raw, amount.decimals);
1822
- }
1823
- var NA_AMOUNT_ASSET_UI = FormattedAmountAssetUi("-");
1824
- var USD_FRACTION_DIGITS = AssetDecimals(2);
1825
-
1826
- // src/universal/core/shared/blockchain/math.ts
1827
- var import_viem5 = require("viem");
1828
- function blockchainAmountFromRawOrThrow({
1829
- label,
1830
- raw,
1831
- decimals
1832
- }) {
1833
- const trimmed = raw.trim();
1834
- if (trimmed === "") {
1835
- throw new ValidationError(`${label}: not a uint256 integer ("${raw}")`);
1836
- }
1837
- let value;
1838
- try {
1839
- value = BigInt(trimmed);
1840
- } catch {
1841
- throw new ValidationError(`${label}: not a uint256 integer ("${raw}")`);
1842
- }
1843
- try {
1844
- return BlockchainAmount({ raw: assertUint256(value), decimals });
1845
- } catch {
1846
- throw new ValidationError(`${label}: out of uint256 bounds (${value})`);
1847
- }
1848
- }
1849
-
1850
- // src/universal/types/providers/ondo/ondo.ts
1851
- var OndoTradingStatus = {
1852
- fromDto: (dto) => {
1853
- if (!dto.tradable) return { type: "not-tradable", side: dto.side };
1854
- return {
1855
- type: "tradable",
1856
- side: dto.side,
1857
- grossMaxTokens: decimalOrNull(dto.gross_max_tokens),
1858
- grossMaxNotionalValue: decimalOrNull(dto.gross_max_notional_value),
1859
- grossMaxActiveNotionalValue: decimalOrNull(
1860
- dto.gross_max_active_notional_value
1861
- )
1862
- };
1863
- }
1864
- };
1865
- var decimalOrNull = (value) => value === null ? null : DecimalString(value);
1866
- var OndoQuote = {
1867
- fromDto: (dto) => {
1868
- const assetDecimals = AssetDecimals(dto.asset_decimals);
1869
- return {
1870
- chain: chainFromId(dto.chain_id),
1871
- ticker: Ticker(dto.ticker),
1872
- assetAddress: EvmContractAddress(dto.asset_address),
1873
- asset: {
1874
- name: dto.ticker,
1875
- symbol: AssetSymbol(dto.symbol),
1876
- decimals: assetDecimals
1877
- },
1878
- side: dto.side,
1879
- tokenBaseUnits: blockchainAmountFromRawOrThrow({
1880
- label: "tokenBaseUnits",
1881
- raw: dto.token_base_units,
1882
- decimals: assetDecimals
1883
- }),
1884
- price: DecimalString(dto.price)
1885
- };
1886
- }
1887
- };
1888
- var OndoBuyTransaction = {
1889
- fromDto: (dto) => {
1890
- const spendDecimals = AssetDecimals(dto.spend_input_decimals);
1891
- const outputDecimals = AssetDecimals(dto.receive_output_decimals);
1892
- return {
1893
- ...parseSwapCore(dto, spendDecimals),
1894
- side: "buy",
1895
- fee: blockchainAmountFromRawOrThrow({
1896
- label: "fee",
1897
- raw: dto.fee,
1898
- decimals: spendDecimals
1899
- }),
1900
- notionalValue: blockchainAmountFromRawOrThrow({
1901
- label: "notional_value",
1902
- raw: dto.notional_value,
1903
- decimals: spendDecimals
1904
- }),
1905
- receiveOutputAmount: parsePositiveAmount({
1906
- label: "receive_output_amount",
1907
- raw: dto.receive_output_amount,
1908
- decimals: outputDecimals,
1909
- // A transaction that yields nothing is not one to sign - the user
1910
- // would pay the deposit and receive no asset - and frontline refuses
1911
- // to emit one. A zero here is a changed encoding, not a small order.
1912
- // Rejecting it at the boundary is also what lets `computeOndoBuyPrice`
1913
- // divide by it without a fallible result: the failure surfaces as the
1914
- // data hook's ERROR state rather than as a division during render.
1915
- reason: "a buy that yields nothing is not fillable"
1916
- })
1917
- };
1918
- }
1919
- };
1920
- var OndoSellTransaction = {
1921
- fromDto: (dto) => {
1922
- const spendDecimals = AssetDecimals(dto.spend_input_decimals);
1923
- const outputDecimals = AssetDecimals(dto.receive_output_decimals);
1924
- const expectedQuantity = parsePositiveAmount({
1925
- label: "expected_quantity",
1926
- raw: dto.expected_quantity,
1927
- decimals: outputDecimals,
1928
- reason: "a sale that yields nothing is not fillable"
1929
- });
1930
- return {
1931
- ...parseSwapCore(dto, spendDecimals),
1932
- side: "sell",
1933
- expected: {
1934
- quantity: expectedQuantity,
1935
- fee: blockchainAmountFromRawOrThrow({
1936
- label: "expected_fee",
1937
- raw: dto.expected_fee,
1938
- decimals: outputDecimals
1939
- })
1940
- },
1941
- minimum: {
1942
- quantity: parseMinimumQuantity(
1943
- dto.minimum_quantity,
1944
- outputDecimals,
1945
- expectedQuantity
1946
- ),
1947
- fee: blockchainAmountFromRawOrThrow({
1948
- label: "minimum_fee",
1949
- raw: dto.minimum_fee,
1950
- decimals: outputDecimals
1951
- })
1952
- }
1953
- };
1954
- }
1955
- };
1956
- function parseSwapCore(dto, spendDecimals) {
1957
- return {
1958
- tx: {
1959
- to: EvmContractAddress(dto.to),
1960
- data: HexEncodedTransactionData(dto.data)
1961
- },
1962
- expiresAt: parseExpiresAt(dto.expires_at),
1963
- spendInputAmount: parsePositiveAmount({
1964
- label: "spend_input_amount",
1965
- raw: dto.spend_input_amount,
1966
- decimals: spendDecimals,
1967
- // A transaction that takes nothing from the wallet is not one to sign:
1968
- // it would settle one leg of a trade and skip the other. Frontline
1969
- // refuses an `amount` of zero whichever way the trade runs, so this is a
1970
- // changed encoding rather than a small order.
1971
- //
1972
- // Guarded on both sides rather than on the sale alone, because which
1973
- // amount becomes the divisor in the price flips with the direction: a
1974
- // guard placed by that would be a rule about the arithmetic rather than
1975
- // about the trade.
1976
- reason: "a swap that spends nothing is not fillable"
1977
- })
1978
- };
1979
- }
1980
- function parseMinimumQuantity(raw, decimals, expectedQuantity) {
1981
- const amount = parsePositiveAmount({
1982
- label: "minimum_quantity",
1983
- raw,
1984
- decimals,
1985
- reason: "a floor of zero guarantees nothing"
1986
- });
1987
- if (amount.raw > expectedQuantity.raw) {
1988
- throw new ValidationError(
1989
- `minimum_quantity: must not exceed expected_quantity ("${raw}" > "${expectedQuantity.raw}")`
1990
- );
1991
- }
1992
- return amount;
1993
- }
1994
- function parsePositiveAmount({
1995
- label,
1996
- raw,
1997
- decimals,
1998
- reason
1999
- }) {
2000
- const amount = blockchainAmountFromRawOrThrow({ label, raw, decimals });
2001
- if (amount.raw <= 0n) {
2002
- throw new ValidationError(
2003
- `${label}: must be greater than zero ("${raw}") - ${reason}`
2004
- );
2005
- }
2006
- return amount;
2007
- }
2008
- function parseExpiresAt(value) {
2009
- const date = new Date(value);
2010
- if (Number.isNaN(date.getTime())) {
2011
- throw new ValidationError(`expires_at: not a date ("${value}")`);
2012
- }
2013
- return date;
2014
- }
2015
-
2016
- // src/universal/api/frontline/providers/ondo/ondo.ts
2017
- async function getOndoTradingStatus(api, params) {
2018
- const dto = await api.send({
2019
- method: "GET",
2020
- url: "/v1/ondo/swap/trading-status",
2021
- queryParams: { symbol: params.symbol, side: params.side },
2022
- attributes: Attributes.protected()
2023
- });
2024
- return OndoTradingStatus.fromDto(dto);
2025
- }
2026
- async function getOndoQuote(api, params) {
2027
- const dto = await api.send({
2028
- method: "GET",
2029
- url: "/v1/ondo/swap/quote",
2030
- queryParams: {
2031
- symbol: params.symbol,
2032
- side: params.side,
2033
- duration: params.duration,
2034
- ...sizeParam(params)
2035
- },
2036
- attributes: Attributes.protected()
2037
- });
2038
- return OndoQuote.fromDto(dto);
2039
- }
2040
- async function buildOndoBuy(api, params) {
2041
- const dto = await api.send({
2042
- method: "POST",
2043
- url: "/v1/ondo/swap/buy",
2044
- body: swapBody(params),
2045
- attributes: Attributes.protected()
2046
- });
2047
- assertSpendScaleAgrees({
2048
- published: dto.spend_input_decimals,
2049
- sized: params.amount,
2050
- trade: "purchase"
2051
- });
2052
- return OndoBuyTransaction.fromDto(dto);
2053
- }
2054
- async function buildOndoSell(api, params) {
2055
- const dto = await api.send({
2056
- method: "POST",
2057
- url: "/v1/ondo/swap/sell",
2058
- body: swapBody(params),
2059
- attributes: Attributes.protected()
2060
- });
2061
- assertSpendScaleAgrees({
2062
- published: dto.spend_input_decimals,
2063
- sized: params.amount,
2064
- trade: "sale",
2065
- // The two answers come from two chains, so on a testnet they can disagree
2066
- // for a reason that is neither the caller's nor a corrupt response. Say so,
2067
- // or a QA run reads as a puzzle rather than a diagnosis.
2068
- note: "the quote resolves the asset on Ethereum mainnet while the swap executes on the chain requested, so these disagree until frontline serves a chain-scoped quote"
2069
- });
2070
- return OndoSellTransaction.fromDto(dto);
2071
- }
2072
- function swapBody(params) {
2073
- return {
2074
- symbol: params.symbol,
2075
- chain: params.chain,
2076
- wallet_address: params.walletAddress,
2077
- amount: params.amount.raw.toString()
2078
- };
2079
- }
2080
- function assertSpendScaleAgrees({
2081
- published,
2082
- sized,
2083
- trade,
2084
- note
2085
- }) {
2086
- if (published === sized.decimals) return;
2087
- const because = note === void 0 ? "" : ` - ${note}`;
2088
- throw new ValidationError(
2089
- `spend_input_decimals: the ${trade} was priced in ${published} decimals but the order was sized in ${sized.decimals}${because}`
2090
- );
2091
- }
2092
- function sizeParam(params) {
2093
- const tokenAmount = "tokenAmount" in params ? params.tokenAmount : void 0;
2094
- const notionalValue = "notionalValue" in params ? params.notionalValue : void 0;
2095
- if (tokenAmount !== void 0) {
2096
- if (notionalValue !== void 0) {
2097
- throw new ValidationError(
2098
- "An Ondo quote takes tokenAmount or notionalValue, not both"
2099
- );
2100
- }
2101
- return { token_amount: formatRawAmount(tokenAmount) };
2102
- }
2103
- if (notionalValue === void 0) {
2104
- throw new ValidationError(
2105
- "An Ondo quote must be sized by tokenAmount or notionalValue"
2106
- );
2107
- }
2108
- return { notional_value: notionalValue };
2109
- }
2110
-
2111
- // src/universal/core/checkout/ondo/ondo-namespace.ts
2112
- var OndoNamespaceImpl = class {
2113
- constructor(ctx) {
2114
- this.ctx = ctx;
2115
- this.log = internalLogger(ctx.logger, "ONDO");
2116
- }
2117
- async getTradingStatus(params) {
2118
- return this.log.wrap("getTradingStatus", params, async () => {
2119
- await this.ctx.ensureUserAuthenticated();
2120
- return getOndoTradingStatus(this.ctx.api, params);
2121
- });
2122
- }
2123
- async getQuote(params) {
2124
- return this.log.wrap("getQuote", params, async () => {
2125
- await this.ctx.ensureUserAuthenticated();
2126
- return getOndoQuote(this.ctx.api, params);
2127
- });
2128
- }
2129
- async buildBuyTransaction(params) {
2130
- return this.log.wrap("buildBuyTransaction", params, async () => {
2131
- await this.ctx.ensureUserAuthenticated();
2132
- return buildOndoBuy(this.ctx.api, params);
2133
- });
2134
- }
2135
- async buildSellTransaction(params) {
2136
- return this.log.wrap("buildSellTransaction", params, async () => {
2137
- await this.ctx.ensureUserAuthenticated();
2138
- return buildOndoSell(this.ctx.api, params);
2139
- });
2140
- }
2141
- };
2142
-
2143
- // src/universal/types/providers/superstate/swap.ts
2144
- var SwapPreview = {
2145
- /** Maps the contract's `Preview { input, fee, output }` struct. */
2146
- fromContract: (preview) => ({
2147
- inputAmount: parseUint256(preview.input, "SwapPreview.input"),
2148
- fee: parseUint256(preview.fee, "SwapPreview.fee"),
2149
- outputAmount: parseUint256(preview.output, "SwapPreview.output")
2150
- })
2151
- };
2152
- var PauseFlags = (value) => value;
2153
- var SwapStatus = {
2154
- /**
2155
- * Maps the contract's `Status { uint32 flags; State state }` struct, where
2156
- * `State` is `0 = Active | 1 = Paused | 2 = Stopped`.
2157
- *
2158
- * `flags` is carried onto the `paused` arm only. On the other two the
2159
- * contract sets it to a self-identifying marker rather than to information -
2160
- * so repeating it would invite a caller to read meaning into a constant.
2161
- *
2162
- * @throws ValidationError on a `state` outside the enum. A contract that has
2163
- * grown a fourth state is one the SDK does not model, and guessing `active`
2164
- * would let a halted swap read as a live one.
2165
- */
2166
- fromContract: (status) => {
2167
- switch (status.state) {
2168
- case 0:
2169
- return { state: "active" };
2170
- case 1:
2171
- return { state: "paused", pausedLevels: PauseFlags(status.flags) };
2172
- case 2:
2173
- return { state: "stopped" };
2174
- default:
2175
- throw new ValidationError(
2176
- `SwapStatus.state: unknown contract state (${status.state})`
2177
- );
2178
- }
2179
- }
2180
- };
2181
- var AllowWalletResponse = {
2182
- fromDto: (dto) => {
2183
- switch (dto.action) {
2184
- case "broadcast_transaction":
2185
- return {
2186
- action: "broadcast_transaction",
2187
- to: EvmContractAddress(dto.to),
2188
- data: HexEncodedTransactionData(dto.data)
2189
- };
2190
- case "none":
2191
- return {
2192
- action: "none",
2193
- alreadyAllowed: dto.already_allowed
2194
- };
2195
- default: {
2196
- const _exhaustive = dto;
2197
- return _exhaustive;
2198
- }
2199
- }
2200
- }
2201
- };
2202
-
2203
- // src/universal/api/frontline/providers/superstate/swap.ts
2204
- async function allowWallet(api, params) {
2205
- const dto = await api.send({
2206
- method: "POST",
2207
- url: `/v1/offers/${encodeURIComponent(params.offerId)}/allow-wallet`,
2208
- body: {
2209
- wallet_address: params.walletAddress,
2210
- chain: params.chain,
2211
- signature: params.signature
2212
- },
2213
- attributes: Attributes.protected()
2214
- });
2215
- return AllowWalletResponse.fromDto(dto);
2216
- }
2217
-
2218
- // src/universal/core/checkout/superstate/blockchain/abi.ts
2219
- var SUPERSTATE_SWAP_ABI = [
2220
- {
2221
- type: "function",
2222
- name: "KIND",
2223
- inputs: [],
2224
- outputs: [
2225
- {
2226
- name: "",
2227
- type: "uint16",
2228
- internalType: "uint16"
2229
- }
2230
- ],
2231
- stateMutability: "view"
2232
- },
2233
- {
2234
- type: "function",
2235
- name: "ONE_HUNDRED_P",
2236
- inputs: [],
2237
- outputs: [
2238
- {
2239
- name: "",
2240
- type: "uint256",
2241
- internalType: "uint256"
2242
- }
2243
- ],
2244
- stateMutability: "view"
2245
- },
2246
- {
2247
- type: "function",
2248
- name: "SWAP_LEVEL",
2249
- inputs: [],
2250
- outputs: [
2251
- {
2252
- name: "",
2253
- type: "uint32",
2254
- internalType: "uint32"
2255
- }
2256
- ],
2257
- stateMutability: "view"
2258
- },
2259
- {
2260
- type: "function",
2261
- name: "VERSION",
2262
- inputs: [],
2263
- outputs: [
2264
- {
2265
- name: "",
2266
- type: "uint16",
2267
- internalType: "uint16"
2268
- }
2269
- ],
2270
- stateMutability: "view"
2271
- },
2272
- {
2273
- type: "function",
2274
- name: "authorized",
2275
- inputs: [
2276
- {
2277
- name: "user",
2278
- type: "address",
2279
- internalType: "address"
2280
- }
2281
- ],
2282
- outputs: [
2283
- {
2284
- name: "",
2285
- type: "bool",
2286
- internalType: "bool"
2287
- }
2288
- ],
2289
- stateMutability: "view"
2290
- },
2291
- {
2292
- type: "function",
2293
- name: "bpp",
2294
- inputs: [
2295
- {
2296
- name: "amount",
2297
- type: "uint256",
2298
- internalType: "uint256"
2299
- }
2300
- ],
2301
- outputs: [
2302
- {
2303
- name: "",
2304
- type: "uint256",
2305
- internalType: "uint256"
2306
- }
2307
- ],
2308
- stateMutability: "view"
2309
- },
2310
- {
2311
- type: "function",
2312
- name: "bps",
2313
- inputs: [],
2314
- outputs: [
2315
- {
2316
- name: "",
2317
- type: "uint256",
2318
- internalType: "uint256"
2319
- }
2320
- ],
2321
- stateMutability: "view"
2322
- },
2323
- {
2324
- type: "function",
2325
- name: "cancelOwnershipHandover",
2326
- inputs: [],
2327
- outputs: [],
2328
- stateMutability: "payable"
2329
- },
2330
- {
2331
- type: "function",
2332
- name: "completeOwnershipHandover",
2333
- inputs: [
2334
- {
2335
- name: "pendingOwner",
2336
- type: "address",
2337
- internalType: "address"
2338
- }
2339
- ],
2340
- outputs: [],
2341
- stateMutability: "payable"
2342
- },
2343
- {
2344
- type: "function",
2345
- name: "fee",
2346
- inputs: [
2347
- {
2348
- name: "amount",
2349
- type: "uint256",
2350
- internalType: "uint256"
2351
- }
2352
- ],
2353
- outputs: [
2354
- {
2355
- name: "",
2356
- type: "uint256",
2357
- internalType: "uint256"
2358
- },
2359
- {
2360
- name: "",
2361
- type: "uint256",
2362
- internalType: "uint256"
2363
- }
2364
- ],
2365
- stateMutability: "view"
2366
- },
2367
- {
2368
- type: "function",
2369
- name: "id",
2370
- inputs: [],
2371
- outputs: [
2372
- {
2373
- name: "",
2374
- type: "bytes32",
2375
- internalType: "bytes32"
2376
- }
2377
- ],
2378
- stateMutability: "view"
2379
- },
2380
- {
2381
- type: "function",
2382
- name: "inputTokens",
2383
- inputs: [
2384
- {
2385
- name: "",
2386
- type: "address",
2387
- internalType: "address"
2388
- }
2389
- ],
2390
- outputs: [
2391
- {
2392
- name: "",
2393
- type: "bool",
2394
- internalType: "bool"
2395
- }
2396
- ],
2397
- stateMutability: "view"
2398
- },
2399
- {
2400
- type: "function",
2401
- name: "outputToken",
2402
- inputs: [],
2403
- outputs: [
2404
- {
2405
- name: "",
2406
- type: "address",
2407
- internalType: "address"
2408
- }
2409
- ],
2410
- stateMutability: "view"
2411
- },
2412
- {
2413
- type: "function",
2414
- name: "outputTokenBalance",
2415
- inputs: [],
2416
- outputs: [
2417
- {
2418
- name: "",
2419
- type: "uint256",
2420
- internalType: "uint256"
2421
- }
2422
- ],
2423
- stateMutability: "view"
2424
- },
2425
- {
2426
- type: "function",
2427
- name: "owner",
2428
- inputs: [],
2429
- outputs: [
2430
- {
2431
- name: "result",
2432
- type: "address",
2433
- internalType: "address"
2434
- }
2435
- ],
2436
- stateMutability: "view"
2437
- },
2438
- {
2439
- type: "function",
2440
- name: "ownershipHandoverExpiresAt",
2441
- inputs: [
2442
- {
2443
- name: "pendingOwner",
2444
- type: "address",
2445
- internalType: "address"
2446
- }
2447
- ],
2448
- outputs: [
2449
- {
2450
- name: "result",
2451
- type: "uint256",
2452
- internalType: "uint256"
2453
- }
2454
- ],
2455
- stateMutability: "view"
2456
- },
2457
- {
2458
- type: "function",
2459
- name: "pause",
2460
- inputs: [
2461
- {
2462
- name: "level",
2463
- type: "uint32",
2464
- internalType: "uint32"
2465
- }
2466
- ],
2467
- outputs: [
2468
- {
2469
- name: "",
2470
- type: "bool",
2471
- internalType: "bool"
2472
- }
2473
- ],
2474
- stateMutability: "nonpayable"
2475
- },
2476
- {
2477
- type: "function",
2478
- name: "paused",
2479
- inputs: [],
2480
- outputs: [
2481
- {
2482
- name: "",
2483
- type: "uint32",
2484
- internalType: "uint32"
2485
- }
2486
- ],
2487
- stateMutability: "view"
2488
- },
2489
- {
2490
- type: "function",
2491
- name: "preview",
2492
- inputs: [
2493
- {
2494
- name: "token",
2495
- type: "address",
2496
- internalType: "address"
2497
- },
2498
- {
2499
- name: "amount",
2500
- type: "uint256",
2501
- internalType: "uint256"
2502
- }
2503
- ],
2504
- outputs: [
2505
- {
2506
- name: "",
2507
- type: "tuple",
2508
- internalType: "struct Preview",
2509
- components: [
2510
- {
2511
- name: "input",
2512
- type: "uint256",
2513
- internalType: "uint256"
2514
- },
2515
- {
2516
- name: "fee",
2517
- type: "uint256",
2518
- internalType: "uint256"
2519
- },
2520
- {
2521
- name: "output",
2522
- type: "uint256",
2523
- internalType: "uint256"
2524
- }
2525
- ]
2526
- }
2527
- ],
2528
- stateMutability: "view"
2529
- },
2530
- {
2531
- type: "function",
2532
- name: "renounceOwnership",
2533
- inputs: [],
2534
- outputs: [],
2535
- stateMutability: "payable"
2536
- },
2537
- {
2538
- type: "function",
2539
- name: "requestOwnershipHandover",
2540
- inputs: [],
2541
- outputs: [],
2542
- stateMutability: "payable"
2543
- },
2544
- {
2545
- type: "function",
2546
- name: "setBps",
2547
- inputs: [
2548
- {
2549
- name: "points",
2550
- type: "uint256",
2551
- internalType: "uint256"
2552
- }
2553
- ],
2554
- outputs: [
2555
- {
2556
- name: "",
2557
- type: "bool",
2558
- internalType: "bool"
2559
- }
2560
- ],
2561
- stateMutability: "nonpayable"
2562
- },
2563
- {
2564
- type: "function",
2565
- name: "setInputToken",
2566
- inputs: [
2567
- {
2568
- name: "token",
2569
- type: "address",
2570
- internalType: "address"
2571
- },
2572
- {
2573
- name: "val",
2574
- type: "bool",
2575
- internalType: "bool"
2576
- }
2577
- ],
2578
- outputs: [
2579
- {
2580
- name: "",
2581
- type: "bool",
2582
- internalType: "bool"
2583
- }
2584
- ],
2585
- stateMutability: "nonpayable"
2586
- },
2587
- {
2588
- type: "function",
2589
- name: "status",
2590
- inputs: [],
2591
- outputs: [
2592
- {
2593
- name: "",
2594
- type: "tuple",
2595
- internalType: "struct Status",
2596
- components: [
2597
- {
2598
- name: "flags",
2599
- type: "uint32",
2600
- internalType: "uint32"
2601
- },
2602
- {
2603
- name: "state",
2604
- type: "uint8",
2605
- internalType: "enum State"
2606
- }
2607
- ]
2608
- }
2609
- ],
2610
- stateMutability: "view"
2611
- },
2612
- {
2613
- type: "function",
2614
- name: "stop",
2615
- inputs: [],
2616
- outputs: [
2617
- {
2618
- name: "",
2619
- type: "bool",
2620
- internalType: "bool"
2621
- }
2622
- ],
2623
- stateMutability: "nonpayable"
2624
- },
2625
- {
2626
- type: "function",
2627
- name: "stopped",
2628
- inputs: [],
2629
- outputs: [
2630
- {
2631
- name: "",
2632
- type: "bool",
2633
- internalType: "bool"
2634
- }
2635
- ],
2636
- stateMutability: "view"
2637
- },
2638
- {
2639
- type: "function",
2640
- name: "swap",
2641
- inputs: [
2642
- {
2643
- name: "token",
2644
- type: "address",
2645
- internalType: "address"
2646
- },
2647
- {
2648
- name: "amount",
2649
- type: "uint256",
2650
- internalType: "uint256"
2651
- },
2652
- {
2653
- name: "slip",
2654
- type: "uint256",
2655
- internalType: "uint256"
2656
- }
2657
- ],
2658
- outputs: [
2659
- {
2660
- name: "",
2661
- type: "uint256",
2662
- internalType: "uint256"
2663
- }
2664
- ],
2665
- stateMutability: "nonpayable"
2666
- },
2667
- {
2668
- type: "function",
2669
- name: "tokenBalance",
2670
- inputs: [
2671
- {
2672
- name: "token",
2673
- type: "address",
2674
- internalType: "address"
2675
- }
2676
- ],
2677
- outputs: [
2678
- {
2679
- name: "",
2680
- type: "uint256",
2681
- internalType: "uint256"
2682
- }
2683
- ],
2684
- stateMutability: "view"
2685
- },
2686
- {
2687
- type: "function",
2688
- name: "totals",
2689
- inputs: [
2690
- {
2691
- name: "user",
2692
- type: "address",
2693
- internalType: "address"
2694
- },
2695
- {
2696
- name: "token",
2697
- type: "address",
2698
- internalType: "address"
2699
- }
2700
- ],
2701
- outputs: [
2702
- {
2703
- name: "",
2704
- type: "tuple",
2705
- internalType: "struct SwapTotal",
2706
- components: [
2707
- {
2708
- name: "inputSum",
2709
- type: "uint256",
2710
- internalType: "uint256"
2711
- },
2712
- {
2713
- name: "feeSum",
2714
- type: "uint256",
2715
- internalType: "uint256"
2716
- },
2717
- {
2718
- name: "outputSum",
2719
- type: "uint256",
2720
- internalType: "uint256"
2721
- },
2722
- {
2723
- name: "count",
2724
- type: "uint256",
2725
- internalType: "uint256"
2726
- }
2727
- ]
2728
- }
2729
- ],
2730
- stateMutability: "view"
2731
- },
2732
- {
2733
- type: "function",
2734
- name: "totals",
2735
- inputs: [
2736
- {
2737
- name: "token",
2738
- type: "address",
2739
- internalType: "address"
2740
- }
2741
- ],
2742
- outputs: [
2743
- {
2744
- name: "",
2745
- type: "tuple",
2746
- internalType: "struct SwapTotal",
2747
- components: [
2748
- {
2749
- name: "inputSum",
2750
- type: "uint256",
2751
- internalType: "uint256"
2752
- },
2753
- {
2754
- name: "feeSum",
2755
- type: "uint256",
2756
- internalType: "uint256"
2757
- },
2758
- {
2759
- name: "outputSum",
2760
- type: "uint256",
2761
- internalType: "uint256"
2762
- },
2763
- {
2764
- name: "count",
2765
- type: "uint256",
2766
- internalType: "uint256"
2767
- }
2768
- ]
2769
- }
2770
- ],
2771
- stateMutability: "view"
2772
- },
2773
- {
2774
- type: "function",
2775
- name: "transfer",
2776
- inputs: [
2777
- {
2778
- name: "to",
2779
- type: "address",
2780
- internalType: "address"
2781
- },
2782
- {
2783
- name: "amount",
2784
- type: "uint256",
2785
- internalType: "uint256"
2786
- }
2787
- ],
2788
- outputs: [
2789
- {
2790
- name: "",
2791
- type: "bool",
2792
- internalType: "bool"
2793
- }
2794
- ],
2795
- stateMutability: "nonpayable"
2796
- },
2797
- {
2798
- type: "function",
2799
- name: "transfer",
2800
- inputs: [
2801
- {
2802
- name: "to",
2803
- type: "address",
2804
- internalType: "address"
2805
- },
2806
- {
2807
- name: "token",
2808
- type: "address",
2809
- internalType: "address"
2810
- },
2811
- {
2812
- name: "amount",
2813
- type: "uint256",
2814
- internalType: "uint256"
2815
- }
2816
- ],
2817
- outputs: [
2818
- {
2819
- name: "",
2820
- type: "bool",
2821
- internalType: "bool"
2822
- }
2823
- ],
2824
- stateMutability: "nonpayable"
2825
- },
2826
- {
2827
- type: "function",
2828
- name: "transferOwnership",
2829
- inputs: [
2830
- {
2831
- name: "newOwner",
2832
- type: "address",
2833
- internalType: "address"
2834
- }
2835
- ],
2836
- outputs: [],
2837
- stateMutability: "payable"
2838
- },
2839
- {
2840
- type: "event",
2841
- name: "BpsUpdated",
2842
- inputs: [
2843
- {
2844
- name: "prev",
2845
- type: "uint256",
2846
- indexed: false,
2847
- internalType: "uint256"
2848
- },
2849
- {
2850
- name: "next",
2851
- type: "uint256",
2852
- indexed: false,
2853
- internalType: "uint256"
2854
- }
2855
- ],
2856
- anonymous: false
2857
- },
2858
- {
2859
- type: "event",
2860
- name: "InputTokenUpdated",
2861
- inputs: [
2862
- {
2863
- name: "token",
2864
- type: "address",
2865
- indexed: true,
2866
- internalType: "address"
2867
- },
2868
- {
2869
- name: "prev",
2870
- type: "bool",
2871
- indexed: false,
2872
- internalType: "bool"
2873
- },
2874
- {
2875
- name: "next",
2876
- type: "bool",
2877
- indexed: false,
2878
- internalType: "bool"
2879
- }
2880
- ],
2881
- anonymous: false
2882
- },
2883
- {
2884
- type: "event",
2885
- name: "OwnershipHandoverCanceled",
2886
- inputs: [
2887
- {
2888
- name: "pendingOwner",
2889
- type: "address",
2890
- indexed: true,
2891
- internalType: "address"
2892
- }
2893
- ],
2894
- anonymous: false
2895
- },
2896
- {
2897
- type: "event",
2898
- name: "OwnershipHandoverRequested",
2899
- inputs: [
2900
- {
2901
- name: "pendingOwner",
2902
- type: "address",
2903
- indexed: true,
2904
- internalType: "address"
2905
- }
2906
- ],
2907
- anonymous: false
2908
- },
2909
- {
2910
- type: "event",
2911
- name: "OwnershipTransferred",
2912
- inputs: [
2913
- {
2914
- name: "oldOwner",
2915
- type: "address",
2916
- indexed: true,
2917
- internalType: "address"
2918
- },
2919
- {
2920
- name: "newOwner",
2921
- type: "address",
2922
- indexed: true,
2923
- internalType: "address"
2924
- }
2925
- ],
2926
- anonymous: false
2927
- },
2928
- {
2929
- type: "event",
2930
- name: "Paused",
2931
- inputs: [
2932
- {
2933
- name: "previous",
2934
- type: "uint32",
2935
- indexed: false,
2936
- internalType: "uint32"
2937
- },
2938
- {
2939
- name: "next",
2940
- type: "uint32",
2941
- indexed: false,
2942
- internalType: "uint32"
2943
- }
2944
- ],
2945
- anonymous: false
2946
- },
2947
- {
2948
- type: "event",
2949
- name: "Stopped",
2950
- inputs: [],
2951
- anonymous: false
2952
- },
2953
- {
2954
- type: "event",
2955
- name: "Swapped",
2956
- inputs: [
2957
- {
2958
- name: "user",
2959
- type: "address",
2960
- indexed: true,
2961
- internalType: "address"
2962
- },
2963
- {
2964
- name: "inputToken",
2965
- type: "address",
2966
- indexed: true,
2967
- internalType: "address"
2968
- },
2969
- {
2970
- name: "outputToken",
2971
- type: "address",
2972
- indexed: true,
2973
- internalType: "address"
2974
- },
2975
- {
2976
- name: "inputAmount",
2977
- type: "uint256",
2978
- indexed: false,
2979
- internalType: "uint256"
2980
- },
2981
- {
2982
- name: "fee",
2983
- type: "uint256",
2984
- indexed: false,
2985
- internalType: "uint256"
2986
- },
2987
- {
2988
- name: "outputAmount",
2989
- type: "uint256",
2990
- indexed: false,
2991
- internalType: "uint256"
2992
- }
2993
- ],
2994
- anonymous: false
2995
- },
2996
- {
2997
- type: "event",
2998
- name: "Transferred",
2999
- inputs: [
3000
- {
3001
- name: "to",
3002
- type: "address",
3003
- indexed: true,
3004
- internalType: "address"
3005
- },
3006
- {
3007
- name: "token",
3008
- type: "address",
3009
- indexed: true,
3010
- internalType: "address"
3011
- },
3012
- {
3013
- name: "amount",
3014
- type: "uint256",
3015
- indexed: false,
3016
- internalType: "uint256"
3017
- }
3018
- ],
3019
- anonymous: false
3020
- },
3021
- {
3022
- type: "error",
3023
- name: "AlreadyInitialized",
3024
- inputs: []
3025
- },
3026
- {
3027
- type: "error",
3028
- name: "InsufficientAmount",
3029
- inputs: []
3030
- },
3031
- {
3032
- type: "error",
3033
- name: "InvalidAddress",
3034
- inputs: []
3035
- },
3036
- {
3037
- type: "error",
3038
- name: "InvalidAmount",
3039
- inputs: []
3040
- },
3041
- {
3042
- type: "error",
3043
- name: "IsPaused",
3044
- inputs: [
3045
- {
3046
- name: "level",
3047
- type: "uint32",
3048
- internalType: "uint32"
3049
- }
3050
- ]
3051
- },
3052
- {
3053
- type: "error",
3054
- name: "IsStopped",
3055
- inputs: []
3056
- },
3057
- {
3058
- type: "error",
3059
- name: "NewOwnerIsZeroAddress",
3060
- inputs: []
3061
- },
3062
- {
3063
- type: "error",
3064
- name: "NoHandoverRequest",
3065
- inputs: []
3066
- },
3067
- {
3068
- type: "error",
3069
- name: "SwapFailed",
3070
- inputs: [
3071
- {
3072
- name: "user",
3073
- type: "address",
3074
- internalType: "address"
3075
- },
3076
- {
3077
- name: "token",
3078
- type: "address",
3079
- internalType: "address"
3080
- }
3081
- ]
3082
- },
3083
- {
3084
- type: "error",
3085
- name: "Unauthorized",
3086
- inputs: []
3087
- }
3088
- ];
3089
-
3090
- // src/universal/core/shared/blockchain/erc20/abi.ts
3091
- var ERC20_ABI = [
3092
- {
3093
- type: "function",
3094
- name: "allowance",
3095
- inputs: [
3096
- { name: "owner", type: "address" },
3097
- { name: "spender", type: "address" }
3098
- ],
3099
- outputs: [{ name: "", type: "uint256" }],
3100
- stateMutability: "view"
3101
- },
3102
- {
3103
- type: "function",
3104
- name: "approve",
3105
- inputs: [
3106
- { name: "spender", type: "address" },
3107
- { name: "amount", type: "uint256" }
3108
- ],
3109
- outputs: [{ name: "", type: "bool" }],
3110
- stateMutability: "nonpayable"
3111
- },
3112
- {
3113
- type: "function",
3114
- name: "balanceOf",
3115
- inputs: [{ name: "account", type: "address" }],
3116
- outputs: [{ name: "", type: "uint256" }],
3117
- stateMutability: "view"
3118
- },
3119
- {
3120
- type: "function",
3121
- name: "decimals",
3122
- inputs: [],
3123
- outputs: [{ name: "", type: "uint8" }],
3124
- stateMutability: "view"
3125
- },
3126
- {
3127
- type: "function",
3128
- name: "name",
3129
- inputs: [],
3130
- outputs: [{ name: "", type: "string" }],
3131
- stateMutability: "view"
3132
- },
3133
- {
3134
- type: "function",
3135
- name: "symbol",
3136
- inputs: [],
3137
- outputs: [{ name: "", type: "string" }],
3138
- stateMutability: "view"
3139
- },
3140
- {
3141
- type: "function",
3142
- name: "totalSupply",
3143
- inputs: [],
3144
- outputs: [{ name: "", type: "uint256" }],
3145
- stateMutability: "view"
3146
- },
3147
- {
3148
- type: "function",
3149
- name: "transfer",
3150
- inputs: [
3151
- { name: "recipient", type: "address" },
3152
- { name: "amount", type: "uint256" }
3153
- ],
3154
- outputs: [{ name: "", type: "bool" }],
3155
- stateMutability: "nonpayable"
3156
- },
3157
- {
3158
- type: "function",
3159
- name: "transferFrom",
3160
- inputs: [
3161
- { name: "sender", type: "address" },
3162
- { name: "recipient", type: "address" },
3163
- { name: "amount", type: "uint256" }
3164
- ],
3165
- outputs: [{ name: "", type: "bool" }],
3166
- stateMutability: "nonpayable"
3167
- },
3168
- {
3169
- type: "event",
3170
- name: "Approval",
3171
- inputs: [
3172
- { name: "owner", type: "address", indexed: true },
3173
- { name: "spender", type: "address", indexed: true },
3174
- { name: "value", type: "uint256", indexed: false }
3175
- ],
3176
- anonymous: false
3177
- },
3178
- {
3179
- type: "event",
3180
- name: "Transfer",
3181
- inputs: [
3182
- { name: "from", type: "address", indexed: true },
3183
- { name: "to", type: "address", indexed: true },
3184
- { name: "value", type: "uint256", indexed: false }
3185
- ],
3186
- anonymous: false
3187
- }
3188
- ];
3189
-
3190
- // src/universal/api/rpc/providers/superstate/swap.ts
3191
- async function getSwapAuthorization(clients, params) {
3192
- return clients(params.chain).readContract({
3193
- address: params.contractAddress,
3194
- abi: SUPERSTATE_SWAP_ABI,
3195
- functionName: "authorized",
3196
- args: [params.walletAddress]
3197
- });
3198
- }
3199
- async function getSwapPreview(clients, params) {
3200
- const preview = await clients(params.chain).readContract({
3201
- address: params.contractAddress,
3202
- abi: SUPERSTATE_SWAP_ABI,
3203
- functionName: "preview",
3204
- args: [params.inputToken, params.amount]
3205
- });
3206
- return SwapPreview.fromContract(preview);
3207
- }
3208
- async function getSwapStatus(clients, params) {
3209
- const status = await clients(params.chain).readContract({
3210
- address: params.contractAddress,
3211
- abi: SUPERSTATE_SWAP_ABI,
3212
- functionName: "status"
3213
- });
3214
- return SwapStatus.fromContract(status);
3215
- }
3216
- async function getSwapOutputToken(clients, params) {
3217
- const client = clients(params.chain);
3218
- const tokenAddress = await client.readContract({
3219
- address: params.contractAddress,
3220
- abi: SUPERSTATE_SWAP_ABI,
3221
- functionName: "outputToken"
3222
- });
3223
- const token = { address: EvmContractAddress(tokenAddress), abi: ERC20_ABI };
3224
- const [name, symbol, decimals] = await client.multicall({
3225
- contracts: [
3226
- { ...token, functionName: "name" },
3227
- { ...token, functionName: "symbol" },
3228
- { ...token, functionName: "decimals" }
3229
- ],
3230
- allowFailure: false
3231
- });
3232
- return {
3233
- name,
3234
- symbol: AssetSymbol(symbol),
3235
- decimals: AssetDecimals(decimals)
3236
- };
3237
- }
3238
-
3239
- // src/universal/core/checkout/superstate/swap-namespace.ts
3240
- var SuperstateSwapNamespaceImpl = class {
3241
- constructor(ctx) {
3242
- this.ctx = ctx;
3243
- this.log = internalLogger(ctx.logger, "SUPERSTATE");
3244
- }
3245
- async getAuthorization(params) {
3246
- return this.log.wrap(
3247
- "getAuthorization",
3248
- params,
3249
- async () => getSwapAuthorization(this.ctx.rpc, params)
3250
- );
3251
- }
3252
- async getPreview(params) {
3253
- return this.log.wrap(
3254
- "getPreview",
3255
- params,
3256
- async () => getSwapPreview(this.ctx.rpc, params)
3257
- );
3258
- }
3259
- async getStatus(params) {
3260
- return this.log.wrap(
3261
- "getStatus",
3262
- params,
3263
- async () => getSwapStatus(this.ctx.rpc, params)
3264
- );
3265
- }
3266
- async getOutputToken(params) {
3267
- return this.log.wrap(
3268
- "getOutputToken",
3269
- params,
3270
- async () => getSwapOutputToken(this.ctx.rpc, params)
3271
- );
3272
- }
3273
- async allowWallet(params) {
3274
- return this.log.wrap("allowWallet", params, async () => {
3275
- await this.ctx.ensureUserAuthenticated();
3276
- return allowWallet(this.ctx.api, params);
3277
- });
3278
- }
3279
- };
3280
-
3281
- // src/universal/api/rpc/erc20.ts
3282
- async function getTokenAllowance(clients, params) {
3283
- const allowance = await clients(params.chain).readContract({
3284
- address: params.tokenAddress,
3285
- abi: ERC20_ABI,
3286
- functionName: "allowance",
3287
- args: [params.owner, params.spender]
3288
- });
3289
- return parseUint256(allowance, "allowance");
3290
- }
3291
- async function getTokenBalance(clients, params) {
3292
- const balance = await clients(params.chain).readContract({
3293
- address: params.tokenAddress,
3294
- abi: ERC20_ABI,
3295
- functionName: "balanceOf",
3296
- args: [params.owner]
3297
- });
3298
- return parseUint256(balance, "balanceOf");
3299
- }
3300
-
3301
- // src/universal/core/shared/blockchain/erc20/erc20-namespace.ts
3302
- var Erc20NamespaceImpl = class {
3303
- constructor(ctx) {
3304
- this.ctx = ctx;
3305
- this.log = internalLogger(ctx.logger, "ERC20");
3306
- }
3307
- async getAllowance(params) {
3308
- return this.log.wrap(
3309
- "getAllowance",
3310
- params,
3311
- async () => getTokenAllowance(this.ctx.rpc, params)
3312
- );
3313
- }
3314
- async getBalance(params) {
3315
- return this.log.wrap(
3316
- "getBalance",
3317
- params,
3318
- async () => getTokenBalance(this.ctx.rpc, params)
3319
- );
3320
- }
3321
- };
3322
-
3323
- // src/universal/api/nabu/tokens.ts
3324
- var import_viem6 = require("viem");
3325
-
3326
- // src/universal/types/token-metadata.ts
3327
- var TokenLogoUrl = (value) => value;
3328
- var TokenLogo = {
3329
- /** `baseUrl` is the registry origin; registry URLs are root-relative. */
3330
- fromDto: (dto, baseUrl) => dto.kind === "VECTOR" ? { kind: "VECTOR", url: resolveLogoUrl(dto.url, baseUrl) } : {
3331
- kind: "RASTER",
3332
- original: logoImageFromDto(dto.original, baseUrl),
3333
- variants: dto.variants.map((v) => logoImageFromDto(v, baseUrl))
3334
- }
3335
- };
3336
- var TokenMetadata = {
3337
- /** `baseUrl` is the registry origin; registry logo URLs are root-relative. */
3338
- fromDto: (dto, baseUrl) => {
3339
- assertSupportedSchemaVersion(dto.schema_version);
3340
- return {
3341
- identifier: {
3342
- chain: EthereumChain(dto.chain),
3343
- address: EvmContractAddress(dto.address)
3344
- },
3345
- name: dto.name,
3346
- symbol: AssetSymbol(dto.symbol),
3347
- decimals: AssetDecimals(dto.decimals),
3348
- logo: TokenLogo.fromDto(dto.logo, baseUrl),
3349
- logoDark: dto.logo_dark === void 0 ? null : TokenLogo.fromDto(dto.logo_dark, baseUrl)
3350
- };
3351
- },
3352
- /**
3353
- * Maps the complete registry snapshot to every token it lists across the
3354
- * chains this SDK models, skipping native coins and chains outside
3355
- * {@link EthereumChain} (e.g. Solana) rather than failing on them — the
3356
- * registry may serve chains ahead of the SDK's type surface.
3357
- */
3358
- fromRegistryDto: (dto, baseUrl) => {
3359
- assertSupportedSchemaVersion(dto.schema_version);
3360
- return dto.chains.flatMap((chainDto) => {
3361
- let chain;
3362
- try {
3363
- chain = EthereumChain(chainDto.chain);
3364
- } catch {
3365
- return [];
3366
- }
3367
- return tokensOfChain(chain, chainDto.assets, baseUrl);
3368
- });
3369
- },
3370
- /**
3371
- * Maps a chain snapshot to the tokens it lists, skipping the chain's native
3372
- * coin (`kind: 'COIN'`, no contract address).
3373
- */
3374
- fromChainAssetsDto: (dto, baseUrl) => {
3375
- assertSupportedSchemaVersion(dto.schema_version);
3376
- return tokensOfChain(EthereumChain(dto.chain), dto.assets, baseUrl);
3377
- }
3378
- };
3379
- function tokensOfChain(chain, assets, baseUrl) {
3380
- return assets.filter((asset) => asset.kind === "TOKEN" && asset.address !== void 0).map((asset) => ({
3381
- identifier: {
3382
- chain,
3383
- // The filter above cannot narrow `address` for the type checker.
3384
- address: EvmContractAddress(asset.address)
3385
- },
3386
- name: asset.name,
3387
- symbol: AssetSymbol(asset.symbol),
3388
- decimals: AssetDecimals(asset.decimals),
3389
- logo: TokenLogo.fromDto(asset.logo, baseUrl),
3390
- logoDark: asset.logo_dark === void 0 ? null : TokenLogo.fromDto(asset.logo_dark, baseUrl)
3391
- }));
3392
- }
3393
- function assertSupportedSchemaVersion(version) {
3394
- if (version !== 1) {
3395
- throw new ValidationError(
3396
- `Unsupported token registry schema_version: ${version}`
3397
- );
3398
- }
3399
- }
3400
- var logoImageFromDto = (dto, baseUrl) => ({
3401
- url: resolveLogoUrl(dto.url, baseUrl),
3402
- width: dto.width,
3403
- height: dto.height
3404
- });
3405
- var resolveLogoUrl = (url, baseUrl) => TokenLogoUrl(
3406
- url.startsWith("http") ? url : `${baseUrl.replace(/\/$/, "")}${url}`
3407
- );
3408
-
3409
- // src/universal/api/nabu/tokens.ts
3410
- function createNabuApiClient(baseUrl, logger = null) {
3411
- return new HttpClient({ baseUrl }, {}, logger);
3412
- }
3413
- async function fetchTokenMetadata(client, token) {
3414
- const address = checksummed(token.address);
3415
- let response;
3416
- try {
3417
- response = await client.send({
3418
- method: "GET",
3419
- url: `/${token.chain}/token/${address}`
3420
- });
3421
- } catch (error) {
3422
- if (isRegistryHtmlFallback(error)) {
3423
- return null;
3424
- }
3425
- throw error;
3426
- }
3427
- if (response.status === 404) {
3428
- return null;
3429
- }
3430
- assertOk(response);
3431
- if (response.body === null) {
3432
- throw new ValidationError(
3433
- `Token registry returned an empty body for token "${address}" on "${token.chain}"`
3434
- );
3435
- }
3436
- return TokenMetadata.fromDto(response.body, client.config.baseUrl);
3437
- }
3438
- async function fetchTokensMetadata(client, chain) {
3439
- let response;
3440
- try {
3441
- response = await client.send({
3442
- method: "GET",
3443
- url: `/${chain}/assets.json`
3444
- });
3445
- } catch (error) {
3446
- if (isRegistryHtmlFallback(error)) {
3447
- throw new ValidationError(
3448
- `Token registry returned non-JSON for the "${chain}" snapshot`
3449
- );
3450
- }
3451
- throw error;
3452
- }
3453
- assertOk(response);
3454
- if (response.body === null) {
3455
- throw new ValidationError(
3456
- `Token registry returned an empty "${chain}" snapshot`
3457
- );
3458
- }
3459
- return TokenMetadata.fromChainAssetsDto(response.body, client.config.baseUrl);
3460
- }
3461
- async function fetchAllTokensMetadata(client) {
3462
- let response;
3463
- try {
3464
- response = await client.send({
3465
- method: "GET",
3466
- url: `/assets.json`
3467
- });
3468
- } catch (error) {
3469
- if (isRegistryHtmlFallback(error)) {
3470
- throw new ValidationError(
3471
- "Token registry returned non-JSON for the complete snapshot"
3472
- );
3473
- }
3474
- throw error;
3475
- }
3476
- assertOk(response);
3477
- if (response.body === null) {
3478
- throw new ValidationError(
3479
- "Token registry returned an empty complete snapshot"
3480
- );
3481
- }
3482
- return TokenMetadata.fromRegistryDto(response.body, client.config.baseUrl);
3483
- }
3484
- function isRegistryHtmlFallback(error) {
3485
- return error instanceof HttpError && error.response.status >= 200 && error.response.status < 300;
3486
- }
3487
- function assertOk(response) {
3488
- if (response.status < 200 || response.status >= 300) {
3489
- throw new HttpError(response);
3490
- }
3491
- }
3492
- function checksummed(address) {
3493
- try {
3494
- return (0, import_viem6.getAddress)(address);
3495
- } catch (_) {
3496
- throw new ValidationError(`Invalid EVM contract address: "${address}"`);
3497
- }
3498
- }
3499
-
3500
- // src/universal/core/tokens/tokens-namespace.ts
3501
- var TokensNamespaceImpl = class {
3502
- /**
3503
- * Takes the registry origin rather than a `UniversalNamespaceContext`: the
3504
- * registry is unauthenticated and on its own host, so the frontline sender
3505
- * and the auth check would both be dead weight here.
3506
- */
3507
- constructor(baseUrl, logger = null) {
3508
- this.api = createNabuApiClient(baseUrl, logger);
3509
- this.log = internalLogger(logger, "TOKENS");
3510
- }
3511
- get(token) {
3512
- return this.log.wrap(
3513
- "get",
3514
- token,
3515
- () => fetchTokenMetadata(this.api, token)
3516
- );
3517
- }
3518
- list(chain) {
3519
- return this.log.wrap(
3520
- "list",
3521
- chain,
3522
- () => chain === void 0 ? fetchAllTokensMetadata(this.api) : fetchTokensMetadata(this.api, chain)
3523
- );
3524
- }
3525
- };
3526
-
3527
- // src/universal/types/offer-option-address.ts
3528
- var OfferOptionAddressId = (value) => value;
3529
- var OfferOptionAddress = {
3530
- /** Maps the API DTO into the SDK offer-option-address domain model. */
3531
- fromDto: (dto) => ({
3532
- id: OfferOptionAddressId(dto.id),
3533
- offerOptionId: OfferOptionId(dto.offer_option_id),
3534
- address: EvmWalletAddress(dto.address),
3535
- protocol: dto.protocol,
3536
- createdAt: new Date(dto.created_at)
3537
- })
3538
- };
3539
- var ConnectExternalWalletParams = {
3540
- /** Maps connect-wallet params into the API DTO payload. */
3541
- toDto: (params) => ({
3542
- offer_option_id: params.offerOptionId,
3543
- wallet_address: params.walletAddress,
3544
- chain: params.chain,
3545
- signature: params.signature
3546
- })
3547
- };
3548
-
3549
- // src/universal/types/wallet-ownership-challenge.ts
3550
- var WalletOwnershipChallenge = {
3551
- /** Maps the API DTO into the SDK wallet-ownership-challenge domain model. */
3552
- fromDto: (dto) => ({
3553
- message: dto.message,
3554
- expiresAt: new Date(dto.expires_at)
3555
- })
3556
- };
3557
- var CreateWalletOwnershipChallengeParams = {
3558
- /**
3559
- * Maps challenge-request params into the API DTO payload. The discriminated
3560
- * union guarantees SIWE fields are present exactly when `challengeType` is
3561
- * `siwe`, so the mapping narrows on the discriminant.
3562
- */
3563
- toDto: (params) => {
3564
- switch (params.challengeType) {
3565
- case "plain":
3566
- return {
3567
- wallet_address: params.walletAddress,
3568
- chain: params.chain,
3569
- challenge_type: "plain"
3570
- };
3571
- case "siwe":
3572
- return {
3573
- wallet_address: params.walletAddress,
3574
- chain: params.chain,
3575
- challenge_type: "siwe",
3576
- domain: params.domain,
3577
- uri: params.uri,
3578
- statement: params.statement
3579
- };
3580
- default: {
3581
- const _exhaustive = params;
3582
- return _exhaustive;
3583
- }
3584
- }
3585
- }
3586
- };
3587
-
3588
- // src/universal/api/frontline/wallet-connect.ts
3589
- async function createWalletOwnershipChallenge(api, params) {
3590
- const dto = await api.send({
3591
- method: "POST",
3592
- url: "/v1/wallet-ownership",
3593
- body: CreateWalletOwnershipChallengeParams.toDto(params),
3594
- attributes: Attributes.protected()
3595
- });
3596
- return WalletOwnershipChallenge.fromDto(dto);
3597
- }
3598
- async function connectExternalWallet(api, params) {
3599
- const dto = await api.send({
3600
- method: "POST",
3601
- url: `/v1/offers/${params.offerId}/addresses`,
3602
- body: ConnectExternalWalletParams.toDto(params),
3603
- attributes: Attributes.protected()
3604
- });
3605
- return OfferOptionAddress.fromDto(dto);
3606
- }
3607
- async function listOptionAddresses(api, offerId, offerOptionId) {
3608
- const { data } = await api.send({
3609
- method: "GET",
3610
- url: `/v1/offers/${offerId}/addresses`,
3611
- queryParams: { offer_option_id: offerOptionId },
3612
- attributes: Attributes.protected()
3613
- });
3614
- return data.map(OfferOptionAddress.fromDto);
3615
- }
3616
- async function removeOptionAddress(api, offerId, addressId) {
3617
- const dto = await api.send({
3618
- method: "DELETE",
3619
- url: `/v1/offers/${offerId}/addresses/${addressId}`,
3620
- attributes: Attributes.protected()
3621
- });
3622
- return OfferOptionAddress.fromDto(dto);
3623
- }
3624
-
3625
- // src/universal/core/wallets/wallets-namespace.ts
3626
- var WalletsNamespaceImpl = class {
3627
- constructor(ctx) {
3628
- this.ctx = ctx;
3629
- this.log = internalLogger(ctx.logger, "WALLETS");
3630
- }
3631
- async createOwnershipChallenge(params) {
3632
- return this.log.wrap("createOwnershipChallenge", params, async () => {
3633
- await this.ctx.ensureUserAuthenticated();
3634
- return createWalletOwnershipChallenge(
3635
- this.ctx.api,
3636
- params
3637
- );
3638
- });
3639
- }
3640
- async connectExternal(params) {
3641
- return this.log.wrap("connectExternal", params, async () => {
3642
- await this.ctx.ensureUserAuthenticated();
3643
- return connectExternalWallet(this.ctx.api, params);
3644
- });
3645
- }
3646
- async list(params) {
3647
- return this.log.wrap("list", params, async () => {
3648
- await this.ctx.ensureUserAuthenticated();
3649
- return listOptionAddresses(
3650
- this.ctx.api,
3651
- params.offerId,
3652
- params.offerOptionId
3653
- );
3654
- });
3655
- }
3656
- async remove(params) {
3657
- return this.log.wrap("remove", params, async () => {
3658
- await this.ctx.ensureUserAuthenticated();
3659
- return removeOptionAddress(
3660
- this.ctx.api,
3661
- params.offerId,
3662
- params.addressId
3663
- );
3664
- });
3665
- }
3666
- };
3667
-
3668
- // src/server/core/coinlist-server.ts
3669
- var ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS = 60;
3670
- var CoinListServerImpl = class {
3671
- constructor(_config) {
3672
- this._config = _config;
3673
- const logger = _config.logger ?? null;
3674
- this.api = new ApiClient(
3675
- {
3676
- baseUrl: _config.baseUrl ?? PUBLIC_API_BASE_URL,
3677
- xApiVersion: API_VERSION
3678
- },
3679
- // When refresh=true the renewal middleware has received a 401 and wants a
3680
- // fresh token. A read-only store cannot persist a new session, so return
3681
- // null immediately — this tells the middleware to skip the retry rather
3682
- // than re-sending with the same expired token and wasting a round-trip.
3683
- (refresh) => refresh && !this._config.sessionStore.setSession ? Promise.resolve(null) : this.auth.getAccessToken(),
3684
- logger
3685
- );
3686
- this.auth = new ServerAuthNamespaceImpl(this.api, {
3687
- ..._config,
3688
- accessTokenExpiryBufferSeconds: _config.accessTokenExpiryBufferSeconds ?? ACCESS_TOKEN_EXPIRY_BUFFER_SECONDS,
3689
- strict: _config.strict ?? false
3690
- });
3691
- const ctx = {
3692
- api: this.api,
3693
- rpc: publicClients(this.api, _config.rpc, _config.logger ?? null),
3694
- logger,
3695
- ensureUserAuthenticated: () => this.ensureAuthenticated(void 0),
3696
- ensureAuthenticated: (clientCreds) => this.ensureAuthenticated(clientCreds)
3697
- };
3698
- this.offers = new ServerOffersNamespaceImpl(ctx);
3699
- this.requirements = new ServerRequirementsNamespaceImpl(ctx);
3700
- this.wallets = new WalletsNamespaceImpl(ctx);
3701
- this.erc20 = new Erc20NamespaceImpl(ctx);
3702
- this.tokenSale = new CoinListTokenSaleNamespaceImpl(ctx);
3703
- this.superstate = new SuperstateSwapNamespaceImpl(ctx);
3704
- this.ondo = new OndoNamespaceImpl(ctx);
3705
- this.tokens = new TokensNamespaceImpl(
3706
- _config.tokensBaseUrl ?? NABU_BASE_URL,
3707
- logger
3708
- );
3709
- }
3710
- /**
3711
- * An app-level token authenticates a request on its own; without one the
3712
- * caller needs a user session.
3713
- */
3714
- async ensureAuthenticated(clientCreds) {
3715
- if (clientCreds) return;
3716
- const token = await this.auth.getAccessToken();
3717
- if (token === null) {
3718
- throw new NotAuthenticatedError();
3719
- }
3720
- }
3721
- };
3722
- function createCoinListServer(config) {
3723
- return new CoinListServerImpl(config);
3724
- }
3725
-
3726
- // src/server/core/observability/pino-server-logger.ts
3727
- var import_pino = require("pino");
3728
-
3729
- // src/universal/core/shared/observability/pino-logger.ts
3730
- function toPinoRecord(event) {
3731
- try {
3732
- const record = {};
3733
- for (const key of ownKeys(event.fields)) {
3734
- record[key] = readProperty(event.fields, key, 0, /* @__PURE__ */ new WeakSet());
3735
- }
3736
- const cause = "cause" in event ? event.cause : void 0;
3737
- if (cause !== void 0) {
3738
- record.cause = sanitize(cause, 0, /* @__PURE__ */ new WeakSet());
3739
- }
3740
- return { ...record, scope: event.scope, ...event.bindings };
3741
- } catch (_) {
3742
- return { "log.render": "<unrenderable event>" };
3743
- }
3744
- }
3745
- var PINO_LEVEL = {
3746
- none: "silent",
3747
- error: "error",
3748
- warn: "warn",
3749
- info: "info",
3750
- debug: "debug"
3751
- };
3752
- var MAX_DEPTH = 8;
3753
- function sanitize(value, depth, seen) {
3754
- switch (typeof value) {
3755
- case "string":
3756
- case "boolean":
3757
- return value;
3758
- case "number":
3759
- return Number.isFinite(value) ? value : String(value);
3760
- case "bigint":
3761
- return value.toString();
3762
- case "undefined":
3763
- return "<undefined>";
3764
- case "function":
3765
- return "<function>";
3766
- case "symbol":
3767
- return value.toString();
3768
- case "object":
3769
- return value === null ? null : sanitizeObject(value, depth, seen);
3770
- default:
3771
- return "<unrenderable>";
3772
- }
3773
- }
3774
- function sanitizeObject(value, depth, seen) {
3775
- if (seen.has(value)) return "<circular>";
3776
- if (depth >= MAX_DEPTH) return "<max depth>";
3777
- if (value instanceof Error) return describeError(value);
3778
- if (value instanceof Date) return describeDate(value);
3779
- seen.add(value);
3780
- try {
3781
- if (Array.isArray(value)) {
3782
- return value.map(
3783
- (_item, index) => readProperty(value, String(index), depth, seen)
3784
- );
3785
- }
3786
- const out = {};
3787
- for (const key of ownKeys(value)) {
3788
- out[key] = readProperty(value, key, depth, seen);
3789
- }
3790
- return out;
3791
- } finally {
3792
- seen.delete(value);
3793
- }
3794
- }
3795
- function readProperty(owner, key, depth, seen) {
3796
- try {
3797
- return sanitize(owner[key], depth + 1, seen);
3798
- } catch (_) {
3799
- return "<unreadable>";
3800
- }
3801
- }
3802
- function ownKeys(value) {
3803
- try {
3804
- return Object.keys(value);
3805
- } catch (_) {
3806
- return [];
3807
- }
3808
- }
3809
- function describeError(error) {
3810
- return {
3811
- name: safeRead(() => error.name),
3812
- message: safeRead(() => error.message),
3813
- stack: safeRead(() => error.stack)
3814
- };
3815
- }
3816
- function describeDate(date) {
3817
- return safeRead(() => date.toISOString());
3818
- }
3819
- function safeRead(read) {
3820
- try {
3821
- const value = read();
3822
- return typeof value === "string" ? value : "<unreadable>";
3823
- } catch (_) {
3824
- return "<unreadable>";
3825
- }
3826
- }
3827
- var SDK_LOGGER_NAME = "@coinlist-co/react";
3828
- function loggerOverPino(sink, level) {
3829
- return {
3830
- level: () => level,
3831
- debug: (event) => emit(sink, "debug", event),
3832
- info: (event) => emit(sink, "info", event),
3833
- warn: (event) => emit(sink, "warn", event),
3834
- error: (event) => emit(sink, "error", event)
3835
- };
3836
- }
3837
- function emit(sink, method, event) {
3838
- try {
3839
- const value = event();
3840
- sink[method](toPinoRecord(value), value.msg);
3841
- } catch (error) {
3842
- reportRenderFailure(sink, error);
3843
- }
3844
- }
3845
- function reportRenderFailure(sink, error) {
3846
- try {
3847
- sink.error(
3848
- { "error.type": error instanceof Error ? error.name : typeof error },
3849
- "log event failed to render"
3850
- );
3851
- } catch (_) {
3852
- }
3853
- }
3854
-
3855
- // src/server/core/observability/pino-server-logger.ts
3856
- function pinoServerLogger(options) {
3857
- return loggerOverPino(
3858
- // `name` as a child binding rather than pino's `name` option: the option
3859
- // is honoured by pino's node build and silently dropped by its browser
3860
- // build, so a binding is the only spelling that identifies the SDK in
3861
- // both environments.
3862
- (0, import_pino.pino)({
3863
- level: PINO_LEVEL[options.level]
3864
- }).child({ name: SDK_LOGGER_NAME }),
3865
- options.level
3866
- );
3867
- }
3868
- // Annotate the CommonJS export names for ESM import in node:
3869
- 0 && (module.exports = {
3870
- ServerAuthNamespaceImpl,
3871
- ServerOffersNamespaceImpl,
3872
- ServerRequirementsNamespaceImpl,
3873
- WritableSessionStoreRequiredError,
3874
- createCoinListServer,
3875
- emptySessionStore,
3876
- pinoServerLogger
3877
- });
3878
- //# sourceMappingURL=index.cjs.map