@coinlist-co/react 0.12.2-rc.8a0d02a → 0.12.2-rc.99b1bd5

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-IZJ4JSSC.js → chunk-IQAJ3L25.js} +173 -253
  3. package/dist/chunk-IQAJ3L25.js.map +1 -0
  4. package/dist/{chunk-3WW5FLT7.js → chunk-J45AY2FX.js} +10 -10
  5. package/dist/chunk-J45AY2FX.js.map +1 -0
  6. package/dist/{chunk-C6GF7MDF.js → chunk-M2TURNJH.js} +876 -800
  7. package/dist/chunk-M2TURNJH.js.map +1 -0
  8. package/dist/chunk-MJ6YXZWH.js +22 -0
  9. package/dist/chunk-MJ6YXZWH.js.map +1 -0
  10. package/dist/client/index.d.ts +2836 -5619
  11. package/dist/client/index.js +7157 -8250
  12. package/dist/client/index.js.map +1 -1
  13. package/dist/server/index.d.ts +2 -32
  14. package/dist/server/index.js +6 -4
  15. package/dist/server/index.js.map +1 -1
  16. package/dist/{time-CVZpAkGY.d.cts → time-DkU7jivQ.d.ts} +1907 -3185
  17. package/dist/{token-registry-snapshot-BkwA8KmD.d.ts → token-registry-snapshot-D0OWXMe4.d.ts} +22 -58
  18. package/dist/universal/index.d.ts +81 -1067
  19. package/dist/universal/index.js +22 -46
  20. package/package.json +18 -14
  21. package/dist/chunk-3WW5FLT7.js.map +0 -1
  22. package/dist/chunk-C6GF7MDF.js.map +0 -1
  23. package/dist/chunk-IZJ4JSSC.js.map +0 -1
  24. package/dist/client/index.cjs +0 -20460
  25. package/dist/client/index.cjs.map +0 -1
  26. package/dist/client/index.d.cts +0 -8195
  27. package/dist/server/index.cjs +0 -4525
  28. package/dist/server/index.cjs.map +0 -1
  29. package/dist/server/index.d.cts +0 -382
  30. package/dist/time-CVZpAkGY.d.ts +0 -3987
  31. package/dist/token-registry-snapshot-bR14QehS.d.cts +0 -245
  32. package/dist/universal/index.cjs +0 -4562
  33. package/dist/universal/index.cjs.map +0 -1
  34. package/dist/universal/index.d.cts +0 -1362
@@ -1,4562 +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/universal/index.ts
21
- var universal_exports = {};
22
- __export(universal_exports, {
23
- AllowWalletResponse: () => AllowWalletResponse,
24
- Asset: () => Asset,
25
- AssetCode: () => AssetCode,
26
- AssetDecimals: () => AssetDecimals,
27
- AssetIconUrl: () => AssetIconUrl,
28
- AssetId: () => AssetId,
29
- AssetSymbol: () => AssetSymbol,
30
- AsyncOfferDetail: () => AsyncOfferDetail,
31
- AuthorizationCode: () => AuthorizationCode,
32
- BPS_DENOM: () => BPS_DENOM,
33
- Blockchain: () => Blockchain,
34
- BlockchainAmount: () => BlockchainAmount,
35
- Bps: () => Bps,
36
- CENTRIFUGE_POLL_INTERVAL_MS: () => CENTRIFUGE_POLL_INTERVAL_MS,
37
- CentrifugeNamespaceImpl: () => CentrifugeNamespaceImpl,
38
- CentrifugeVaultBuyTransaction: () => CentrifugeVaultBuyTransaction,
39
- CentrifugeVaultClaimProceedsTransaction: () => CentrifugeVaultClaimProceedsTransaction,
40
- CentrifugeVaultClaimTransaction: () => CentrifugeVaultClaimTransaction,
41
- CentrifugeVaultLeg: () => CentrifugeVaultLeg,
42
- CentrifugeVaultLegId: () => CentrifugeVaultLegId,
43
- CentrifugeVaultPosition: () => CentrifugeVaultPosition,
44
- CentrifugeVaultRedeemPosition: () => CentrifugeVaultRedeemPosition,
45
- CentrifugeVaultStatus: () => CentrifugeVaultStatus,
46
- Chain: () => Chain,
47
- ClientCredentialsOAuth: () => ClientCredentialsOAuth,
48
- ClientId: () => ClientId,
49
- ClientSecret: () => ClientSecret,
50
- CodeChallenge: () => CodeChallenge,
51
- CodeVerifier: () => CodeVerifier,
52
- CoinListTokenSaleNamespaceImpl: () => CoinListTokenSaleNamespaceImpl,
53
- ConnectExternalWalletParams: () => ConnectExternalWalletParams,
54
- CreateParticipationParams: () => CreateParticipationParams,
55
- CreateWalletOwnershipChallengeParams: () => CreateWalletOwnershipChallengeParams,
56
- Cursor: () => Cursor,
57
- DEFAULT_AMOUNT_TO_COMPUTE_PRICE: () => DEFAULT_AMOUNT_TO_COMPUTE_PRICE,
58
- DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE: () => DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE,
59
- DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE: () => DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE,
60
- DEFAULT_SLIPPAGE_BPS: () => DEFAULT_SLIPPAGE_BPS,
61
- DecimalString: () => DecimalString,
62
- DocumentSubmission: () => DocumentSubmission,
63
- ERC20_ABI: () => ERC20_ABI,
64
- ETHEREUM_CHAINS: () => ETHEREUM_CHAINS,
65
- EpochMillis: () => EpochMillis,
66
- Erc20NamespaceImpl: () => Erc20NamespaceImpl,
67
- EthereumChain: () => EthereumChain,
68
- EvmContractAddress: () => EvmContractAddress,
69
- EvmWalletAddress: () => EvmWalletAddress,
70
- FaqItem: () => FaqItem,
71
- FormattedAmountAssetUi: () => FormattedAmountAssetUi,
72
- FormattedAmountUi: () => FormattedAmountUi,
73
- FormattedPercentUi: () => FormattedPercentUi,
74
- HexEncodedTransactionData: () => HexEncodedTransactionData,
75
- HttpError: () => HttpError,
76
- InvariantError: () => InvariantError,
77
- Isin: () => Isin,
78
- Iso2CountryCode: () => Iso2CountryCode,
79
- KnownAssetSymbol: () => KnownAssetSymbol,
80
- KycToken: () => KycToken,
81
- Link: () => Link,
82
- MAX_ASSET_DECIMALS: () => MAX_ASSET_DECIMALS,
83
- MAX_UINT_256: () => MAX_UINT_256,
84
- MathError: () => MathError,
85
- Milestone: () => Milestone,
86
- Millis: () => Millis,
87
- NA_AMOUNT_ASSET_UI: () => NA_AMOUNT_ASSET_UI,
88
- NotAuthenticatedError: () => NotAuthenticatedError,
89
- NotImplementedError: () => NotImplementedError,
90
- OAuthRefreshToken: () => OAuthRefreshToken,
91
- OAuthSession: () => OAuthSession,
92
- ONDO_NOT_TRADABLE_CODE: () => ONDO_NOT_TRADABLE_CODE,
93
- ONDO_POLL_INTERVAL_MS: () => ONDO_POLL_INTERVAL_MS,
94
- ONDO_QUOTE_MAX_TTL_MS: () => ONDO_QUOTE_MAX_TTL_MS,
95
- ONDO_SETTLEMENT_ASSET: () => ONDO_SETTLEMENT_ASSET,
96
- ONDO_SUPPORTED_INPUT_ASSETS: () => ONDO_SUPPORTED_INPUT_ASSETS,
97
- Offer: () => Offer,
98
- OfferDetail: () => OfferDetail,
99
- OfferEditorial: () => OfferEditorial,
100
- OfferId: () => OfferId,
101
- OfferOption: () => OfferOption,
102
- OfferOptionAddress: () => OfferOptionAddress,
103
- OfferOptionAddressId: () => OfferOptionAddressId,
104
- OfferOptionId: () => OfferOptionId,
105
- OfferOptionSlug: () => OfferOptionSlug,
106
- OfferSlug: () => OfferSlug,
107
- OfferSwapContract: () => OfferSwapContract,
108
- OfferToken: () => OfferToken,
109
- OfferVaultContract: () => OfferVaultContract,
110
- OffersNamespaceImpl: () => OffersNamespaceImpl,
111
- OndoBuyTransaction: () => OndoBuyTransaction,
112
- OndoNamespaceImpl: () => OndoNamespaceImpl,
113
- OndoQuote: () => OndoQuote,
114
- OndoSellTransaction: () => OndoSellTransaction,
115
- OndoTradingStatus: () => OndoTradingStatus,
116
- PKCEState: () => PKCEState,
117
- PaginatedResponse: () => PaginatedResponse,
118
- PaginationParams: () => PaginationParams,
119
- Participation: () => Participation,
120
- ParticipationId: () => ParticipationId,
121
- ParticipationsPaginationParams: () => ParticipationsPaginationParams,
122
- PauseFlags: () => PauseFlags,
123
- Pii: () => Pii,
124
- PiiAddress: () => PiiAddress,
125
- PiiJurisdiction: () => PiiJurisdiction,
126
- RedactedWalletError: () => RedactedWalletError,
127
- RedirectUri: () => RedirectUri,
128
- Requirement: () => Requirement,
129
- RequirementId: () => RequirementId,
130
- RequirementStatusInfo: () => RequirementStatusInfo,
131
- RequirementsNamespaceImpl: () => RequirementsNamespaceImpl,
132
- SLIPPAGE_OPTIONS_BPS: () => SLIPPAGE_OPTIONS_BPS,
133
- SOLANA_CHAINS: () => SOLANA_CHAINS,
134
- STABLE_DECIMALS: () => STABLE_DECIMALS,
135
- SUPERSTATE_ISSUER_NAME: () => SUPERSTATE_ISSUER_NAME,
136
- SUPERSTATE_SUPPORTED_INPUT_ASSETS: () => SUPERSTATE_SUPPORTED_INPUT_ASSETS,
137
- SUPERSTATE_SWAP_ABI: () => SUPERSTATE_SWAP_ABI,
138
- SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA: () => SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA,
139
- SWAP_LEVEL: () => SWAP_LEVEL,
140
- SWAP_POLL_INTERVAL_MS: () => SWAP_POLL_INTERVAL_MS,
141
- Seconds: () => Seconds,
142
- ShortenedWalletAddress: () => ShortenedWalletAddress,
143
- SolanaChain: () => SolanaChain,
144
- StablecoinSymbol: () => StablecoinSymbol,
145
- SuperstateSwapNamespaceImpl: () => SuperstateSwapNamespaceImpl,
146
- SwapPreview: () => SwapPreview,
147
- SwapQuote: () => SwapQuote,
148
- SwapStatus: () => SwapStatus,
149
- TOKEN_REGISTRY: () => TOKEN_REGISTRY,
150
- TermItem: () => TermItem,
151
- Ticker: () => Ticker,
152
- TokenLogo: () => TokenLogo,
153
- TokenLogoUrl: () => TokenLogoUrl,
154
- TokenMetadata: () => TokenMetadata,
155
- TokenRegistrySnapshot: () => TokenRegistrySnapshot,
156
- TokensNamespaceImpl: () => TokensNamespaceImpl,
157
- TxExplorerUrl: () => TxExplorerUrl,
158
- USDC: () => USDC,
159
- USDC_SYMBOL: () => USDC_SYMBOL,
160
- USDT: () => USDT,
161
- USDT_SYMBOL: () => USDT_SYMBOL,
162
- User: () => User,
163
- UserEmail: () => UserEmail,
164
- UserId: () => UserId,
165
- ValidationError: () => ValidationError,
166
- WalletAddress: () => WalletAddress,
167
- WalletOwnershipChallenge: () => WalletOwnershipChallenge,
168
- WalletSelection: () => WalletSelection,
169
- WalletsNamespaceImpl: () => WalletsNamespaceImpl,
170
- apiErrorCode: () => apiErrorCode,
171
- applyBps: () => applyBps,
172
- assertUint256: () => assertUint256,
173
- assetAmount: () => assetAmount,
174
- blockchainAmountFromRawOrThrow: () => blockchainAmountFromRawOrThrow,
175
- chainFromId: () => chainFromId,
176
- computeOndoBuyPrice: () => computeOndoBuyPrice,
177
- computeOndoSellPrice: () => computeOndoSellPrice,
178
- computePrice: () => computePrice,
179
- computeSlip: () => computeSlip,
180
- decodeSwappedOutputAmount: () => decodeSwappedOutputAmount,
181
- fetchAllPages: () => fetchAllPages,
182
- formatAmount: () => formatAmount,
183
- formatBpsAsPercent: () => formatBpsAsPercent,
184
- formatCompactAmount: () => formatCompactAmount,
185
- formatRawAmount: () => formatRawAmount,
186
- formatShareAmount: () => formatShareAmount,
187
- formattedPricePerShare: () => formattedPricePerShare,
188
- formattedUsdPrice: () => formattedUsdPrice,
189
- generatePKCEParams: () => generatePKCEParams,
190
- getChainId: () => getChainId,
191
- getNetworkName: () => getNetworkName,
192
- isChain: () => isChain,
193
- isExpired: () => isExpired,
194
- isOfferType: () => isOfferType,
195
- isOndoNotTradableError: () => isOndoNotTradableError,
196
- isSwapAvailable: () => isSwapAvailable,
197
- offerDisplayTokens: () => offerDisplayTokens,
198
- ondoQuoteOfferDeadline: () => ondoQuoteOfferDeadline,
199
- parseBlockchainAmount: () => parseBlockchainAmount,
200
- parseUint256: () => parseUint256,
201
- resolveCentrifugeVaults: () => resolveCentrifugeVaults,
202
- shortenAddress: () => shortenAddress,
203
- superstateSwapContractAddress: () => superstateSwapContractAddress,
204
- swapSpender: () => swapSpender,
205
- txExplorerUrl: () => txExplorerUrl,
206
- usdAmount: () => usdAmount,
207
- viemChain: () => viemChain
208
- });
209
- module.exports = __toCommonJS(universal_exports);
210
-
211
- // src/universal/api/internal-access-token-source.ts
212
- var SentWith = {
213
- userToken: (token) => ({
214
- type: "user-token",
215
- token
216
- }),
217
- noUserToken: { type: "no-user-token" }
218
- };
219
-
220
- // src/universal/api/http-attributes.ts
221
- var empty = {};
222
- var concat = (left, right) => ({
223
- ...left,
224
- ...right
225
- });
226
- var concatAll = (...items) => {
227
- let result = empty;
228
- for (const item of items) {
229
- result = concat(result, item);
230
- }
231
- return result;
232
- };
233
- var protectedRequest = () => ({ protected: true });
234
- var userAgent = () => ({ userAgent: true });
235
- var idempotencyKey = () => ({
236
- idempotencyKey: true
237
- });
238
- var clientCredentials = (credentials) => ({
239
- clientCredentials: credentials
240
- });
241
- var retryAttempt = (attempt) => ({
242
- retryAttempt: attempt
243
- });
244
- var renewAttempted = (value) => ({
245
- renewAttempted: value
246
- });
247
- var notRetryable = () => ({ retryable: false });
248
- var sentWith = (token) => ({
249
- sentWith: token
250
- });
251
- var requestId = (id) => ({ requestId: id });
252
- var getRequestId = (attrs) => attrs?.requestId ?? null;
253
- var isProtected = (attrs) => attrs?.protected === true;
254
- var needUserAgent = (attrs) => attrs?.userAgent === true;
255
- var isIdempotent = (attrs) => attrs?.idempotencyKey === true;
256
- var getRetryAttempt = (attrs) => attrs?.retryAttempt ?? 0;
257
- var wasRenewAttempted = (attrs) => attrs?.renewAttempted === true;
258
- var isRetryable = (attrs) => attrs?.retryable !== false;
259
- var getSentWith = (attrs) => attrs?.sentWith === void 0 ? SentWith.noUserToken : SentWith.userToken(attrs.sentWith);
260
- var getClientCredentials = (attrs) => attrs?.clientCredentials;
261
- var Attributes = {
262
- empty,
263
- concat,
264
- concatAll,
265
- protected: protectedRequest,
266
- isProtected,
267
- userAgent,
268
- needUserAgent,
269
- idempotencyKey,
270
- isIdempotent,
271
- retryAttempt,
272
- getRetryAttempt,
273
- renewAttempted,
274
- wasRenewAttempted,
275
- notRetryable,
276
- isRetryable,
277
- sentWith,
278
- getSentWith,
279
- clientCredentials,
280
- getClientCredentials,
281
- requestId,
282
- getRequestId
283
- };
284
-
285
- // src/universal/api/http.ts
286
- var HttpError = class extends Error {
287
- constructor(response) {
288
- super(`Request failed with ${response.status} status`);
289
- this.name = "HttpError";
290
- this.response = response;
291
- }
292
- /**
293
- * Correlates this failure with the `[HTTP]` log lines for the same request,
294
- * which carry the method, the URL, the duration and every retry. `null` when
295
- * the response did not come from an {@link HttpClient}.
296
- *
297
- * Worth quoting in a bug report: it is what makes a log excerpt readable.
298
- */
299
- get requestId() {
300
- return this.response.requestId ?? null;
301
- }
302
- };
303
- function apiErrorCode(error) {
304
- if (!(error instanceof HttpError)) return null;
305
- const body = error.response.body;
306
- if (typeof body !== "object" || body === null) return null;
307
- const code = body.code;
308
- return typeof code === "string" ? code : null;
309
- }
310
- async function makeRequest(request) {
311
- const headers = {
312
- Accept: "application/json",
313
- ...request.method === "POST" && request.body !== void 0 ? { "Content-Type": "application/json" } : {},
314
- ...request.headers ?? {}
315
- };
316
- const init = {
317
- method: request.method,
318
- headers,
319
- ...request.redirect !== void 0 ? { redirect: request.redirect } : {}
320
- };
321
- if (request.method === "POST" && request.body !== void 0) {
322
- init.body = JSON.stringify(request.body);
323
- }
324
- const response = await fetch(
325
- buildUrlWithQueryParams(request.url, request.queryParams),
326
- init
327
- );
328
- const responseHeaders = headersToRecord(response.headers);
329
- if (response.status === 204 || response.status === 205) {
330
- return {
331
- status: response.status,
332
- body: null,
333
- headers: responseHeaders
334
- };
335
- }
336
- if (response.status >= 300 && response.status < 400) {
337
- await response.text();
338
- return {
339
- status: response.status,
340
- body: null,
341
- headers: responseHeaders
342
- };
343
- }
344
- const text = await response.text();
345
- let body;
346
- try {
347
- body = text ? JSON.parse(text) : null;
348
- } catch (_) {
349
- throw new HttpError({
350
- status: response.status,
351
- headers: responseHeaders,
352
- body: text
353
- });
354
- }
355
- return {
356
- status: response.status,
357
- body,
358
- headers: responseHeaders
359
- };
360
- }
361
- function buildUrlWithQueryParams(url, queryParams) {
362
- if (!queryParams) {
363
- return url;
364
- }
365
- const searchParams = new URLSearchParams();
366
- for (const [key, value] of Object.entries(queryParams)) {
367
- if (value === void 0 || value === null) {
368
- continue;
369
- }
370
- if (Array.isArray(value)) {
371
- for (const item of value) {
372
- if (item === void 0 || item === null) {
373
- continue;
374
- }
375
- searchParams.append(key, String(item));
376
- }
377
- continue;
378
- }
379
- searchParams.append(key, String(value));
380
- }
381
- const queryString = searchParams.toString();
382
- if (!queryString) {
383
- return url;
384
- }
385
- return url.includes("?") ? `${url}&${queryString}` : `${url}?${queryString}`;
386
- }
387
- function headersToRecord(headers) {
388
- const record = {};
389
- headers.forEach((value, key) => {
390
- record[key.toLowerCase()] = value;
391
- });
392
- return record;
393
- }
394
-
395
- // src/universal/api/pagination.ts
396
- async function fetchAllPages(fetchPage, baseParams) {
397
- const items = [];
398
- let cursor = null;
399
- do {
400
- const params = {
401
- ...baseParams ?? {},
402
- after: cursor ?? void 0
403
- };
404
- const page = await fetchPage(params);
405
- items.push(...page.data);
406
- cursor = page.startingAfter;
407
- } while (cursor);
408
- return items;
409
- }
410
-
411
- // src/universal/core/shared/utils/crypto.ts
412
- async function sha256(data) {
413
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
414
- const buffer = bytes.buffer.slice(
415
- bytes.byteOffset,
416
- bytes.byteOffset + bytes.byteLength
417
- );
418
- return crypto.subtle.digest("SHA-256", buffer);
419
- }
420
- function arrayBufferToBase64Url(buffer, padding = true) {
421
- const bytes = new Uint8Array(buffer);
422
- let binary = "";
423
- for (let i = 0; i < bytes.length; i++) {
424
- binary += String.fromCharCode(bytes[i]);
425
- }
426
- let base64 = btoa(binary);
427
- base64 = base64.replace(/\+/g, "-").replace(/\//g, "_");
428
- if (!padding) {
429
- base64 = base64.replace(/=+$/, "");
430
- }
431
- return base64;
432
- }
433
- function generateSecureRandomBase64Url(byteLength) {
434
- const bytes = new Uint8Array(byteLength);
435
- crypto.getRandomValues(bytes);
436
- const buffer = bytes.buffer;
437
- return arrayBufferToBase64Url(buffer, false);
438
- }
439
- function notBlankStringOrNull(value) {
440
- if (value?.trim()) {
441
- return value;
442
- } else {
443
- return null;
444
- }
445
- }
446
-
447
- // src/universal/types/oauth.ts
448
- var AuthorizationCode = (value) => value;
449
- var CodeVerifier = (value) => value;
450
- var CodeChallenge = (value) => value;
451
- var PKCEState = (value) => value;
452
- var RedirectUri = (value) => value;
453
- var ClientId = (value) => value;
454
- var ClientSecret = (value) => value;
455
-
456
- // src/universal/core/auth/pkce.ts
457
- async function generatePKCEParams(config) {
458
- const state = generateSecureRandomBase64Url(32);
459
- const codeVerifier = generateSecureRandomBase64Url(32);
460
- const codeChallengeRaw = await sha256(codeVerifier);
461
- const codeChallenge = arrayBufferToBase64Url(codeChallengeRaw, false);
462
- return {
463
- clientId: config.clientId,
464
- responseType: "code",
465
- redirectUri: config.redirectUri,
466
- codeChallenge: CodeChallenge(codeChallenge),
467
- codeChallengeMethod: "S256",
468
- state: PKCEState(state),
469
- codeVerifier: CodeVerifier(codeVerifier)
470
- };
471
- }
472
-
473
- // src/universal/types/errors.ts
474
- var NotImplementedError = class extends Error {
475
- constructor(message = "Not implemented yet") {
476
- super(message);
477
- this.name = "NotImplementedError";
478
- }
479
- };
480
- var NotAuthenticatedError = class extends Error {
481
- constructor(message = "The user is not authenticated. Go through the OAuth flow first!") {
482
- super(message);
483
- this.name = "NotAuthenticatedError";
484
- }
485
- };
486
- var ValidationError = class extends Error {
487
- constructor(message) {
488
- super(message);
489
- this.name = "ValidationError";
490
- }
491
- };
492
- var InvariantError = class extends Error {
493
- constructor(message) {
494
- super(message);
495
- this.name = "InvariantError";
496
- }
497
- };
498
- var MathError = class extends Error {
499
- constructor(message) {
500
- super(message);
501
- this.name = "MathError";
502
- }
503
- };
504
-
505
- // src/universal/core/shared/blockchain/math.ts
506
- var import_viem = require("viem");
507
-
508
- // src/universal/types/blockchain/core.ts
509
- var ETHEREUM_CHAINS = {
510
- ethereum_mainnet: true,
511
- ethereum_sepolia: true,
512
- base_mainnet: true,
513
- base_sepolia: true
514
- };
515
- var EthereumChain = (value) => {
516
- if (!Object.keys(ETHEREUM_CHAINS).includes(value)) {
517
- throw new ValidationError(`Unsupported Ethereum chain: "${value}"`);
518
- }
519
- return value;
520
- };
521
- var SOLANA_CHAINS = {
522
- solana_mainnet: true,
523
- solana_devnet: true
524
- };
525
- var SolanaChain = (value) => {
526
- if (!Object.keys(SOLANA_CHAINS).includes(value)) {
527
- throw new ValidationError(`Unsupported Solana chain: "${value}"`);
528
- }
529
- return value;
530
- };
531
- var isChain = (value) => Object.keys(ETHEREUM_CHAINS).includes(value) || Object.keys(SOLANA_CHAINS).includes(value);
532
- var Chain = (value) => {
533
- if (!isChain(value)) {
534
- throw new ValidationError(`Unsupported chain: "${value}"`);
535
- }
536
- return value;
537
- };
538
- var EvmWalletAddress = (value) => value;
539
- var EvmContractAddress = (value) => value;
540
- var HexEncodedTransactionData = (value) => value;
541
- var MAX_ASSET_DECIMALS = 77;
542
- var AssetDecimals = (value) => {
543
- if (!Number.isInteger(value)) {
544
- throw new ValidationError(`Asset decimals must be an integer: ${value}`);
545
- }
546
- if (value < 0 || value > MAX_ASSET_DECIMALS) {
547
- throw new ValidationError(
548
- `Asset decimals out of range [0, ${MAX_ASSET_DECIMALS}]: ${value}`
549
- );
550
- }
551
- return value;
552
- };
553
- var STABLE_DECIMALS = AssetDecimals(6);
554
- var DecimalString = (value) => value;
555
- var MAX_UINT_256 = 2n ** 256n - 1n;
556
- var assertUint256 = (value) => {
557
- if (isUint256(value)) return value;
558
- throw new InvariantError(`Value out of uint256 bounds: ${value}`);
559
- };
560
- var parseUint256 = (value, label) => {
561
- if (isUint256(value)) return value;
562
- throw new ValidationError(`${label}: out of uint256 bounds (${value})`);
563
- };
564
- var isUint256 = (value) => value >= 0n && value <= MAX_UINT_256;
565
- var BlockchainAmount = Object.assign(
566
- (value) => value,
567
- {
568
- add: (a, b) => combineAmounts(a, b, (x, y) => x + y),
569
- sub: (a, b) => combineAmounts(a, b, (x, y) => x - y),
570
- mul: multiplyAmounts,
571
- div: divideAmounts
572
- }
573
- );
574
- function multiplyAmounts(a, b) {
575
- const product = a.raw * b.raw;
576
- return BlockchainAmount({
577
- raw: product / 10n ** BigInt(b.decimals),
578
- decimals: a.decimals
579
- });
580
- }
581
- function divideAmounts(a, b) {
582
- if (b.raw === 0n) {
583
- throw new MathError("Cannot divide a BlockchainAmount by zero");
584
- }
585
- const scaled = a.raw * 10n ** BigInt(b.decimals);
586
- return BlockchainAmount({ raw: scaled / b.raw, decimals: a.decimals });
587
- }
588
- function combineAmounts(a, b, op) {
589
- if (a.decimals !== b.decimals) {
590
- throw new InvariantError(
591
- `Cannot combine BlockchainAmounts with different decimals: ${a.decimals} vs ${b.decimals}`
592
- );
593
- }
594
- const raw = op(a.raw, b.raw);
595
- if (raw < 0n || raw > MAX_UINT_256) {
596
- throw new InvariantError(`BlockchainAmount out of uint256 bounds: ${raw}`);
597
- }
598
- return BlockchainAmount({ raw, decimals: a.decimals });
599
- }
600
- var AssetSymbol = (value) => value;
601
- var StablecoinSymbol = (value) => value;
602
- var KnownAssetSymbol = StablecoinSymbol;
603
- var Bps = (value) => value;
604
-
605
- // src/universal/core/shared/blockchain/math.ts
606
- function blockchainAmountFromRawOrThrow({
607
- label,
608
- raw,
609
- decimals
610
- }) {
611
- const trimmed = raw.trim();
612
- if (trimmed === "") {
613
- throw new ValidationError(`${label}: not a uint256 integer ("${raw}")`);
614
- }
615
- let value;
616
- try {
617
- value = BigInt(trimmed);
618
- } catch {
619
- throw new ValidationError(`${label}: not a uint256 integer ("${raw}")`);
620
- }
621
- try {
622
- return BlockchainAmount({ raw: assertUint256(value), decimals });
623
- } catch {
624
- throw new ValidationError(`${label}: out of uint256 bounds (${value})`);
625
- }
626
- }
627
- function parseBlockchainAmount(amount, decimals) {
628
- const trimmed = amount.trim();
629
- if (trimmed === "") return { valid: false, reason: { type: "empty" } };
630
- if (trimmed.startsWith("-")) {
631
- return { valid: false, reason: { type: "negative" } };
632
- }
633
- if (/[eE]/.test(trimmed)) {
634
- return { valid: false, reason: { type: "invalid-format" } };
635
- }
636
- if (trimmed === ".") {
637
- return { valid: false, reason: { type: "invalid-format" } };
638
- }
639
- const normalised = trimmed.replace(/^\./, "0.").replace(/\.$/, "");
640
- if (!/^\d+(\.\d+)?$/.test(normalised)) {
641
- return { valid: false, reason: { type: "invalid-format" } };
642
- }
643
- const [, fraction = ""] = normalised.split(".");
644
- if (fraction.length > decimals) {
645
- return {
646
- valid: false,
647
- reason: { type: "too-many-decimals", maxDecimals: decimals }
648
- };
649
- }
650
- try {
651
- const raw = (0, import_viem.parseUnits)(normalised, decimals);
652
- if (raw > MAX_UINT_256) {
653
- return { valid: false, reason: { type: "overflow" } };
654
- }
655
- return {
656
- valid: true,
657
- amount: BlockchainAmount({ raw, decimals })
658
- };
659
- } catch {
660
- return { valid: false, reason: { type: "invalid-format" } };
661
- }
662
- }
663
-
664
- // src/universal/core/shared/utils/wire.ts
665
- function unknownTypeError(dto, model) {
666
- const type = dto.type;
667
- throw new ValidationError(
668
- `${model}.type: unknown type ${JSON.stringify(type)}`
669
- );
670
- }
671
- function requiredString(value, field) {
672
- const text = notBlankStringOrNull(value);
673
- if (text === null) {
674
- throw new ValidationError(
675
- `${field}: expected a non-blank string, got ${typeof value === "string" ? "a blank string" : String(value)}`
676
- );
677
- }
678
- return text;
679
- }
680
- function requiredDate(value, field) {
681
- const date = typeof value === "string" ? new Date(value) : null;
682
- if (date === null || Number.isNaN(date.getTime())) {
683
- throw new ValidationError(
684
- `${field}: expected a date, got ${JSON.stringify(value)}`
685
- );
686
- }
687
- return date;
688
- }
689
- function dateOrNull(value, field) {
690
- return value === null ? null : requiredDate(value, field);
691
- }
692
- function decimalOrNull(value) {
693
- return value === null ? null : DecimalString(value);
694
- }
695
- function requiredArray(value, field) {
696
- if (!Array.isArray(value)) {
697
- throw new ValidationError(
698
- `${field}: expected an array, got ${typeof value}`
699
- );
700
- }
701
- return value;
702
- }
703
-
704
- // src/universal/types/providers/centrifuge/centrifuge.ts
705
- var CentrifugeVaultStatus = {
706
- fromDto: (dto) => ({
707
- chain: EthereumChain(dto.chain),
708
- symbol: AssetSymbol(dto.symbol),
709
- vaultAddress: EvmContractAddress(dto.vault_address),
710
- linked: dto.linked,
711
- permissioned: dto.permissioned,
712
- membershipValidUntil: dateOrNull(
713
- dto.membership_valid_until,
714
- "CentrifugeVaultStatus.membership_valid_until"
715
- ),
716
- halted: dto.halted,
717
- priceUpdatedAt: dateOrNull(
718
- dto.price_updated_at,
719
- "CentrifugeVaultStatus.price_updated_at"
720
- ),
721
- orderability: parseOrderability(
722
- dto.can_order,
723
- dto.reasons,
724
- "CentrifugeVaultStatus"
725
- ),
726
- asOf: requiredDate(dto.as_of, "CentrifugeVaultStatus.as_of")
727
- })
728
- };
729
- var CentrifugeVaultBuyTransaction = {
730
- fromDto: (dto) => {
731
- const spendInputAmount = blockchainAmountFromRawOrThrow({
732
- label: "spend_input_amount",
733
- raw: dto.spend_input_amount,
734
- decimals: AssetDecimals(dto.spend_input_decimals)
735
- });
736
- if (spendInputAmount.raw <= 0n) {
737
- throw new ValidationError(
738
- `spend_input_amount: must be greater than zero ("${dto.spend_input_amount}") - a deposit of nothing is not a request`
739
- );
740
- }
741
- return {
742
- ...parseTransactionCore(dto, "CentrifugeVaultBuyTransaction"),
743
- spendInputAmount
744
- };
745
- }
746
- };
747
- var CentrifugeVaultClaimTransaction = {
748
- fromDto: (dto) => ({
749
- ...parseTransactionCore(dto, "CentrifugeVaultClaimTransaction"),
750
- claimableShares: blockchainAmountFromRawOrThrow({
751
- label: "claimable_shares",
752
- raw: dto.claimable_shares,
753
- decimals: AssetDecimals(dto.share_decimals)
754
- })
755
- })
756
- };
757
- var CentrifugeVaultPosition = {
758
- fromDto: (dto) => {
759
- const assetDecimals = AssetDecimals(dto.asset_decimals);
760
- const shareDecimals = AssetDecimals(dto.share_decimals);
761
- const asset = (label, raw) => blockchainAmountFromRawOrThrow({ label, raw, decimals: assetDecimals });
762
- const shares = (label, raw) => blockchainAmountFromRawOrThrow({ label, raw, decimals: shareDecimals });
763
- return {
764
- chain: EthereumChain(dto.chain),
765
- symbol: AssetSymbol(dto.symbol),
766
- walletAddress: EvmWalletAddress(dto.wallet_address),
767
- status: dto.status,
768
- requested: asset("requested", dto.requested),
769
- pending: asset("pending", dto.pending),
770
- filledAssets: asset("filled_assets", dto.filled_assets),
771
- earnedShares: shares("earned_shares", dto.earned_shares),
772
- claimedShares: shares("claimed_shares", dto.claimed_shares),
773
- claimableShares: shares("claimable_shares", dto.claimable_shares),
774
- shareBalance: shares("share_balance", dto.share_balance),
775
- averagePrice: decimalOrNull(dto.average_price),
776
- frozen: dto.frozen,
777
- asOf: requiredDate(dto.as_of, "CentrifugeVaultPosition.as_of")
778
- };
779
- }
780
- };
781
- var CentrifugeVaultRedeemPosition = {
782
- fromDto: (dto) => ({
783
- chain: EthereumChain(dto.chain),
784
- symbol: AssetSymbol(dto.symbol),
785
- walletAddress: EvmWalletAddress(dto.wallet_address),
786
- status: dto.status,
787
- pending: blockchainAmountFromRawOrThrow({
788
- label: "pending",
789
- raw: dto.pending,
790
- decimals: AssetDecimals(dto.share_decimals)
791
- }),
792
- claimableAssets: blockchainAmountFromRawOrThrow({
793
- label: "claimable_assets",
794
- raw: dto.claimable_assets,
795
- decimals: AssetDecimals(dto.asset_decimals)
796
- }),
797
- frozen: dto.frozen,
798
- asOf: requiredDate(dto.as_of, "CentrifugeVaultRedeemPosition.as_of")
799
- })
800
- };
801
- var CentrifugeVaultLeg = {
802
- /**
803
- * What a claim on the leg would collect: shares for `invest`, the funding
804
- * token for `redeem`.
805
- */
806
- claimable: (leg) => {
807
- switch (leg.direction) {
808
- case "invest":
809
- return leg.position.claimableShares;
810
- case "redeem":
811
- return leg.position.claimableAssets;
812
- default: {
813
- const exhaustive = leg;
814
- return exhaustive;
815
- }
816
- }
817
- },
818
- /** Whether the leg has anything queued or anything ready to claim. */
819
- isActive: (leg) => leg.position.pending.raw > 0n || CentrifugeVaultLeg.claimable(leg).raw > 0n
820
- };
821
- var CentrifugeVaultLegId = {
822
- /** Addresses compare case-insensitively: frontline echoes them lower case. */
823
- of: (leg) => [
824
- leg.direction,
825
- leg.position.chain,
826
- leg.position.walletAddress.toLowerCase()
827
- ].join(":")
828
- };
829
- var CentrifugeVaultClaimProceedsTransaction = {
830
- fromDto: (dto) => ({
831
- ...parseTransactionCore(dto, "CentrifugeVaultClaimProceedsTransaction"),
832
- claimableAssets: blockchainAmountFromRawOrThrow({
833
- label: "claimable_assets",
834
- raw: dto.claimable_assets,
835
- decimals: AssetDecimals(dto.asset_decimals)
836
- })
837
- })
838
- };
839
- function parseOrderability(canOrder, reasons, model) {
840
- const [first, ...rest] = reasons;
841
- if (canOrder) {
842
- if (first !== void 0) {
843
- throw new ValidationError(
844
- `${model}.reasons: expected none when can_order is true, got ${JSON.stringify(reasons)}`
845
- );
846
- }
847
- return { type: "orderable" };
848
- }
849
- if (first === void 0) {
850
- throw new ValidationError(
851
- `${model}.reasons: expected at least one when can_order is false`
852
- );
853
- }
854
- return { type: "blocked", reasons: [first, ...rest] };
855
- }
856
- function parseTransactionCore(dto, model) {
857
- return {
858
- tx: {
859
- to: EvmContractAddress(dto.to),
860
- data: HexEncodedTransactionData(dto.data)
861
- },
862
- expiresAt: dateOrNull(dto.expires_at, `${model}.expires_at`)
863
- };
864
- }
865
-
866
- // src/universal/api/frontline/providers/centrifuge/centrifuge.ts
867
- async function getCentrifugeVaultStatus(api, params) {
868
- const dto = await api.send({
869
- method: "GET",
870
- url: "/v1/centrifuge/vault/status",
871
- queryParams: {
872
- symbol: params.symbol,
873
- chain: params.chain
874
- },
875
- attributes: Attributes.protected()
876
- });
877
- return CentrifugeVaultStatus.fromDto(dto);
878
- }
879
- async function buildCentrifugeVaultBuy(api, params) {
880
- const dto = await api.send({
881
- method: "POST",
882
- url: "/v1/centrifuge/vault/invest",
883
- body: {
884
- ...walletFields(params),
885
- amount: params.amount.raw.toString()
886
- },
887
- attributes: Attributes.protected()
888
- });
889
- if (dto.spend_input_decimals !== params.amount.decimals) {
890
- throw new ValidationError(
891
- `spend_input_decimals: the request was priced in ${dto.spend_input_decimals} decimals but the deposit was sized in ${params.amount.decimals}`
892
- );
893
- }
894
- return CentrifugeVaultBuyTransaction.fromDto(dto);
895
- }
896
- async function getCentrifugeVaultPosition(api, params) {
897
- const dto = await api.send({
898
- method: "GET",
899
- url: "/v1/centrifuge/vault/position",
900
- queryParams: walletFields(params),
901
- attributes: Attributes.protected()
902
- });
903
- return CentrifugeVaultPosition.fromDto(dto);
904
- }
905
- async function getCentrifugeVaultRedeemPosition(api, params) {
906
- const dto = await api.send({
907
- method: "GET",
908
- url: "/v1/centrifuge/vault/redeem-position",
909
- queryParams: walletFields(params),
910
- attributes: Attributes.protected()
911
- });
912
- return CentrifugeVaultRedeemPosition.fromDto(dto);
913
- }
914
- async function createCentrifugeVaultClaim(api, params) {
915
- const dto = await api.send({
916
- method: "POST",
917
- url: "/v1/centrifuge/vault/claim",
918
- body: walletFields(params),
919
- attributes: Attributes.protected()
920
- });
921
- return CentrifugeVaultClaimTransaction.fromDto(dto);
922
- }
923
- async function createCentrifugeVaultClaimProceeds(api, params) {
924
- const dto = await api.send({
925
- method: "POST",
926
- url: "/v1/centrifuge/vault/claim-proceeds",
927
- body: walletFields(params),
928
- attributes: Attributes.protected()
929
- });
930
- return CentrifugeVaultClaimProceedsTransaction.fromDto(dto);
931
- }
932
- function walletFields(params) {
933
- return {
934
- symbol: params.symbol,
935
- chain: params.chain,
936
- wallet_address: params.walletAddress
937
- };
938
- }
939
-
940
- // src/universal/core/shared/observability/log-cause.ts
941
- var import_viem2 = require("viem");
942
- function classifyLogCause(error) {
943
- if (error instanceof HttpError) {
944
- return httpCause(error);
945
- }
946
- if (error instanceof ValidationError) {
947
- return { type: "validation", message: error.message };
948
- }
949
- if (error instanceof InvariantError) {
950
- return { type: "invariant", message: error.message };
951
- }
952
- if (error instanceof MathError) {
953
- return { type: "math", message: error.message };
954
- }
955
- if (error instanceof NotAuthenticatedError) {
956
- return { type: "not-authenticated" };
957
- }
958
- if (error instanceof NotImplementedError) {
959
- return { type: "not-implemented" };
960
- }
961
- if (error instanceof import_viem2.BaseError) {
962
- const http = error.walk((e) => e instanceof HttpError);
963
- if (http instanceof HttpError) {
964
- return httpCause(http);
965
- }
966
- return { type: "rpc", reason: rpcFailureReason(error) };
967
- }
968
- return { type: "generic-error", name: errorName(error) };
969
- }
970
- function rpcFailureReason(error) {
971
- if (error.walk((e) => e instanceof import_viem2.ContractFunctionRevertedError)) {
972
- return "reverted";
973
- }
974
- if (error.walk((e) => e instanceof import_viem2.RpcError)) {
975
- return "node-rejected";
976
- }
977
- if (error.walk(
978
- (e) => e instanceof import_viem2.HttpRequestError || e instanceof import_viem2.WebSocketRequestError || e instanceof import_viem2.SocketClosedError || e instanceof import_viem2.TimeoutError
979
- )) {
980
- return "transport";
981
- }
982
- if (error instanceof import_viem2.ContractFunctionExecutionError) {
983
- return "malformed-response";
984
- }
985
- return "unknown";
986
- }
987
- function describeErrorUnredacted(error) {
988
- if (error instanceof HttpError) {
989
- return describeHttpErrorRedacted(error);
990
- }
991
- if (error instanceof Error) {
992
- return `${error.name}: ${error.message}`;
993
- }
994
- return `thrown non-error: ${stringifyUnredacted(error)}`;
995
- }
996
- function stringifyUnredacted(value) {
997
- if (value === void 0) return "";
998
- try {
999
- return JSON.stringify(
1000
- value,
1001
- (_key, item) => typeof item === "bigint" ? `${item}` : item
1002
- ) ?? String(value);
1003
- } catch (_) {
1004
- return "<unserializable>";
1005
- }
1006
- }
1007
- function describeHttpErrorRedacted(error) {
1008
- const code = apiErrorCode(error);
1009
- const status = error.response.status;
1010
- return code === null ? `HttpError ${status}` : `HttpError ${status} (${code})`;
1011
- }
1012
- function errorName(error) {
1013
- return error instanceof Error ? error.name : `non-error ${typeof error}`;
1014
- }
1015
- function httpCause(error) {
1016
- return {
1017
- type: "http",
1018
- requestId: error.requestId,
1019
- status: error.response.status,
1020
- code: apiErrorCode(error),
1021
- eventId: apiErrorEventId(error)
1022
- };
1023
- }
1024
- function apiErrorEventId(error) {
1025
- const body = error.response.body;
1026
- if (typeof body !== "object" || body === null) return null;
1027
- const eventId = body.event_id;
1028
- return typeof eventId === "string" ? eventId : null;
1029
- }
1030
-
1031
- // src/universal/core/shared/observability/internal-logger.ts
1032
- function internalLogger(logger, scope) {
1033
- return logger ? scopedLogger(logger, scope, {}) : noopInternalLogger;
1034
- }
1035
- var LEVEL_RANK = {
1036
- none: 0,
1037
- error: 1,
1038
- warn: 2,
1039
- info: 3,
1040
- debug: 4
1041
- };
1042
- function scopedLogger(logger, scope, bindings) {
1043
- const admits = (level) => LEVEL_RANK[logger.level()] >= LEVEL_RANK[level];
1044
- const safe = (event) => ({
1045
- msg: event.msg,
1046
- scope,
1047
- bindings,
1048
- fields: event.fields ?? {},
1049
- ...event.cause === void 0 ? {} : { cause: event.cause }
1050
- });
1051
- const unredacted = (event) => ({
1052
- msg: event.msg,
1053
- scope,
1054
- bindings,
1055
- fields: event.fields ?? {}
1056
- });
1057
- const self = {
1058
- child: (binding) => scopedLogger(logger, scope, { ...bindings, ...binding }),
1059
- debug: (event) => {
1060
- if (admits("debug")) logger.debug(() => unredacted(event()));
1061
- },
1062
- info: (event) => {
1063
- if (admits("info")) logger.info(() => safe(event()));
1064
- },
1065
- warn: (event) => {
1066
- if (admits("warn")) logger.warn(() => safe(event()));
1067
- },
1068
- error: (event) => {
1069
- if (admits("error")) logger.error(() => safe(event()));
1070
- },
1071
- failure: (event, error) => {
1072
- if (admits("debug"))
1073
- logger.debug(() => unredacted(verbatim(event(), error)));
1074
- if (admits("error")) logger.error(() => safe(classified(event(), error)));
1075
- },
1076
- warning: (event, error) => {
1077
- if (admits("debug"))
1078
- logger.debug(() => unredacted(verbatim(event(), error)));
1079
- if (admits("warn")) logger.warn(() => safe(classified(event(), error)));
1080
- },
1081
- wrap: async (op, params, run) => {
1082
- const opLog = self.child({ op });
1083
- opLog.debug(() => ({ msg: "call", fields: { params } }));
1084
- try {
1085
- return await run();
1086
- } catch (error) {
1087
- opLog.failure(() => ({ msg: "call failed" }), error);
1088
- throw error;
1089
- }
1090
- }
1091
- };
1092
- return self;
1093
- }
1094
- function verbatim(event, error) {
1095
- return {
1096
- msg: event.msg,
1097
- fields: { ...event.fields, error: describeErrorUnredacted(error) }
1098
- };
1099
- }
1100
- function classified(event, error) {
1101
- return { ...event, cause: event.cause ?? classifyLogCause(error) };
1102
- }
1103
- var noopInternalLogger = {
1104
- child: () => noopInternalLogger,
1105
- debug: () => void 0,
1106
- info: () => void 0,
1107
- warn: () => void 0,
1108
- error: () => void 0,
1109
- failure: () => void 0,
1110
- warning: () => void 0,
1111
- wrap: (_op, _params, run) => run()
1112
- };
1113
-
1114
- // src/universal/core/checkout/centrifuge/centrifuge-namespace.ts
1115
- var CentrifugeNamespaceImpl = class {
1116
- constructor(ctx) {
1117
- this.ctx = ctx;
1118
- this.log = internalLogger(ctx.logger, "CENTRIFUGE");
1119
- }
1120
- async getVaultStatus(params) {
1121
- return this.log.wrap("getVaultStatus", params, async () => {
1122
- await this.ctx.ensureUserAuthenticated();
1123
- return getCentrifugeVaultStatus(this.ctx.api, params);
1124
- });
1125
- }
1126
- async getPosition(params) {
1127
- return this.log.wrap("getPosition", params, async () => {
1128
- await this.ctx.ensureUserAuthenticated();
1129
- return getCentrifugeVaultPosition(this.ctx.api, params);
1130
- });
1131
- }
1132
- async getRedeemPosition(params) {
1133
- return this.log.wrap("getRedeemPosition", params, async () => {
1134
- await this.ctx.ensureUserAuthenticated();
1135
- return getCentrifugeVaultRedeemPosition(this.ctx.api, params);
1136
- });
1137
- }
1138
- async createClaim(params) {
1139
- return this.log.wrap("createClaim", params, async () => {
1140
- await this.ctx.ensureUserAuthenticated();
1141
- return createCentrifugeVaultClaim(this.ctx.api, params);
1142
- });
1143
- }
1144
- async createClaimProceeds(params) {
1145
- return this.log.wrap("createClaimProceeds", params, async () => {
1146
- await this.ctx.ensureUserAuthenticated();
1147
- return createCentrifugeVaultClaimProceeds(this.ctx.api, params);
1148
- });
1149
- }
1150
- async buildBuyTransaction(params) {
1151
- return this.log.wrap("buildBuyTransaction", params, async () => {
1152
- await this.ctx.ensureUserAuthenticated();
1153
- return buildCentrifugeVaultBuy(this.ctx.api, params);
1154
- });
1155
- }
1156
- };
1157
-
1158
- // src/universal/core/checkout/centrifuge/constants.ts
1159
- var CENTRIFUGE_POLL_INTERVAL_MS = 15e3;
1160
-
1161
- // src/universal/core/checkout/centrifuge/vaults.ts
1162
- function resolveCentrifugeVaults(offer, lookup) {
1163
- return offer.vaultContracts.map((contract) => {
1164
- const { chain } = contract;
1165
- if (!isEthereumChain(chain)) {
1166
- return { type: "unresolved", chain, missing: "evm-chain" };
1167
- }
1168
- const onChain = (role) => offer.tokens.filter(
1169
- (token) => token.role === role && token.chain === chain
1170
- );
1171
- const share = firstKnown(onChain("vault"), lookup);
1172
- if (share === null) {
1173
- return { type: "unresolved", chain, missing: "share-token" };
1174
- }
1175
- const funding = firstKnown(onChain("funding"), lookup);
1176
- if (funding === null) {
1177
- return { type: "unresolved", chain, missing: "funding-token" };
1178
- }
1179
- return {
1180
- type: "resolved",
1181
- vault: { chain, proxy: contract.address, share, funding }
1182
- };
1183
- });
1184
- }
1185
- function firstKnown(tokens, lookup) {
1186
- for (const token of tokens) {
1187
- const metadata = lookup(token);
1188
- if (metadata !== null) return metadata;
1189
- }
1190
- return null;
1191
- }
1192
- function isEthereumChain(chain) {
1193
- return chain in ETHEREUM_CHAINS;
1194
- }
1195
-
1196
- // src/universal/types/pagination.ts
1197
- var Cursor = (value) => value;
1198
- var PaginatedResponse = {
1199
- fromDto: (dto, itemMapper) => PaginatedResponse.fromDtoPage(dto, (items) => items.map(itemMapper)),
1200
- /**
1201
- * For a mapper that decides the page as a whole - one that drops items it
1202
- * cannot map, such as `Offer.listFromDto` - rather than item by item. The
1203
- * cursors are the wire's either way: dropping an item changes what the
1204
- * page holds, not where the next page starts.
1205
- */
1206
- fromDtoPage: (dto, pageMapper) => ({
1207
- data: pageMapper(dto.data),
1208
- startingAfter: dto.starting_after ? Cursor(dto.starting_after) : null,
1209
- startingBefore: dto.starting_before ? Cursor(dto.starting_before) : null
1210
- })
1211
- };
1212
- var PaginationParams = {
1213
- toQueryParams: (params) => {
1214
- const queryParams = {};
1215
- if (params.after) {
1216
- queryParams.starting_after = params.after;
1217
- }
1218
- if (params.before) {
1219
- queryParams.starting_before = params.before;
1220
- }
1221
- if (params.limit) {
1222
- queryParams.limit = params.limit;
1223
- }
1224
- return queryParams;
1225
- }
1226
- };
1227
-
1228
- // src/universal/types/asset.ts
1229
- var AssetId = (value) => value;
1230
- var AssetCode = (value) => value;
1231
- var Asset = {
1232
- fromDto: (dto) => ({
1233
- id: AssetId(dto.id),
1234
- code: AssetCode(dto.code),
1235
- name: dto.name,
1236
- fractionalDigits: dto.fractional_digits
1237
- })
1238
- };
1239
-
1240
- // src/universal/types/offer.ts
1241
- var OfferId = (value) => value;
1242
- var OfferSlug = (value) => value;
1243
- var OFFER_TYPES = {
1244
- "coinlist::token_sale": true,
1245
- "superstate::swap": true,
1246
- "ondo::swap": true,
1247
- "centrifuge::vault": true
1248
- };
1249
- var isOfferType = (value) => Object.keys(OFFER_TYPES).includes(value);
1250
- var OfferEditorial = {
1251
- /**
1252
- * `model` prefixes the field in the error (`'Offer'`, `'OfferDetail'`), so
1253
- * the same three checks name the payload that failed them.
1254
- */
1255
- fromDto: (dto, model) => ({
1256
- tagline: requiredString(dto.tagline, `${model}.tagline`),
1257
- bannerUrl: requiredString(dto.banner_url, `${model}.banner_url`),
1258
- startsAt: requiredDate(dto.starts_at, `${model}.starts_at`)
1259
- })
1260
- };
1261
- var Offer = {
1262
- fromDto: (dto) => {
1263
- const tokens = requiredArray(dto.tokens, "Offer.tokens");
1264
- const base2 = {
1265
- id: OfferId(dto.id),
1266
- slug: OfferSlug(dto.slug),
1267
- endsAt: dto.ends_at ? new Date(dto.ends_at) : null,
1268
- tokens: OfferToken.listFromDto(tokens)
1269
- };
1270
- switch (dto.type) {
1271
- case "coinlist::token_sale":
1272
- return {
1273
- ...base2,
1274
- ...OfferEditorial.fromDto(dto, "Offer"),
1275
- type: dto.type,
1276
- logoUrl: requiredString(dto.logo_url, "Offer.logo_url")
1277
- };
1278
- case "superstate::swap":
1279
- return {
1280
- ...base2,
1281
- ...OfferEditorial.fromDto(dto, "Offer"),
1282
- type: dto.type,
1283
- logoUrl: notBlankStringOrNull(dto.logo_url)
1284
- };
1285
- // `tagline`, `banner_url` and `starts_at` arrive as `null` and are left
1286
- // on the wire: copying them would hand every consumer a `startsAt` that
1287
- // is 1970 for one variant and a date for the others.
1288
- case "ondo::swap":
1289
- case "centrifuge::vault":
1290
- return {
1291
- ...base2,
1292
- type: dto.type,
1293
- logoUrl: notBlankStringOrNull(dto.logo_url)
1294
- };
1295
- default:
1296
- return unknownTypeError(dto, "Offer");
1297
- }
1298
- },
1299
- /**
1300
- * Maps a page of offers, dropping every offer whose `type` this SDK does not
1301
- * name. The same reasoning as {@link OfferToken.listFromDto}: a plain `.map`
1302
- * would throw out of `fromDto` and, through `PaginatedResponse.fromDto`,
1303
- * reject the whole page, so one offer of an unknown type would blank the
1304
- * grid for every offer beside it. A single offer fetched by id still
1305
- * throws, because there is nothing beside it to keep.
1306
- */
1307
- listFromDto: (dtos) => dtos.filter((dto) => isOfferType(dto.type)).map(Offer.fromDto)
1308
- };
1309
- var OfferToken = {
1310
- fromDto: (dto) => ({
1311
- role: dto.role,
1312
- chain: Chain(dto.chain),
1313
- address: EvmContractAddress(dto.address)
1314
- }),
1315
- /**
1316
- * Maps an offer's token list, dropping every token on a chain this SDK does
1317
- * not name. Frontline's chain registry runs ahead of {@link Chain}, and a
1318
- * plain `.map` would throw out of `Offer.fromDto` and, through
1319
- * `PaginatedResponse.fromDto`, reject the whole offers page - which is how
1320
- * one Base token blanked production's offers list. Dropping costs that
1321
- * token's metadata alone: `coinlist.tokens.get` takes an `EthereumChain`,
1322
- * so nobody could have looked it up anyway.
1323
- *
1324
- * Same shape as `TokenMetadata.fromRegistryDto`.
1325
- */
1326
- listFromDto: (dtos) => dtos.filter((dto) => isChain(dto.chain)).map(OfferToken.fromDto)
1327
- };
1328
-
1329
- // src/universal/types/trading.ts
1330
- var Ticker = (value) => value;
1331
- var Isin = (value) => value;
1332
-
1333
- // src/universal/types/offer-detail.ts
1334
- var AsyncOfferDetail = {
1335
- /**
1336
- * Narrows an offer fetched generically, e.g. on an offer page, to one with
1337
- * something to claim.
1338
- *
1339
- * An exhaustive `switch` rather than a list of async types, so a new offer
1340
- * type is a compile error here until someone decides whether it settles
1341
- * later.
1342
- */
1343
- is: (offer) => {
1344
- switch (offer.type) {
1345
- case "centrifuge::vault":
1346
- return true;
1347
- case "ondo::swap":
1348
- case "superstate::swap":
1349
- case "coinlist::token_sale":
1350
- return false;
1351
- default: {
1352
- const exhaustive = offer;
1353
- return exhaustive;
1354
- }
1355
- }
1356
- }
1357
- };
1358
- var OfferOptionId = (value) => value;
1359
- var OfferOptionSlug = (value) => value;
1360
- var OfferSwapContract = {
1361
- fromDto: (dto) => ({
1362
- chain: Chain(dto.chain),
1363
- address: EvmContractAddress(dto.address)
1364
- })
1365
- };
1366
- var OfferVaultContract = {
1367
- fromDto: (dto) => ({
1368
- chain: Chain(dto.chain),
1369
- address: EvmContractAddress(dto.address)
1370
- }),
1371
- /**
1372
- * Drops every proxy on a chain this SDK does not name, as
1373
- * `OfferToken.listFromDto` does: frontline publishes the full offer-token
1374
- * chain list, which runs ahead of {@link Chain}, and one unmodelled chain
1375
- * should not throw away the proxies the SDK can use.
1376
- */
1377
- listFromDto: (dtos) => dtos.filter((dto) => isChain(dto.chain)).map(OfferVaultContract.fromDto)
1378
- };
1379
- var OfferDetail = {
1380
- fromDto: (dto) => {
1381
- const fundingAssets = requiredArray(
1382
- dto.funding_assets,
1383
- "OfferDetail.funding_assets"
1384
- );
1385
- const options = requiredArray(dto.options, "OfferDetail.options");
1386
- const terms = requiredArray(dto.terms, "OfferDetail.terms");
1387
- const links = requiredArray(dto.links, "OfferDetail.links");
1388
- const faqs = requiredArray(dto.faqs, "OfferDetail.faqs");
1389
- const milestones = requiredArray(dto.milestones, "OfferDetail.milestones");
1390
- const tokens = requiredArray(dto.tokens, "OfferDetail.tokens");
1391
- const isin = notBlankStringOrNull(dto.isin);
1392
- const ticker = notBlankStringOrNull(dto.ticker);
1393
- const base2 = {
1394
- id: OfferId(dto.id),
1395
- slug: OfferSlug(dto.slug),
1396
- name: dto.name,
1397
- asset: Asset.fromDto(dto.asset),
1398
- fundingAssets: fundingAssets.map(Asset.fromDto),
1399
- tokens: OfferToken.listFromDto(tokens),
1400
- about: notBlankStringOrNull(dto.about),
1401
- category: dto.category,
1402
- issuer: notBlankStringOrNull(dto.issuer),
1403
- isin: isin === null ? null : Isin(isin),
1404
- ticker: ticker === null ? null : Ticker(ticker),
1405
- instrumentType: notBlankStringOrNull(dto.instrument_type),
1406
- listingVenue: notBlankStringOrNull(dto.listing_venue),
1407
- endsAt: dto.ends_at ? new Date(dto.ends_at) : null,
1408
- faqs: faqs.map(FaqItem.fromDto),
1409
- links: links.map(Link.fromDto),
1410
- milestones: milestones.map(Milestone.fromDto),
1411
- options: options.map(OfferOption.fromDto),
1412
- terms: terms.map(TermItem.fromDto)
1413
- };
1414
- switch (dto.type) {
1415
- case "coinlist::token_sale":
1416
- return {
1417
- ...base2,
1418
- ...OfferEditorial.fromDto(dto, "OfferDetail"),
1419
- type: dto.type,
1420
- logoUrl: requiredString(dto.logo_url, "OfferDetail.logo_url")
1421
- };
1422
- case "superstate::swap":
1423
- return {
1424
- ...base2,
1425
- ...OfferEditorial.fromDto(dto, "OfferDetail"),
1426
- type: dto.type,
1427
- logoUrl: notBlankStringOrNull(dto.logo_url)
1428
- };
1429
- // `tagline`, `banner_url` and `starts_at` arrive as `null` and are left
1430
- // on the wire, as in `Offer.fromDto`.
1431
- case "ondo::swap":
1432
- return {
1433
- ...base2,
1434
- type: dto.type,
1435
- logoUrl: notBlankStringOrNull(dto.logo_url),
1436
- swapContracts: requiredArray(
1437
- dto.swap_contracts,
1438
- "OfferDetail.swap_contracts"
1439
- ).map(OfferSwapContract.fromDto)
1440
- };
1441
- // No editorial, as for Ondo. `[]` is fine and a missing key is not, for
1442
- // the same reason as `swap_contracts`: this is the spender a user
1443
- // approves.
1444
- case "centrifuge::vault":
1445
- return {
1446
- ...base2,
1447
- type: dto.type,
1448
- logoUrl: notBlankStringOrNull(dto.logo_url),
1449
- vaultContracts: OfferVaultContract.listFromDto(
1450
- requiredArray(dto.vault_contracts, "OfferDetail.vault_contracts")
1451
- )
1452
- };
1453
- default:
1454
- return unknownTypeError(dto, "OfferDetail");
1455
- }
1456
- }
1457
- };
1458
- var OfferOption = {
1459
- fromDto: (dto) => ({
1460
- id: OfferOptionId(dto.id),
1461
- slug: OfferOptionSlug(dto.slug),
1462
- bidIncrement: dto.bid_increment,
1463
- floorPriceUsd: dto.floor_price_usd,
1464
- minimumPurchaseUsd: dto.minimum_purchase_usd,
1465
- priceUsd: dto.price_usd,
1466
- saleAgreementUrl: notBlankStringOrNull(dto.sale_agreement_url),
1467
- totalTokenSupply: dto.total_token_supply
1468
- })
1469
- };
1470
- var FaqItem = {
1471
- fromDto: (dto) => ({
1472
- question: notBlankStringOrNull(dto.question),
1473
- answer: notBlankStringOrNull(dto.answer)
1474
- })
1475
- };
1476
- var Link = {
1477
- fromDto: (dto) => ({
1478
- label: notBlankStringOrNull(dto.label),
1479
- url: notBlankStringOrNull(dto.url)
1480
- })
1481
- };
1482
- var TermItem = {
1483
- fromDto: (dto) => ({
1484
- key: notBlankStringOrNull(dto.key),
1485
- value: notBlankStringOrNull(dto.value)
1486
- })
1487
- };
1488
- var Milestone = {
1489
- fromDto: (dto) => ({
1490
- name: notBlankStringOrNull(dto.name),
1491
- schedule: notBlankStringOrNull(dto.schedule),
1492
- status: dto.status
1493
- })
1494
- };
1495
-
1496
- // src/universal/types/providers/coin-list/token-sale.ts
1497
- var ParticipationId = (value) => value;
1498
- var Blockchain = (value) => value;
1499
- var WalletAddress = (value) => value;
1500
- var ParticipationsPaginationParams = {
1501
- toQueryParams: (params) => {
1502
- const queryParams = PaginationParams.toQueryParams(params);
1503
- if (params.offerId) {
1504
- queryParams["filters[0][field]"] = "offer_id";
1505
- queryParams["filters[0][op]"] = "==";
1506
- queryParams["filters[0][value]"] = params.offerId;
1507
- }
1508
- return queryParams;
1509
- }
1510
- };
1511
- var Participation = {
1512
- /** Maps API DTO shape into the SDK participation domain model. */
1513
- fromDto: (dto) => {
1514
- const walletAddress = notBlankStringOrNull(dto.wallet_address);
1515
- return {
1516
- id: ParticipationId(dto.id),
1517
- offerId: OfferId(dto.offer_id),
1518
- offerOptionId: OfferOptionId(dto.offer_option_id),
1519
- status: dto.status,
1520
- amount: dto.amount,
1521
- displayAmount: dto.amount_string,
1522
- asset: Asset.fromDto(dto.asset),
1523
- chain: Blockchain(dto.chain),
1524
- insertedAt: dto.inserted_at ? new Date(dto.inserted_at) : null,
1525
- updatedAt: dto.updated_at ? new Date(dto.updated_at) : null,
1526
- walletAddress: walletAddress ? WalletAddress(walletAddress) : null
1527
- };
1528
- }
1529
- };
1530
- var CreateParticipationParams = {
1531
- /** Maps participation creation params into API DTO payload. */
1532
- toDto: (params) => ({
1533
- offer_id: params.offerId,
1534
- offer_option_id: params.offerOptionId,
1535
- chain: params.chain,
1536
- wallet_address: params.walletAddress,
1537
- amount: params.amount,
1538
- asset_id: params.assetId,
1539
- approval_transaction_hash: params.approvalTransactionHash
1540
- })
1541
- };
1542
-
1543
- // src/universal/api/frontline/providers/coin-list/token-sale.ts
1544
- async function fetchParticipations(api, offerId) {
1545
- return fetchAllPages(
1546
- (params) => fetchParticipationsPage(api, params),
1547
- { offerId }
1548
- );
1549
- }
1550
- async function fetchParticipationsPage(api, params) {
1551
- const pageDto = await api.send({
1552
- method: "GET",
1553
- url: "/v1/participations",
1554
- queryParams: ParticipationsPaginationParams.toQueryParams(params),
1555
- attributes: Attributes.protected()
1556
- });
1557
- return PaginatedResponse.fromDto(pageDto, Participation.fromDto);
1558
- }
1559
- async function fetchParticipation(api, id) {
1560
- const dto = await api.send({
1561
- method: "GET",
1562
- url: `/v1/participations/${id}`,
1563
- attributes: Attributes.protected()
1564
- });
1565
- return Participation.fromDto(dto);
1566
- }
1567
- async function createParticipation(api, params) {
1568
- const dto = await api.send({
1569
- method: "POST",
1570
- url: "/v1/participations",
1571
- body: CreateParticipationParams.toDto(params),
1572
- attributes: Attributes.protected()
1573
- });
1574
- return Participation.fromDto(dto);
1575
- }
1576
-
1577
- // src/universal/core/checkout/coin-list/token-sale-namespace.ts
1578
- var CoinListTokenSaleNamespaceImpl = class {
1579
- constructor(ctx) {
1580
- this.ctx = ctx;
1581
- this.log = internalLogger(ctx.logger, "TOKEN_SALE");
1582
- }
1583
- async list(offerId) {
1584
- return this.log.wrap("list", offerId, async () => {
1585
- await this.ctx.ensureUserAuthenticated();
1586
- return fetchParticipations(this.ctx.api, offerId);
1587
- });
1588
- }
1589
- async listPage(params) {
1590
- return this.log.wrap("listPage", params, async () => {
1591
- await this.ctx.ensureUserAuthenticated();
1592
- return fetchParticipationsPage(this.ctx.api, params);
1593
- });
1594
- }
1595
- async get(id) {
1596
- return this.log.wrap("get", id, async () => {
1597
- await this.ctx.ensureUserAuthenticated();
1598
- return fetchParticipation(this.ctx.api, id);
1599
- });
1600
- }
1601
- async createParticipation(params) {
1602
- return this.log.wrap("createParticipation", params, async () => {
1603
- await this.ctx.ensureUserAuthenticated();
1604
- return createParticipation(this.ctx.api, params);
1605
- });
1606
- }
1607
- };
1608
-
1609
- // src/universal/core/shared/blockchain/token-registry.ts
1610
- var USDC_SYMBOL = StablecoinSymbol("USDC");
1611
- var USDC = {
1612
- name: "USD Coin",
1613
- symbol: USDC_SYMBOL,
1614
- decimals: AssetDecimals(6)
1615
- };
1616
- var USDT_SYMBOL = StablecoinSymbol("USDT");
1617
- var USDT = {
1618
- name: "Tether USD",
1619
- symbol: USDT_SYMBOL,
1620
- decimals: AssetDecimals(6)
1621
- };
1622
- var USDC_ADDRESSES = {
1623
- ethereum_mainnet: EvmContractAddress(
1624
- "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"
1625
- ),
1626
- ethereum_sepolia: EvmContractAddress(
1627
- "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238"
1628
- ),
1629
- base_mainnet: EvmContractAddress(
1630
- "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
1631
- ),
1632
- base_sepolia: EvmContractAddress(
1633
- "0x036CbD53842c5426634e7929541eC2318f3dCF7e"
1634
- )
1635
- };
1636
- var USDT_ADDRESSES = {
1637
- ethereum_mainnet: EvmContractAddress(
1638
- "0xdac17f958d2ee523a2206206994597c13d831ec7"
1639
- ),
1640
- ethereum_sepolia: EvmContractAddress(
1641
- "0x7169D38820dfd117C3FA1f22a697dBA58d90BA06"
1642
- ),
1643
- base_mainnet: EvmContractAddress(
1644
- "0xfde4C96c8593536E31F229EA8f37b2ADa2699bb2"
1645
- ),
1646
- base_sepolia: null
1647
- };
1648
- var TOKEN_REGISTRY = {
1649
- erc20: (symbol) => {
1650
- switch (symbol) {
1651
- case "USDC":
1652
- return USDC;
1653
- case "USDT":
1654
- return USDT;
1655
- default:
1656
- throw new InvariantError(`Unknown asset symbol: ${symbol}`);
1657
- }
1658
- },
1659
- /**
1660
- * USDC's contract on `chain`. USDC is deployed on every chain the SDK
1661
- * models, so the table is total and the answer is never `null`.
1662
- */
1663
- usdcAddress: (chain) => USDC_ADDRESSES[chain],
1664
- /**
1665
- * USDT's contract on `chain`, or `null` where Tether publishes none —
1666
- * Base Sepolia today. The honest answer, never a fake address a balance
1667
- * read would call.
1668
- */
1669
- usdtAddress: (chain) => USDT_ADDRESSES[chain]
1670
- };
1671
-
1672
- // src/universal/core/checkout/ondo/constants.ts
1673
- var ONDO_POLL_INTERVAL_MS = 15e3;
1674
- var ONDO_QUOTE_MAX_TTL_MS = 15e3;
1675
- var DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE = DecimalString("1000");
1676
- var ONDO_SETTLEMENT_ASSET = USDC_SYMBOL;
1677
- var DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE = 1;
1678
- var ONDO_SUPPORTED_INPUT_ASSETS = [
1679
- USDC_SYMBOL
1680
- ];
1681
-
1682
- // src/universal/core/checkout/ondo/math.ts
1683
- function computeOndoBuyPrice(transaction) {
1684
- const { notionalValue, receiveOutputAmount } = transaction;
1685
- return pricePerShare({
1686
- usd: notionalValue,
1687
- shares: receiveOutputAmount
1688
- });
1689
- }
1690
- function computeOndoSellPrice(transaction) {
1691
- const { expected, spendInputAmount } = transaction;
1692
- return pricePerShare({
1693
- usd: grossProceeds(expected),
1694
- shares: spendInputAmount
1695
- });
1696
- }
1697
- function ondoQuoteOfferDeadline(expiresAt, nowMs = Date.now()) {
1698
- return new Date(Math.min(expiresAt.getTime(), nowMs + ONDO_QUOTE_MAX_TTL_MS));
1699
- }
1700
- function grossProceeds(expected) {
1701
- const raw = expected.quantity.raw + expected.fee.raw;
1702
- if (raw > MAX_UINT_256) {
1703
- throw new MathError(`Ondo sell proceeds: out of uint256 bounds (${raw})`);
1704
- }
1705
- return BlockchainAmount.add(expected.quantity, expected.fee);
1706
- }
1707
- function pricePerShare({
1708
- usd,
1709
- shares
1710
- }) {
1711
- const price = BlockchainAmount.div(usd, shares);
1712
- return BlockchainAmount({
1713
- raw: assertPriceFits(price.raw),
1714
- decimals: price.decimals
1715
- });
1716
- }
1717
- function assertPriceFits(raw) {
1718
- try {
1719
- return assertUint256(raw);
1720
- } catch {
1721
- throw new MathError(`Ondo price: out of uint256 bounds (${raw})`);
1722
- }
1723
- }
1724
-
1725
- // src/universal/core/checkout/ondo/not-tradable.ts
1726
- var ONDO_NOT_TRADABLE_CODE = "not_tradable";
1727
- function isOndoNotTradableError(error) {
1728
- return apiErrorCode(error) === ONDO_NOT_TRADABLE_CODE;
1729
- }
1730
-
1731
- // src/universal/core/shared/blockchain/formatters.ts
1732
- var import_viem3 = require("viem");
1733
-
1734
- // src/universal/types/blockchain/ui.ts
1735
- var FormattedAmountUi = (value) => value;
1736
- var FormattedPercentUi = (value) => value;
1737
- var TxExplorerUrl = (value) => value;
1738
- var ShortenedWalletAddress = (value) => value;
1739
- var FormattedAmountAssetUi = (value) => value;
1740
- var AssetIconUrl = (value) => value;
1741
-
1742
- // src/universal/core/shared/blockchain/formatters.ts
1743
- function shortenAddress(address) {
1744
- const short = address.length > 10 ? `${address.slice(0, 6)}\u2026${address.slice(-4)}` : address;
1745
- return ShortenedWalletAddress(short);
1746
- }
1747
- function formatAmount(amount, locale, options) {
1748
- const decimal = formatRawAmount(amount);
1749
- let [integerPart, fractionPart = ""] = decimal.split(".");
1750
- const maxFractionDigits = options?.maxFractionDigits;
1751
- const minFractionDigits = Math.min(
1752
- options?.minFractionDigits ?? (maxFractionDigits !== void 0 ? maxFractionDigits : 2),
1753
- maxFractionDigits ?? amount.decimals,
1754
- amount.decimals
1755
- );
1756
- if (maxFractionDigits !== void 0 && fractionPart.length > maxFractionDigits) {
1757
- ({ integerPart, fractionPart } = roundFractionHalfUp(
1758
- integerPart,
1759
- fractionPart,
1760
- maxFractionDigits
1761
- ));
1762
- }
1763
- const trimmed = fractionPart.replace(/0+$/, "");
1764
- const fraction = trimmed.padEnd(minFractionDigits, "0");
1765
- const integerFormatted = BigInt(integerPart).toLocaleString(locale);
1766
- if (minFractionDigits === 0 && fraction === "") {
1767
- return FormattedAmountUi(integerFormatted);
1768
- }
1769
- const decimalSeparator = new Intl.NumberFormat(locale).formatToParts(1.1).find((p) => p.type === "decimal")?.value ?? ".";
1770
- return FormattedAmountUi(`${integerFormatted}${decimalSeparator}${fraction}`);
1771
- }
1772
- function roundFractionHalfUp(integerPart, fractionPart, maxFractionDigits) {
1773
- if (fractionPart.length <= maxFractionDigits) {
1774
- return { integerPart, fractionPart };
1775
- }
1776
- if (maxFractionDigits === 0) {
1777
- const roundUp = fractionPart[0] >= "5";
1778
- const integer = BigInt(integerPart) + (roundUp ? 1n : 0n);
1779
- return { integerPart: integer.toString(), fractionPart: "" };
1780
- }
1781
- const trimmed = fractionPart.slice(0, maxFractionDigits);
1782
- if (fractionPart[maxFractionDigits] < "5") {
1783
- return { integerPart, fractionPart: trimmed };
1784
- }
1785
- const digits = trimmed.split("").map((digit) => Number.parseInt(digit, 10));
1786
- let carry = 1;
1787
- for (let i = digits.length - 1; i >= 0 && carry > 0; i -= 1) {
1788
- const sum = digits[i] + carry;
1789
- if (sum === 10) {
1790
- digits[i] = 0;
1791
- carry = 1;
1792
- } else {
1793
- digits[i] = sum;
1794
- carry = 0;
1795
- }
1796
- }
1797
- return {
1798
- integerPart: carry > 0 ? (BigInt(integerPart) + 1n).toString() : integerPart,
1799
- fractionPart: digits.join("")
1800
- };
1801
- }
1802
- function formatRawAmount(amount) {
1803
- return (0, import_viem3.formatUnits)(amount.raw, amount.decimals);
1804
- }
1805
- function formatCompactAmount(amount, locale) {
1806
- const value = Number(formatRawAmount(amount));
1807
- const formatted = new Intl.NumberFormat(locale, {
1808
- notation: "compact",
1809
- maximumFractionDigits: 2
1810
- }).format(value);
1811
- return FormattedAmountUi(formatted);
1812
- }
1813
- function formatBpsAsPercent(bps, locale) {
1814
- const whole = bps / 100n;
1815
- const fraction = bps % 100n;
1816
- const wholeFormatted = whole.toLocaleString(locale);
1817
- const decimalSeparator = new Intl.NumberFormat(locale).formatToParts(1.1).find((p) => p.type === "decimal")?.value ?? ".";
1818
- if (fraction === 0n) {
1819
- return FormattedPercentUi(`${wholeFormatted}%`);
1820
- }
1821
- const fractionFormatted = fraction.toString().padStart(2, "0").replace(/0+$/, "");
1822
- return FormattedPercentUi(
1823
- `${wholeFormatted}${decimalSeparator}${fractionFormatted}%`
1824
- );
1825
- }
1826
- function usdAmount(amount) {
1827
- return FormattedAmountAssetUi(`$${amount}`);
1828
- }
1829
- function assetAmount(amount, symbol) {
1830
- return FormattedAmountAssetUi(`${amount} ${symbol}`);
1831
- }
1832
- var NA_AMOUNT_ASSET_UI = FormattedAmountAssetUi("-");
1833
- var SHARE_MAX_FRACTION_DIGITS = AssetDecimals(6);
1834
- var SHARE_MIN_FRACTION_DIGITS = AssetDecimals(2);
1835
- function formatShareAmount(amount, locale) {
1836
- return formatAmount(amount, locale, {
1837
- maxFractionDigits: SHARE_MAX_FRACTION_DIGITS,
1838
- minFractionDigits: SHARE_MIN_FRACTION_DIGITS
1839
- });
1840
- }
1841
- var USD_FRACTION_DIGITS = AssetDecimals(2);
1842
- function formattedUsdPrice(amount, locale) {
1843
- if (!amount) return NA_AMOUNT_ASSET_UI;
1844
- return usdAmount(
1845
- formatAmount(amount, locale, { maxFractionDigits: USD_FRACTION_DIGITS })
1846
- );
1847
- }
1848
-
1849
- // src/universal/core/shared/blockchain/chain.ts
1850
- var import_chains = require("viem/chains");
1851
- var VIEM_CHAINS = {
1852
- ethereum_mainnet: import_chains.mainnet,
1853
- ethereum_sepolia: import_chains.sepolia,
1854
- base_mainnet: import_chains.base,
1855
- base_sepolia: import_chains.baseSepolia
1856
- };
1857
- function viemChain(chain) {
1858
- return VIEM_CHAINS[chain];
1859
- }
1860
- function getChainId(chain) {
1861
- return VIEM_CHAINS[chain].id;
1862
- }
1863
- function chainFromId(chainId) {
1864
- const chains = Object.keys(VIEM_CHAINS);
1865
- const chain = chains.find((c) => String(VIEM_CHAINS[c].id) === chainId);
1866
- if (!chain) {
1867
- throw new ValidationError(`Unsupported EIP-155 chain id: "${chainId}"`);
1868
- }
1869
- return chain;
1870
- }
1871
- function getNetworkName(chain) {
1872
- switch (chain) {
1873
- case "ethereum_mainnet":
1874
- return "Ethereum";
1875
- case "ethereum_sepolia":
1876
- return "Ethereum Sepolia";
1877
- case "base_mainnet":
1878
- return "Base";
1879
- case "base_sepolia":
1880
- return "Base Sepolia";
1881
- default: {
1882
- const _exhaustive = chain;
1883
- return _exhaustive;
1884
- }
1885
- }
1886
- }
1887
- function txExplorerUrl(chain, txHash) {
1888
- return TxExplorerUrl(`${explorerBaseUrl(chain)}/tx/${txHash}`);
1889
- }
1890
- function explorerBaseUrl(chain) {
1891
- switch (chain) {
1892
- case "ethereum_mainnet":
1893
- return "https://etherscan.io";
1894
- case "ethereum_sepolia":
1895
- return "https://sepolia.etherscan.io";
1896
- case "base_mainnet":
1897
- return "https://basescan.org";
1898
- case "base_sepolia":
1899
- return "https://sepolia-explorer.base.org";
1900
- default: {
1901
- const _exhaustive = chain;
1902
- return _exhaustive;
1903
- }
1904
- }
1905
- }
1906
-
1907
- // src/universal/types/providers/ondo/ondo.ts
1908
- var OndoTradingStatus = {
1909
- fromDto: (dto) => {
1910
- if (!dto.tradable) return { type: "not-tradable", side: dto.side };
1911
- return {
1912
- type: "tradable",
1913
- side: dto.side,
1914
- grossMaxTokens: decimalOrNull(dto.gross_max_tokens),
1915
- grossMaxNotionalValue: decimalOrNull(dto.gross_max_notional_value),
1916
- grossMaxActiveNotionalValue: decimalOrNull(
1917
- dto.gross_max_active_notional_value
1918
- )
1919
- };
1920
- }
1921
- };
1922
- var OndoQuote = {
1923
- fromDto: (dto) => {
1924
- const assetDecimals = AssetDecimals(dto.asset_decimals);
1925
- return {
1926
- chain: chainFromId(dto.chain_id),
1927
- ticker: Ticker(dto.ticker),
1928
- assetAddress: EvmContractAddress(dto.asset_address),
1929
- asset: {
1930
- name: dto.ticker,
1931
- symbol: AssetSymbol(dto.symbol),
1932
- decimals: assetDecimals
1933
- },
1934
- side: dto.side,
1935
- tokenBaseUnits: blockchainAmountFromRawOrThrow({
1936
- label: "tokenBaseUnits",
1937
- raw: dto.token_base_units,
1938
- decimals: assetDecimals
1939
- }),
1940
- price: DecimalString(dto.price)
1941
- };
1942
- }
1943
- };
1944
- var OndoBuyTransaction = {
1945
- fromDto: (dto) => {
1946
- const spendDecimals = AssetDecimals(dto.spend_input_decimals);
1947
- const outputDecimals = AssetDecimals(dto.receive_output_decimals);
1948
- return {
1949
- ...parseSwapCore(dto, spendDecimals),
1950
- side: "buy",
1951
- fee: blockchainAmountFromRawOrThrow({
1952
- label: "fee",
1953
- raw: dto.fee,
1954
- decimals: spendDecimals
1955
- }),
1956
- notionalValue: blockchainAmountFromRawOrThrow({
1957
- label: "notional_value",
1958
- raw: dto.notional_value,
1959
- decimals: spendDecimals
1960
- }),
1961
- receiveOutputAmount: parsePositiveAmount({
1962
- label: "receive_output_amount",
1963
- raw: dto.receive_output_amount,
1964
- decimals: outputDecimals,
1965
- // A transaction that yields nothing is not one to sign - the user
1966
- // would pay the deposit and receive no asset - and frontline refuses
1967
- // to emit one. A zero here is a changed encoding, not a small order.
1968
- // Rejecting it at the boundary is also what lets `computeOndoBuyPrice`
1969
- // divide by it without a fallible result: the failure surfaces as the
1970
- // data hook's ERROR state rather than as a division during render.
1971
- reason: "a buy that yields nothing is not fillable"
1972
- })
1973
- };
1974
- }
1975
- };
1976
- var OndoSellTransaction = {
1977
- fromDto: (dto) => {
1978
- const spendDecimals = AssetDecimals(dto.spend_input_decimals);
1979
- const outputDecimals = AssetDecimals(dto.receive_output_decimals);
1980
- const expectedQuantity = parsePositiveAmount({
1981
- label: "expected_quantity",
1982
- raw: dto.expected_quantity,
1983
- decimals: outputDecimals,
1984
- reason: "a sale that yields nothing is not fillable"
1985
- });
1986
- return {
1987
- ...parseSwapCore(dto, spendDecimals),
1988
- side: "sell",
1989
- expected: {
1990
- quantity: expectedQuantity,
1991
- fee: blockchainAmountFromRawOrThrow({
1992
- label: "expected_fee",
1993
- raw: dto.expected_fee,
1994
- decimals: outputDecimals
1995
- })
1996
- },
1997
- minimum: {
1998
- quantity: parseMinimumQuantity(
1999
- dto.minimum_quantity,
2000
- outputDecimals,
2001
- expectedQuantity
2002
- ),
2003
- fee: blockchainAmountFromRawOrThrow({
2004
- label: "minimum_fee",
2005
- raw: dto.minimum_fee,
2006
- decimals: outputDecimals
2007
- })
2008
- }
2009
- };
2010
- }
2011
- };
2012
- function parseSwapCore(dto, spendDecimals) {
2013
- return {
2014
- tx: {
2015
- to: EvmContractAddress(dto.to),
2016
- data: HexEncodedTransactionData(dto.data)
2017
- },
2018
- expiresAt: parseExpiresAt(dto.expires_at),
2019
- spendInputAmount: parsePositiveAmount({
2020
- label: "spend_input_amount",
2021
- raw: dto.spend_input_amount,
2022
- decimals: spendDecimals,
2023
- // A transaction that takes nothing from the wallet is not one to sign:
2024
- // it would settle one leg of a trade and skip the other. Frontline
2025
- // refuses an `amount` of zero whichever way the trade runs, so this is a
2026
- // changed encoding rather than a small order.
2027
- //
2028
- // Guarded on both sides rather than on the sale alone, because which
2029
- // amount becomes the divisor in the price flips with the direction: a
2030
- // guard placed by that would be a rule about the arithmetic rather than
2031
- // about the trade.
2032
- reason: "a swap that spends nothing is not fillable"
2033
- })
2034
- };
2035
- }
2036
- function parseMinimumQuantity(raw, decimals, expectedQuantity) {
2037
- const amount = parsePositiveAmount({
2038
- label: "minimum_quantity",
2039
- raw,
2040
- decimals,
2041
- reason: "a floor of zero guarantees nothing"
2042
- });
2043
- if (amount.raw > expectedQuantity.raw) {
2044
- throw new ValidationError(
2045
- `minimum_quantity: must not exceed expected_quantity ("${raw}" > "${expectedQuantity.raw}")`
2046
- );
2047
- }
2048
- return amount;
2049
- }
2050
- function parsePositiveAmount({
2051
- label,
2052
- raw,
2053
- decimals,
2054
- reason
2055
- }) {
2056
- const amount = blockchainAmountFromRawOrThrow({ label, raw, decimals });
2057
- if (amount.raw <= 0n) {
2058
- throw new ValidationError(
2059
- `${label}: must be greater than zero ("${raw}") - ${reason}`
2060
- );
2061
- }
2062
- return amount;
2063
- }
2064
- function parseExpiresAt(value) {
2065
- const date = new Date(value);
2066
- if (Number.isNaN(date.getTime())) {
2067
- throw new ValidationError(`expires_at: not a date ("${value}")`);
2068
- }
2069
- return date;
2070
- }
2071
-
2072
- // src/universal/api/frontline/providers/ondo/ondo.ts
2073
- async function getOndoTradingStatus(api, params) {
2074
- const dto = await api.send({
2075
- method: "GET",
2076
- url: "/v1/ondo/swap/trading-status",
2077
- queryParams: { symbol: params.symbol, side: params.side },
2078
- attributes: Attributes.protected()
2079
- });
2080
- return OndoTradingStatus.fromDto(dto);
2081
- }
2082
- async function getOndoQuote(api, params) {
2083
- const dto = await api.send({
2084
- method: "GET",
2085
- url: "/v1/ondo/swap/quote",
2086
- queryParams: {
2087
- symbol: params.symbol,
2088
- side: params.side,
2089
- duration: params.duration,
2090
- ...sizeParam(params)
2091
- },
2092
- attributes: Attributes.protected()
2093
- });
2094
- return OndoQuote.fromDto(dto);
2095
- }
2096
- async function buildOndoBuy(api, params) {
2097
- const dto = await api.send({
2098
- method: "POST",
2099
- url: "/v1/ondo/swap/buy",
2100
- body: swapBody(params),
2101
- attributes: Attributes.protected()
2102
- });
2103
- assertSpendScaleAgrees({
2104
- published: dto.spend_input_decimals,
2105
- sized: params.amount,
2106
- trade: "purchase"
2107
- });
2108
- return OndoBuyTransaction.fromDto(dto);
2109
- }
2110
- async function buildOndoSell(api, params) {
2111
- const dto = await api.send({
2112
- method: "POST",
2113
- url: "/v1/ondo/swap/sell",
2114
- body: swapBody(params),
2115
- attributes: Attributes.protected()
2116
- });
2117
- assertSpendScaleAgrees({
2118
- published: dto.spend_input_decimals,
2119
- sized: params.amount,
2120
- trade: "sale",
2121
- // The two answers come from two chains, so on a testnet they can disagree
2122
- // for a reason that is neither the caller's nor a corrupt response. Say so,
2123
- // or a QA run reads as a puzzle rather than a diagnosis.
2124
- 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"
2125
- });
2126
- return OndoSellTransaction.fromDto(dto);
2127
- }
2128
- function swapBody(params) {
2129
- return {
2130
- symbol: params.symbol,
2131
- chain: params.chain,
2132
- wallet_address: params.walletAddress,
2133
- amount: params.amount.raw.toString()
2134
- };
2135
- }
2136
- function assertSpendScaleAgrees({
2137
- published,
2138
- sized,
2139
- trade,
2140
- note
2141
- }) {
2142
- if (published === sized.decimals) return;
2143
- const because = note === void 0 ? "" : ` - ${note}`;
2144
- throw new ValidationError(
2145
- `spend_input_decimals: the ${trade} was priced in ${published} decimals but the order was sized in ${sized.decimals}${because}`
2146
- );
2147
- }
2148
- function sizeParam(params) {
2149
- const tokenAmount = "tokenAmount" in params ? params.tokenAmount : void 0;
2150
- const notionalValue = "notionalValue" in params ? params.notionalValue : void 0;
2151
- if (tokenAmount !== void 0) {
2152
- if (notionalValue !== void 0) {
2153
- throw new ValidationError(
2154
- "An Ondo quote takes tokenAmount or notionalValue, not both"
2155
- );
2156
- }
2157
- return { token_amount: formatRawAmount(tokenAmount) };
2158
- }
2159
- if (notionalValue === void 0) {
2160
- throw new ValidationError(
2161
- "An Ondo quote must be sized by tokenAmount or notionalValue"
2162
- );
2163
- }
2164
- return { notional_value: notionalValue };
2165
- }
2166
-
2167
- // src/universal/core/checkout/ondo/ondo-namespace.ts
2168
- var OndoNamespaceImpl = class {
2169
- constructor(ctx) {
2170
- this.ctx = ctx;
2171
- this.log = internalLogger(ctx.logger, "ONDO");
2172
- }
2173
- async getTradingStatus(params) {
2174
- return this.log.wrap("getTradingStatus", params, async () => {
2175
- await this.ctx.ensureUserAuthenticated();
2176
- return getOndoTradingStatus(this.ctx.api, params);
2177
- });
2178
- }
2179
- async getQuote(params) {
2180
- return this.log.wrap("getQuote", params, async () => {
2181
- await this.ctx.ensureUserAuthenticated();
2182
- return getOndoQuote(this.ctx.api, params);
2183
- });
2184
- }
2185
- async buildBuyTransaction(params) {
2186
- return this.log.wrap("buildBuyTransaction", params, async () => {
2187
- await this.ctx.ensureUserAuthenticated();
2188
- return buildOndoBuy(this.ctx.api, params);
2189
- });
2190
- }
2191
- async buildSellTransaction(params) {
2192
- return this.log.wrap("buildSellTransaction", params, async () => {
2193
- await this.ctx.ensureUserAuthenticated();
2194
- return buildOndoSell(this.ctx.api, params);
2195
- });
2196
- }
2197
- };
2198
-
2199
- // src/universal/core/checkout/superstate/blockchain/abi.ts
2200
- var SUPERSTATE_SWAP_ABI = [
2201
- {
2202
- type: "function",
2203
- name: "KIND",
2204
- inputs: [],
2205
- outputs: [
2206
- {
2207
- name: "",
2208
- type: "uint16",
2209
- internalType: "uint16"
2210
- }
2211
- ],
2212
- stateMutability: "view"
2213
- },
2214
- {
2215
- type: "function",
2216
- name: "ONE_HUNDRED_P",
2217
- inputs: [],
2218
- outputs: [
2219
- {
2220
- name: "",
2221
- type: "uint256",
2222
- internalType: "uint256"
2223
- }
2224
- ],
2225
- stateMutability: "view"
2226
- },
2227
- {
2228
- type: "function",
2229
- name: "SWAP_LEVEL",
2230
- inputs: [],
2231
- outputs: [
2232
- {
2233
- name: "",
2234
- type: "uint32",
2235
- internalType: "uint32"
2236
- }
2237
- ],
2238
- stateMutability: "view"
2239
- },
2240
- {
2241
- type: "function",
2242
- name: "VERSION",
2243
- inputs: [],
2244
- outputs: [
2245
- {
2246
- name: "",
2247
- type: "uint16",
2248
- internalType: "uint16"
2249
- }
2250
- ],
2251
- stateMutability: "view"
2252
- },
2253
- {
2254
- type: "function",
2255
- name: "authorized",
2256
- inputs: [
2257
- {
2258
- name: "user",
2259
- type: "address",
2260
- internalType: "address"
2261
- }
2262
- ],
2263
- outputs: [
2264
- {
2265
- name: "",
2266
- type: "bool",
2267
- internalType: "bool"
2268
- }
2269
- ],
2270
- stateMutability: "view"
2271
- },
2272
- {
2273
- type: "function",
2274
- name: "bpp",
2275
- inputs: [
2276
- {
2277
- name: "amount",
2278
- type: "uint256",
2279
- internalType: "uint256"
2280
- }
2281
- ],
2282
- outputs: [
2283
- {
2284
- name: "",
2285
- type: "uint256",
2286
- internalType: "uint256"
2287
- }
2288
- ],
2289
- stateMutability: "view"
2290
- },
2291
- {
2292
- type: "function",
2293
- name: "bps",
2294
- inputs: [],
2295
- outputs: [
2296
- {
2297
- name: "",
2298
- type: "uint256",
2299
- internalType: "uint256"
2300
- }
2301
- ],
2302
- stateMutability: "view"
2303
- },
2304
- {
2305
- type: "function",
2306
- name: "cancelOwnershipHandover",
2307
- inputs: [],
2308
- outputs: [],
2309
- stateMutability: "payable"
2310
- },
2311
- {
2312
- type: "function",
2313
- name: "completeOwnershipHandover",
2314
- inputs: [
2315
- {
2316
- name: "pendingOwner",
2317
- type: "address",
2318
- internalType: "address"
2319
- }
2320
- ],
2321
- outputs: [],
2322
- stateMutability: "payable"
2323
- },
2324
- {
2325
- type: "function",
2326
- name: "fee",
2327
- inputs: [
2328
- {
2329
- name: "amount",
2330
- type: "uint256",
2331
- internalType: "uint256"
2332
- }
2333
- ],
2334
- outputs: [
2335
- {
2336
- name: "",
2337
- type: "uint256",
2338
- internalType: "uint256"
2339
- },
2340
- {
2341
- name: "",
2342
- type: "uint256",
2343
- internalType: "uint256"
2344
- }
2345
- ],
2346
- stateMutability: "view"
2347
- },
2348
- {
2349
- type: "function",
2350
- name: "id",
2351
- inputs: [],
2352
- outputs: [
2353
- {
2354
- name: "",
2355
- type: "bytes32",
2356
- internalType: "bytes32"
2357
- }
2358
- ],
2359
- stateMutability: "view"
2360
- },
2361
- {
2362
- type: "function",
2363
- name: "inputTokens",
2364
- inputs: [
2365
- {
2366
- name: "",
2367
- type: "address",
2368
- internalType: "address"
2369
- }
2370
- ],
2371
- outputs: [
2372
- {
2373
- name: "",
2374
- type: "bool",
2375
- internalType: "bool"
2376
- }
2377
- ],
2378
- stateMutability: "view"
2379
- },
2380
- {
2381
- type: "function",
2382
- name: "outputToken",
2383
- inputs: [],
2384
- outputs: [
2385
- {
2386
- name: "",
2387
- type: "address",
2388
- internalType: "address"
2389
- }
2390
- ],
2391
- stateMutability: "view"
2392
- },
2393
- {
2394
- type: "function",
2395
- name: "outputTokenBalance",
2396
- inputs: [],
2397
- outputs: [
2398
- {
2399
- name: "",
2400
- type: "uint256",
2401
- internalType: "uint256"
2402
- }
2403
- ],
2404
- stateMutability: "view"
2405
- },
2406
- {
2407
- type: "function",
2408
- name: "owner",
2409
- inputs: [],
2410
- outputs: [
2411
- {
2412
- name: "result",
2413
- type: "address",
2414
- internalType: "address"
2415
- }
2416
- ],
2417
- stateMutability: "view"
2418
- },
2419
- {
2420
- type: "function",
2421
- name: "ownershipHandoverExpiresAt",
2422
- inputs: [
2423
- {
2424
- name: "pendingOwner",
2425
- type: "address",
2426
- internalType: "address"
2427
- }
2428
- ],
2429
- outputs: [
2430
- {
2431
- name: "result",
2432
- type: "uint256",
2433
- internalType: "uint256"
2434
- }
2435
- ],
2436
- stateMutability: "view"
2437
- },
2438
- {
2439
- type: "function",
2440
- name: "pause",
2441
- inputs: [
2442
- {
2443
- name: "level",
2444
- type: "uint32",
2445
- internalType: "uint32"
2446
- }
2447
- ],
2448
- outputs: [
2449
- {
2450
- name: "",
2451
- type: "bool",
2452
- internalType: "bool"
2453
- }
2454
- ],
2455
- stateMutability: "nonpayable"
2456
- },
2457
- {
2458
- type: "function",
2459
- name: "paused",
2460
- inputs: [],
2461
- outputs: [
2462
- {
2463
- name: "",
2464
- type: "uint32",
2465
- internalType: "uint32"
2466
- }
2467
- ],
2468
- stateMutability: "view"
2469
- },
2470
- {
2471
- type: "function",
2472
- name: "preview",
2473
- inputs: [
2474
- {
2475
- name: "token",
2476
- type: "address",
2477
- internalType: "address"
2478
- },
2479
- {
2480
- name: "amount",
2481
- type: "uint256",
2482
- internalType: "uint256"
2483
- }
2484
- ],
2485
- outputs: [
2486
- {
2487
- name: "",
2488
- type: "tuple",
2489
- internalType: "struct Preview",
2490
- components: [
2491
- {
2492
- name: "input",
2493
- type: "uint256",
2494
- internalType: "uint256"
2495
- },
2496
- {
2497
- name: "fee",
2498
- type: "uint256",
2499
- internalType: "uint256"
2500
- },
2501
- {
2502
- name: "output",
2503
- type: "uint256",
2504
- internalType: "uint256"
2505
- }
2506
- ]
2507
- }
2508
- ],
2509
- stateMutability: "view"
2510
- },
2511
- {
2512
- type: "function",
2513
- name: "renounceOwnership",
2514
- inputs: [],
2515
- outputs: [],
2516
- stateMutability: "payable"
2517
- },
2518
- {
2519
- type: "function",
2520
- name: "requestOwnershipHandover",
2521
- inputs: [],
2522
- outputs: [],
2523
- stateMutability: "payable"
2524
- },
2525
- {
2526
- type: "function",
2527
- name: "setBps",
2528
- inputs: [
2529
- {
2530
- name: "points",
2531
- type: "uint256",
2532
- internalType: "uint256"
2533
- }
2534
- ],
2535
- outputs: [
2536
- {
2537
- name: "",
2538
- type: "bool",
2539
- internalType: "bool"
2540
- }
2541
- ],
2542
- stateMutability: "nonpayable"
2543
- },
2544
- {
2545
- type: "function",
2546
- name: "setInputToken",
2547
- inputs: [
2548
- {
2549
- name: "token",
2550
- type: "address",
2551
- internalType: "address"
2552
- },
2553
- {
2554
- name: "val",
2555
- type: "bool",
2556
- internalType: "bool"
2557
- }
2558
- ],
2559
- outputs: [
2560
- {
2561
- name: "",
2562
- type: "bool",
2563
- internalType: "bool"
2564
- }
2565
- ],
2566
- stateMutability: "nonpayable"
2567
- },
2568
- {
2569
- type: "function",
2570
- name: "status",
2571
- inputs: [],
2572
- outputs: [
2573
- {
2574
- name: "",
2575
- type: "tuple",
2576
- internalType: "struct Status",
2577
- components: [
2578
- {
2579
- name: "flags",
2580
- type: "uint32",
2581
- internalType: "uint32"
2582
- },
2583
- {
2584
- name: "state",
2585
- type: "uint8",
2586
- internalType: "enum State"
2587
- }
2588
- ]
2589
- }
2590
- ],
2591
- stateMutability: "view"
2592
- },
2593
- {
2594
- type: "function",
2595
- name: "stop",
2596
- inputs: [],
2597
- outputs: [
2598
- {
2599
- name: "",
2600
- type: "bool",
2601
- internalType: "bool"
2602
- }
2603
- ],
2604
- stateMutability: "nonpayable"
2605
- },
2606
- {
2607
- type: "function",
2608
- name: "stopped",
2609
- inputs: [],
2610
- outputs: [
2611
- {
2612
- name: "",
2613
- type: "bool",
2614
- internalType: "bool"
2615
- }
2616
- ],
2617
- stateMutability: "view"
2618
- },
2619
- {
2620
- type: "function",
2621
- name: "swap",
2622
- inputs: [
2623
- {
2624
- name: "token",
2625
- type: "address",
2626
- internalType: "address"
2627
- },
2628
- {
2629
- name: "amount",
2630
- type: "uint256",
2631
- internalType: "uint256"
2632
- },
2633
- {
2634
- name: "slip",
2635
- type: "uint256",
2636
- internalType: "uint256"
2637
- }
2638
- ],
2639
- outputs: [
2640
- {
2641
- name: "",
2642
- type: "uint256",
2643
- internalType: "uint256"
2644
- }
2645
- ],
2646
- stateMutability: "nonpayable"
2647
- },
2648
- {
2649
- type: "function",
2650
- name: "tokenBalance",
2651
- inputs: [
2652
- {
2653
- name: "token",
2654
- type: "address",
2655
- internalType: "address"
2656
- }
2657
- ],
2658
- outputs: [
2659
- {
2660
- name: "",
2661
- type: "uint256",
2662
- internalType: "uint256"
2663
- }
2664
- ],
2665
- stateMutability: "view"
2666
- },
2667
- {
2668
- type: "function",
2669
- name: "totals",
2670
- inputs: [
2671
- {
2672
- name: "user",
2673
- type: "address",
2674
- internalType: "address"
2675
- },
2676
- {
2677
- name: "token",
2678
- type: "address",
2679
- internalType: "address"
2680
- }
2681
- ],
2682
- outputs: [
2683
- {
2684
- name: "",
2685
- type: "tuple",
2686
- internalType: "struct SwapTotal",
2687
- components: [
2688
- {
2689
- name: "inputSum",
2690
- type: "uint256",
2691
- internalType: "uint256"
2692
- },
2693
- {
2694
- name: "feeSum",
2695
- type: "uint256",
2696
- internalType: "uint256"
2697
- },
2698
- {
2699
- name: "outputSum",
2700
- type: "uint256",
2701
- internalType: "uint256"
2702
- },
2703
- {
2704
- name: "count",
2705
- type: "uint256",
2706
- internalType: "uint256"
2707
- }
2708
- ]
2709
- }
2710
- ],
2711
- stateMutability: "view"
2712
- },
2713
- {
2714
- type: "function",
2715
- name: "totals",
2716
- inputs: [
2717
- {
2718
- name: "token",
2719
- type: "address",
2720
- internalType: "address"
2721
- }
2722
- ],
2723
- outputs: [
2724
- {
2725
- name: "",
2726
- type: "tuple",
2727
- internalType: "struct SwapTotal",
2728
- components: [
2729
- {
2730
- name: "inputSum",
2731
- type: "uint256",
2732
- internalType: "uint256"
2733
- },
2734
- {
2735
- name: "feeSum",
2736
- type: "uint256",
2737
- internalType: "uint256"
2738
- },
2739
- {
2740
- name: "outputSum",
2741
- type: "uint256",
2742
- internalType: "uint256"
2743
- },
2744
- {
2745
- name: "count",
2746
- type: "uint256",
2747
- internalType: "uint256"
2748
- }
2749
- ]
2750
- }
2751
- ],
2752
- stateMutability: "view"
2753
- },
2754
- {
2755
- type: "function",
2756
- name: "transfer",
2757
- inputs: [
2758
- {
2759
- name: "to",
2760
- type: "address",
2761
- internalType: "address"
2762
- },
2763
- {
2764
- name: "amount",
2765
- type: "uint256",
2766
- internalType: "uint256"
2767
- }
2768
- ],
2769
- outputs: [
2770
- {
2771
- name: "",
2772
- type: "bool",
2773
- internalType: "bool"
2774
- }
2775
- ],
2776
- stateMutability: "nonpayable"
2777
- },
2778
- {
2779
- type: "function",
2780
- name: "transfer",
2781
- inputs: [
2782
- {
2783
- name: "to",
2784
- type: "address",
2785
- internalType: "address"
2786
- },
2787
- {
2788
- name: "token",
2789
- type: "address",
2790
- internalType: "address"
2791
- },
2792
- {
2793
- name: "amount",
2794
- type: "uint256",
2795
- internalType: "uint256"
2796
- }
2797
- ],
2798
- outputs: [
2799
- {
2800
- name: "",
2801
- type: "bool",
2802
- internalType: "bool"
2803
- }
2804
- ],
2805
- stateMutability: "nonpayable"
2806
- },
2807
- {
2808
- type: "function",
2809
- name: "transferOwnership",
2810
- inputs: [
2811
- {
2812
- name: "newOwner",
2813
- type: "address",
2814
- internalType: "address"
2815
- }
2816
- ],
2817
- outputs: [],
2818
- stateMutability: "payable"
2819
- },
2820
- {
2821
- type: "event",
2822
- name: "BpsUpdated",
2823
- inputs: [
2824
- {
2825
- name: "prev",
2826
- type: "uint256",
2827
- indexed: false,
2828
- internalType: "uint256"
2829
- },
2830
- {
2831
- name: "next",
2832
- type: "uint256",
2833
- indexed: false,
2834
- internalType: "uint256"
2835
- }
2836
- ],
2837
- anonymous: false
2838
- },
2839
- {
2840
- type: "event",
2841
- name: "InputTokenUpdated",
2842
- inputs: [
2843
- {
2844
- name: "token",
2845
- type: "address",
2846
- indexed: true,
2847
- internalType: "address"
2848
- },
2849
- {
2850
- name: "prev",
2851
- type: "bool",
2852
- indexed: false,
2853
- internalType: "bool"
2854
- },
2855
- {
2856
- name: "next",
2857
- type: "bool",
2858
- indexed: false,
2859
- internalType: "bool"
2860
- }
2861
- ],
2862
- anonymous: false
2863
- },
2864
- {
2865
- type: "event",
2866
- name: "OwnershipHandoverCanceled",
2867
- inputs: [
2868
- {
2869
- name: "pendingOwner",
2870
- type: "address",
2871
- indexed: true,
2872
- internalType: "address"
2873
- }
2874
- ],
2875
- anonymous: false
2876
- },
2877
- {
2878
- type: "event",
2879
- name: "OwnershipHandoverRequested",
2880
- inputs: [
2881
- {
2882
- name: "pendingOwner",
2883
- type: "address",
2884
- indexed: true,
2885
- internalType: "address"
2886
- }
2887
- ],
2888
- anonymous: false
2889
- },
2890
- {
2891
- type: "event",
2892
- name: "OwnershipTransferred",
2893
- inputs: [
2894
- {
2895
- name: "oldOwner",
2896
- type: "address",
2897
- indexed: true,
2898
- internalType: "address"
2899
- },
2900
- {
2901
- name: "newOwner",
2902
- type: "address",
2903
- indexed: true,
2904
- internalType: "address"
2905
- }
2906
- ],
2907
- anonymous: false
2908
- },
2909
- {
2910
- type: "event",
2911
- name: "Paused",
2912
- inputs: [
2913
- {
2914
- name: "previous",
2915
- type: "uint32",
2916
- indexed: false,
2917
- internalType: "uint32"
2918
- },
2919
- {
2920
- name: "next",
2921
- type: "uint32",
2922
- indexed: false,
2923
- internalType: "uint32"
2924
- }
2925
- ],
2926
- anonymous: false
2927
- },
2928
- {
2929
- type: "event",
2930
- name: "Stopped",
2931
- inputs: [],
2932
- anonymous: false
2933
- },
2934
- {
2935
- type: "event",
2936
- name: "Swapped",
2937
- inputs: [
2938
- {
2939
- name: "user",
2940
- type: "address",
2941
- indexed: true,
2942
- internalType: "address"
2943
- },
2944
- {
2945
- name: "inputToken",
2946
- type: "address",
2947
- indexed: true,
2948
- internalType: "address"
2949
- },
2950
- {
2951
- name: "outputToken",
2952
- type: "address",
2953
- indexed: true,
2954
- internalType: "address"
2955
- },
2956
- {
2957
- name: "inputAmount",
2958
- type: "uint256",
2959
- indexed: false,
2960
- internalType: "uint256"
2961
- },
2962
- {
2963
- name: "fee",
2964
- type: "uint256",
2965
- indexed: false,
2966
- internalType: "uint256"
2967
- },
2968
- {
2969
- name: "outputAmount",
2970
- type: "uint256",
2971
- indexed: false,
2972
- internalType: "uint256"
2973
- }
2974
- ],
2975
- anonymous: false
2976
- },
2977
- {
2978
- type: "event",
2979
- name: "Transferred",
2980
- inputs: [
2981
- {
2982
- name: "to",
2983
- type: "address",
2984
- indexed: true,
2985
- internalType: "address"
2986
- },
2987
- {
2988
- name: "token",
2989
- type: "address",
2990
- indexed: true,
2991
- internalType: "address"
2992
- },
2993
- {
2994
- name: "amount",
2995
- type: "uint256",
2996
- indexed: false,
2997
- internalType: "uint256"
2998
- }
2999
- ],
3000
- anonymous: false
3001
- },
3002
- {
3003
- type: "error",
3004
- name: "AlreadyInitialized",
3005
- inputs: []
3006
- },
3007
- {
3008
- type: "error",
3009
- name: "InsufficientAmount",
3010
- inputs: []
3011
- },
3012
- {
3013
- type: "error",
3014
- name: "InvalidAddress",
3015
- inputs: []
3016
- },
3017
- {
3018
- type: "error",
3019
- name: "InvalidAmount",
3020
- inputs: []
3021
- },
3022
- {
3023
- type: "error",
3024
- name: "IsPaused",
3025
- inputs: [
3026
- {
3027
- name: "level",
3028
- type: "uint32",
3029
- internalType: "uint32"
3030
- }
3031
- ]
3032
- },
3033
- {
3034
- type: "error",
3035
- name: "IsStopped",
3036
- inputs: []
3037
- },
3038
- {
3039
- type: "error",
3040
- name: "NewOwnerIsZeroAddress",
3041
- inputs: []
3042
- },
3043
- {
3044
- type: "error",
3045
- name: "NoHandoverRequest",
3046
- inputs: []
3047
- },
3048
- {
3049
- type: "error",
3050
- name: "SwapFailed",
3051
- inputs: [
3052
- {
3053
- name: "user",
3054
- type: "address",
3055
- internalType: "address"
3056
- },
3057
- {
3058
- name: "token",
3059
- type: "address",
3060
- internalType: "address"
3061
- }
3062
- ]
3063
- },
3064
- {
3065
- type: "error",
3066
- name: "Unauthorized",
3067
- inputs: []
3068
- }
3069
- ];
3070
-
3071
- // src/universal/core/shared/blockchain/bps.ts
3072
- var BPS_DENOM = Bps(10000n);
3073
- function applyBps(amount, bps) {
3074
- return assertUint256(amount * bps / BPS_DENOM);
3075
- }
3076
-
3077
- // src/universal/core/checkout/superstate/blockchain/math.ts
3078
- function computePrice({
3079
- inputTokenAmount,
3080
- outputTokenAmount
3081
- }) {
3082
- if (outputTokenAmount.raw === 0n) return null;
3083
- const scale = 10n ** BigInt(outputTokenAmount.decimals);
3084
- const raw = assertUint256(
3085
- inputTokenAmount.raw * scale / outputTokenAmount.raw
3086
- );
3087
- return BlockchainAmount({ raw, decimals: inputTokenAmount.decimals });
3088
- }
3089
- function computeSlip(amount, slippage) {
3090
- const retained = Bps(assertUint256(BPS_DENOM - slippage));
3091
- const slipRaw = applyBps(amount.raw, retained);
3092
- return BlockchainAmount({ raw: slipRaw, decimals: amount.decimals });
3093
- }
3094
-
3095
- // src/universal/core/checkout/superstate/blockchain/quote.ts
3096
- var SwapQuote = {
3097
- /**
3098
- * Assembles a {@link SwapQuote} from a raw contract {@link SwapPreview}. The
3099
- * input and fee are denominated in the input token; the output in the output
3100
- * token.
3101
- */
3102
- fromPreview: (preview, inputDecimals, outputDecimals) => ({
3103
- inputTokenAmount: BlockchainAmount({
3104
- raw: preview.inputAmount,
3105
- decimals: inputDecimals
3106
- }),
3107
- fee: BlockchainAmount({ raw: preview.fee, decimals: inputDecimals }),
3108
- outputTokenAmount: BlockchainAmount({
3109
- raw: preview.outputAmount,
3110
- decimals: outputDecimals
3111
- })
3112
- })
3113
- };
3114
-
3115
- // src/universal/core/checkout/superstate/blockchain/status.ts
3116
- var SWAP_LEVEL = 2;
3117
- function isSwapAvailable(status) {
3118
- switch (status.state) {
3119
- case "active":
3120
- return true;
3121
- case "stopped":
3122
- return false;
3123
- case "paused":
3124
- return (status.pausedLevels & SWAP_LEVEL) === 0;
3125
- default: {
3126
- const _exhaustive = status;
3127
- return _exhaustive;
3128
- }
3129
- }
3130
- }
3131
-
3132
- // src/universal/core/checkout/superstate/blockchain/swapped-event.ts
3133
- var import_viem4 = require("viem");
3134
- function decodeSwappedOutputAmount(receipt, outputDecimals) {
3135
- try {
3136
- const [swapped] = (0, import_viem4.parseEventLogs)({
3137
- abi: SUPERSTATE_SWAP_ABI,
3138
- eventName: "Swapped",
3139
- logs: receipt.logs
3140
- });
3141
- if (!swapped) return null;
3142
- const raw = swapped.args.outputAmount;
3143
- if (raw < 0n || raw > MAX_UINT_256) return null;
3144
- return BlockchainAmount({ raw, decimals: outputDecimals });
3145
- } catch {
3146
- return null;
3147
- }
3148
- }
3149
-
3150
- // src/universal/core/checkout/superstate/constants.ts
3151
- var SUPERSTATE_ISSUER_NAME = "Superstate";
3152
- var SUPERSTATE_SUPPORTED_INPUT_ASSETS = [USDC_SYMBOL];
3153
- var SWAP_POLL_INTERVAL_MS = 15e3;
3154
- var DEFAULT_AMOUNT_TO_COMPUTE_PRICE = 1000000n;
3155
- var SLIPPAGE_OPTIONS_BPS = [25n, 50n, 100n, 200n, 500n].map(
3156
- (n) => Bps(n)
3157
- );
3158
- var DEFAULT_SLIPPAGE_BPS = Bps(50n);
3159
- var SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA = EvmContractAddress("0x27E8CE9Ca1A1E98Bc4009F08Dc596bFcf88aCED1");
3160
- var SUPERSTATE_SWAP_CONTRACT_ADDRESSES = {
3161
- ethereum_sepolia: SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA
3162
- };
3163
- function superstateSwapContractAddress(chain) {
3164
- return SUPERSTATE_SWAP_CONTRACT_ADDRESSES[chain] ?? null;
3165
- }
3166
-
3167
- // src/universal/core/checkout/superstate/formatters.ts
3168
- function formattedPricePerShare(quote, locale) {
3169
- if (!quote) return NA_AMOUNT_ASSET_UI;
3170
- return formattedUsdPrice(computePrice(quote), locale);
3171
- }
3172
-
3173
- // src/universal/types/providers/superstate/swap.ts
3174
- var SwapPreview = {
3175
- /** Maps the contract's `Preview { input, fee, output }` struct. */
3176
- fromContract: (preview) => ({
3177
- inputAmount: parseUint256(preview.input, "SwapPreview.input"),
3178
- fee: parseUint256(preview.fee, "SwapPreview.fee"),
3179
- outputAmount: parseUint256(preview.output, "SwapPreview.output")
3180
- })
3181
- };
3182
- var PauseFlags = (value) => value;
3183
- var SwapStatus = {
3184
- /**
3185
- * Maps the contract's `Status { uint32 flags; State state }` struct, where
3186
- * `State` is `0 = Active | 1 = Paused | 2 = Stopped`.
3187
- *
3188
- * `flags` is carried onto the `paused` arm only. On the other two the
3189
- * contract sets it to a self-identifying marker rather than to information -
3190
- * so repeating it would invite a caller to read meaning into a constant.
3191
- *
3192
- * @throws ValidationError on a `state` outside the enum. A contract that has
3193
- * grown a fourth state is one the SDK does not model, and guessing `active`
3194
- * would let a halted swap read as a live one.
3195
- */
3196
- fromContract: (status) => {
3197
- switch (status.state) {
3198
- case 0:
3199
- return { state: "active" };
3200
- case 1:
3201
- return { state: "paused", pausedLevels: PauseFlags(status.flags) };
3202
- case 2:
3203
- return { state: "stopped" };
3204
- default:
3205
- throw new ValidationError(
3206
- `SwapStatus.state: unknown contract state (${status.state})`
3207
- );
3208
- }
3209
- }
3210
- };
3211
- var AllowWalletResponse = {
3212
- fromDto: (dto) => {
3213
- switch (dto.action) {
3214
- case "broadcast_transaction":
3215
- return {
3216
- action: "broadcast_transaction",
3217
- to: EvmContractAddress(dto.to),
3218
- data: HexEncodedTransactionData(dto.data)
3219
- };
3220
- case "none":
3221
- return {
3222
- action: "none",
3223
- alreadyAllowed: dto.already_allowed
3224
- };
3225
- default: {
3226
- const _exhaustive = dto;
3227
- return _exhaustive;
3228
- }
3229
- }
3230
- }
3231
- };
3232
-
3233
- // src/universal/api/frontline/providers/superstate/swap.ts
3234
- async function allowWallet(api, params) {
3235
- const dto = await api.send({
3236
- method: "POST",
3237
- url: `/v1/offers/${encodeURIComponent(params.offerId)}/allow-wallet`,
3238
- body: {
3239
- wallet_address: params.walletAddress,
3240
- chain: params.chain,
3241
- signature: params.signature
3242
- },
3243
- attributes: Attributes.protected()
3244
- });
3245
- return AllowWalletResponse.fromDto(dto);
3246
- }
3247
-
3248
- // src/universal/core/shared/blockchain/erc20/abi.ts
3249
- var ERC20_ABI = [
3250
- {
3251
- type: "function",
3252
- name: "allowance",
3253
- inputs: [
3254
- { name: "owner", type: "address" },
3255
- { name: "spender", type: "address" }
3256
- ],
3257
- outputs: [{ name: "", type: "uint256" }],
3258
- stateMutability: "view"
3259
- },
3260
- {
3261
- type: "function",
3262
- name: "approve",
3263
- inputs: [
3264
- { name: "spender", type: "address" },
3265
- { name: "amount", type: "uint256" }
3266
- ],
3267
- outputs: [{ name: "", type: "bool" }],
3268
- stateMutability: "nonpayable"
3269
- },
3270
- {
3271
- type: "function",
3272
- name: "balanceOf",
3273
- inputs: [{ name: "account", type: "address" }],
3274
- outputs: [{ name: "", type: "uint256" }],
3275
- stateMutability: "view"
3276
- },
3277
- {
3278
- type: "function",
3279
- name: "decimals",
3280
- inputs: [],
3281
- outputs: [{ name: "", type: "uint8" }],
3282
- stateMutability: "view"
3283
- },
3284
- {
3285
- type: "function",
3286
- name: "name",
3287
- inputs: [],
3288
- outputs: [{ name: "", type: "string" }],
3289
- stateMutability: "view"
3290
- },
3291
- {
3292
- type: "function",
3293
- name: "symbol",
3294
- inputs: [],
3295
- outputs: [{ name: "", type: "string" }],
3296
- stateMutability: "view"
3297
- },
3298
- {
3299
- type: "function",
3300
- name: "totalSupply",
3301
- inputs: [],
3302
- outputs: [{ name: "", type: "uint256" }],
3303
- stateMutability: "view"
3304
- },
3305
- {
3306
- type: "function",
3307
- name: "transfer",
3308
- inputs: [
3309
- { name: "recipient", type: "address" },
3310
- { name: "amount", type: "uint256" }
3311
- ],
3312
- outputs: [{ name: "", type: "bool" }],
3313
- stateMutability: "nonpayable"
3314
- },
3315
- {
3316
- type: "function",
3317
- name: "transferFrom",
3318
- inputs: [
3319
- { name: "sender", type: "address" },
3320
- { name: "recipient", type: "address" },
3321
- { name: "amount", type: "uint256" }
3322
- ],
3323
- outputs: [{ name: "", type: "bool" }],
3324
- stateMutability: "nonpayable"
3325
- },
3326
- {
3327
- type: "event",
3328
- name: "Approval",
3329
- inputs: [
3330
- { name: "owner", type: "address", indexed: true },
3331
- { name: "spender", type: "address", indexed: true },
3332
- { name: "value", type: "uint256", indexed: false }
3333
- ],
3334
- anonymous: false
3335
- },
3336
- {
3337
- type: "event",
3338
- name: "Transfer",
3339
- inputs: [
3340
- { name: "from", type: "address", indexed: true },
3341
- { name: "to", type: "address", indexed: true },
3342
- { name: "value", type: "uint256", indexed: false }
3343
- ],
3344
- anonymous: false
3345
- }
3346
- ];
3347
-
3348
- // src/universal/api/rpc/providers/superstate/swap.ts
3349
- async function getSwapAuthorization(clients, params) {
3350
- return clients(params.chain).readContract({
3351
- address: params.contractAddress,
3352
- abi: SUPERSTATE_SWAP_ABI,
3353
- functionName: "authorized",
3354
- args: [params.walletAddress]
3355
- });
3356
- }
3357
- async function getSwapPreview(clients, params) {
3358
- const preview = await clients(params.chain).readContract({
3359
- address: params.contractAddress,
3360
- abi: SUPERSTATE_SWAP_ABI,
3361
- functionName: "preview",
3362
- args: [params.inputToken, params.amount]
3363
- });
3364
- return SwapPreview.fromContract(preview);
3365
- }
3366
- async function getSwapStatus(clients, params) {
3367
- const status = await clients(params.chain).readContract({
3368
- address: params.contractAddress,
3369
- abi: SUPERSTATE_SWAP_ABI,
3370
- functionName: "status"
3371
- });
3372
- return SwapStatus.fromContract(status);
3373
- }
3374
- async function getSwapOutputToken(clients, params) {
3375
- const client = clients(params.chain);
3376
- const tokenAddress = await client.readContract({
3377
- address: params.contractAddress,
3378
- abi: SUPERSTATE_SWAP_ABI,
3379
- functionName: "outputToken"
3380
- });
3381
- const token = { address: EvmContractAddress(tokenAddress), abi: ERC20_ABI };
3382
- const [name, symbol, decimals] = await client.multicall({
3383
- contracts: [
3384
- { ...token, functionName: "name" },
3385
- { ...token, functionName: "symbol" },
3386
- { ...token, functionName: "decimals" }
3387
- ],
3388
- allowFailure: false
3389
- });
3390
- return {
3391
- name,
3392
- symbol: AssetSymbol(symbol),
3393
- decimals: AssetDecimals(decimals)
3394
- };
3395
- }
3396
-
3397
- // src/universal/core/checkout/superstate/swap-namespace.ts
3398
- var SuperstateSwapNamespaceImpl = class {
3399
- constructor(ctx) {
3400
- this.ctx = ctx;
3401
- this.log = internalLogger(ctx.logger, "SUPERSTATE");
3402
- }
3403
- async getAuthorization(params) {
3404
- return this.log.wrap(
3405
- "getAuthorization",
3406
- params,
3407
- async () => getSwapAuthorization(this.ctx.rpc, params)
3408
- );
3409
- }
3410
- async getPreview(params) {
3411
- return this.log.wrap(
3412
- "getPreview",
3413
- params,
3414
- async () => getSwapPreview(this.ctx.rpc, params)
3415
- );
3416
- }
3417
- async getStatus(params) {
3418
- return this.log.wrap(
3419
- "getStatus",
3420
- params,
3421
- async () => getSwapStatus(this.ctx.rpc, params)
3422
- );
3423
- }
3424
- async getOutputToken(params) {
3425
- return this.log.wrap(
3426
- "getOutputToken",
3427
- params,
3428
- async () => getSwapOutputToken(this.ctx.rpc, params)
3429
- );
3430
- }
3431
- async allowWallet(params) {
3432
- return this.log.wrap("allowWallet", params, async () => {
3433
- await this.ctx.ensureUserAuthenticated();
3434
- return allowWallet(this.ctx.api, params);
3435
- });
3436
- }
3437
- };
3438
-
3439
- // src/universal/api/frontline/offers.ts
3440
- async function fetchOffers(api, clientCreds) {
3441
- return fetchAllPages((params) => fetchOffersPage(api, params, clientCreds));
3442
- }
3443
- async function fetchOffersPage(api, params, clientCreds) {
3444
- const queryParams = PaginationParams.toQueryParams(params);
3445
- const pageDto = await api.send({
3446
- method: "GET",
3447
- url: "/v1/offers",
3448
- queryParams,
3449
- attributes: Attributes.concat(
3450
- Attributes.protected(),
3451
- Attributes.clientCredentials(clientCreds)
3452
- )
3453
- });
3454
- return PaginatedResponse.fromDtoPage(pageDto, Offer.listFromDto);
3455
- }
3456
- async function fetchOfferDetails(api, id, clientCreds) {
3457
- const dto = await api.send({
3458
- method: "GET",
3459
- url: `/v1/offers/${id}`,
3460
- attributes: Attributes.concat(
3461
- Attributes.protected(),
3462
- Attributes.clientCredentials(clientCreds)
3463
- )
3464
- });
3465
- return OfferDetail.fromDto(dto);
3466
- }
3467
-
3468
- // src/universal/core/offers/offers-namespace.ts
3469
- var OffersNamespaceImpl = class {
3470
- constructor(ctx) {
3471
- this.ctx = ctx;
3472
- this.log = internalLogger(ctx.logger, "OFFERS");
3473
- }
3474
- async list() {
3475
- return this.log.wrap("list", void 0, async () => {
3476
- await this.ctx.ensureUserAuthenticated();
3477
- return fetchOffers(this.ctx.api, void 0);
3478
- });
3479
- }
3480
- async listPage(params) {
3481
- return this.log.wrap("listPage", params, async () => {
3482
- await this.ctx.ensureUserAuthenticated();
3483
- return fetchOffersPage(this.ctx.api, params, void 0);
3484
- });
3485
- }
3486
- async get(id) {
3487
- return this.log.wrap("get", id, async () => {
3488
- await this.ctx.ensureUserAuthenticated();
3489
- return fetchOfferDetails(this.ctx.api, id, void 0);
3490
- });
3491
- }
3492
- };
3493
-
3494
- // src/universal/core/offers/swap-contracts.ts
3495
- function swapSpender(swapContracts, chain) {
3496
- return swapContracts.find((contract) => contract.chain === chain)?.address ?? null;
3497
- }
3498
-
3499
- // src/universal/types/document-submission.ts
3500
- var DocumentSubmission = {
3501
- fromDto: (dto) => ({
3502
- status: dto.status,
3503
- formType: dto.form_type
3504
- })
3505
- };
3506
-
3507
- // src/universal/api/frontline/documents.ts
3508
- async function submitDocument(api, documentType, fields) {
3509
- const dto = await api.send({
3510
- method: "POST",
3511
- url: `/v1/documents/${documentType}/submission`,
3512
- body: fields,
3513
- attributes: Attributes.protected()
3514
- });
3515
- return DocumentSubmission.fromDto(dto);
3516
- }
3517
-
3518
- // src/universal/types/kyc.ts
3519
- var KycToken = {
3520
- fromDto: (dto) => ({
3521
- token: dto.token
3522
- })
3523
- };
3524
-
3525
- // src/universal/api/frontline/kyc.ts
3526
- async function createKycToken(api, levelName, reset) {
3527
- const dto = await api.send({
3528
- method: "POST",
3529
- url: "/v1/kyc-token",
3530
- body: {
3531
- ...levelName === void 0 ? {} : { level_name: levelName },
3532
- ...reset === void 0 ? {} : { reset }
3533
- },
3534
- attributes: Attributes.protected()
3535
- });
3536
- return KycToken.fromDto(dto);
3537
- }
3538
-
3539
- // src/universal/types/pii.ts
3540
- var Iso2CountryCode = (value) => value;
3541
- var PiiJurisdiction = {
3542
- fromDto: (dto) => ({
3543
- iso2: Iso2CountryCode(dto.iso_2),
3544
- name: dto.name
3545
- })
3546
- };
3547
- var PiiAddress = {
3548
- fromDto: (dto) => ({
3549
- street: dto.street,
3550
- city: dto.city,
3551
- state: dto.state,
3552
- postalCode: dto.postal_code,
3553
- country: dto.country
3554
- })
3555
- };
3556
- var Pii = {
3557
- fromDto: (dto) => ({
3558
- kind: dto.kind,
3559
- fullLegalName: dto.full_legal_name,
3560
- dateOfBirth: dto.date_of_birth,
3561
- jurisdiction: dto.jurisdiction ? PiiJurisdiction.fromDto(dto.jurisdiction) : null,
3562
- taxId: dto.tax_id,
3563
- permanentAddress: PiiAddress.fromDto(dto.permanent_address)
3564
- })
3565
- };
3566
-
3567
- // src/universal/api/frontline/pii.ts
3568
- async function fetchPii(api) {
3569
- const dto = await api.send({
3570
- method: "GET",
3571
- url: "/v1/pii",
3572
- attributes: Attributes.protected()
3573
- });
3574
- return Pii.fromDto(dto);
3575
- }
3576
-
3577
- // src/universal/types/requirement.ts
3578
- var RequirementId = (value) => value;
3579
- var Requirement = {
3580
- fromDto: (dto) => ({
3581
- id: RequirementId(dto.id),
3582
- type: dto.type,
3583
- details: dto.details
3584
- })
3585
- };
3586
- var RequirementStatusInfo = {
3587
- fromStatusesDto: (dto) => Object.entries(dto.statuses).map(
3588
- ([id, value]) => typeof value === "string" ? { id: RequirementId(id), status: value, action: null } : {
3589
- id: RequirementId(id),
3590
- status: value.status,
3591
- action: value.action ?? null,
3592
- kycLevel: value.kyc_level,
3593
- kycReset: value.kyc_reset
3594
- }
3595
- )
3596
- };
3597
-
3598
- // src/universal/api/frontline/requirements.ts
3599
- async function fetchOfferRequirements(api, offerId, clientCreds) {
3600
- const response = await api.send({
3601
- method: "GET",
3602
- url: `/v1/offers/${offerId}/requirements`,
3603
- attributes: Attributes.concat(
3604
- Attributes.protected(),
3605
- Attributes.clientCredentials(clientCreds)
3606
- )
3607
- });
3608
- return Object.fromEntries(
3609
- Object.entries(response.options).map(([optionId, list]) => [
3610
- optionId,
3611
- list.data.map(Requirement.fromDto)
3612
- ])
3613
- );
3614
- }
3615
- async function fetchRequirementStatuses(api, offerId) {
3616
- const response = await api.send({
3617
- method: "GET",
3618
- url: `/v1/offers/${offerId}/requirements/statuses`,
3619
- attributes: Attributes.protected()
3620
- });
3621
- return RequirementStatusInfo.fromStatusesDto(response);
3622
- }
3623
-
3624
- // src/universal/core/requirements/requirements-namespace.ts
3625
- var RequirementsNamespaceImpl = class {
3626
- constructor(ctx) {
3627
- this.ctx = ctx;
3628
- this.log = internalLogger(ctx.logger, "REQUIREMENTS");
3629
- }
3630
- async forOffer(offerId) {
3631
- return this.log.wrap("forOffer", offerId, async () => {
3632
- await this.ctx.ensureUserAuthenticated();
3633
- return fetchOfferRequirements(
3634
- this.ctx.api,
3635
- offerId,
3636
- void 0
3637
- );
3638
- });
3639
- }
3640
- async statuses(offerId) {
3641
- return this.log.wrap("statuses", offerId, async () => {
3642
- await this.ctx.ensureUserAuthenticated();
3643
- return fetchRequirementStatuses(this.ctx.api, offerId);
3644
- });
3645
- }
3646
- async createKycToken(params) {
3647
- return this.log.wrap("createKycToken", params, async () => {
3648
- await this.ctx.ensureUserAuthenticated();
3649
- return createKycToken(
3650
- this.ctx.api,
3651
- params?.levelName,
3652
- params?.reset
3653
- );
3654
- });
3655
- }
3656
- async getPii() {
3657
- return this.log.wrap("getPii", void 0, async () => {
3658
- await this.ctx.ensureUserAuthenticated();
3659
- return fetchPii(this.ctx.api);
3660
- });
3661
- }
3662
- async submitDocument(params) {
3663
- return this.log.wrap("submitDocument", params, async () => {
3664
- await this.ctx.ensureUserAuthenticated();
3665
- return submitDocument(
3666
- this.ctx.api,
3667
- params.documentType,
3668
- params.fields
3669
- );
3670
- });
3671
- }
3672
- };
3673
-
3674
- // src/universal/api/rpc/erc20.ts
3675
- async function getTokenAllowance(clients, params) {
3676
- const allowance = await clients(params.chain).readContract({
3677
- address: params.tokenAddress,
3678
- abi: ERC20_ABI,
3679
- functionName: "allowance",
3680
- args: [params.owner, params.spender]
3681
- });
3682
- return parseUint256(allowance, "allowance");
3683
- }
3684
- async function getTokenBalance(clients, params) {
3685
- const balance = await clients(params.chain).readContract({
3686
- address: params.tokenAddress,
3687
- abi: ERC20_ABI,
3688
- functionName: "balanceOf",
3689
- args: [params.owner]
3690
- });
3691
- return parseUint256(balance, "balanceOf");
3692
- }
3693
-
3694
- // src/universal/core/shared/blockchain/erc20/erc20-namespace.ts
3695
- var Erc20NamespaceImpl = class {
3696
- constructor(ctx) {
3697
- this.ctx = ctx;
3698
- this.log = internalLogger(ctx.logger, "ERC20");
3699
- }
3700
- async getAllowance(params) {
3701
- return this.log.wrap(
3702
- "getAllowance",
3703
- params,
3704
- async () => getTokenAllowance(this.ctx.rpc, params)
3705
- );
3706
- }
3707
- async getBalance(params) {
3708
- return this.log.wrap(
3709
- "getBalance",
3710
- params,
3711
- async () => getTokenBalance(this.ctx.rpc, params)
3712
- );
3713
- }
3714
- };
3715
-
3716
- // src/universal/core/tokens/token-registry-snapshot.ts
3717
- var TokenRegistrySnapshot = {
3718
- /** Indexes a `tokens.list()` result. `[]` is a valid, empty snapshot. */
3719
- fromTokens: (tokens) => ({
3720
- tokens,
3721
- byKey: new Map(
3722
- tokens.map((token) => [registryKey(token.identifier), token])
3723
- )
3724
- }),
3725
- /**
3726
- * The registry's entry for one token, or `null` when it lists none. The
3727
- * registry is curated, so `null` is an ordinary answer rather than an
3728
- * error, and callers fall back to their own display defaults.
3729
- */
3730
- get: (snapshot, token) => snapshot.byKey.get(registryKey(token)) ?? null,
3731
- /**
3732
- * The registry's entry for the token an offer is *about*, or `null` when
3733
- * it lists none of them.
3734
- *
3735
- * Resolution follows {@link offerDisplayTokens}: the token a sale
3736
- * distributes or a swap hands over, never the funding token the user pays
3737
- * with. An offer deployed on several chains carries one such token per
3738
- * chain, and the first the registry knows wins - they are the same asset,
3739
- * so any listed one answers for the offer.
3740
- */
3741
- forOffer: (snapshot, offer) => {
3742
- for (const token of offerDisplayTokens(offer)) {
3743
- const metadata = TokenRegistrySnapshot.get(snapshot, token);
3744
- if (metadata !== null) {
3745
- return metadata;
3746
- }
3747
- }
3748
- return null;
3749
- }
3750
- };
3751
- function offerDisplayTokens(offer) {
3752
- const swaps = offer.tokens.filter(
3753
- (token) => token.role === "swap" || token.role === "vault"
3754
- );
3755
- const distributions = offer.tokens.filter(
3756
- (token) => token.role === "distribution"
3757
- );
3758
- return [...swaps, ...distributions];
3759
- }
3760
- function registryKey(token) {
3761
- return `${token.chain}:${token.address.toLowerCase()}`;
3762
- }
3763
-
3764
- // src/universal/api/nabu/tokens.ts
3765
- var import_viem5 = require("viem");
3766
-
3767
- // src/universal/api/frontline/config.ts
3768
- var HEADER_API_VERSION = "X-API-Version";
3769
-
3770
- // src/universal/api/http-client.ts
3771
- var HttpClient = class {
3772
- constructor(config, middleware = {}, logger = null, options = {}) {
3773
- this.config = config;
3774
- this.middleware = middleware;
3775
- this.log = internalLogger(logger, "HTTP");
3776
- this.makeRequestId = options.makeRequestId ?? defaultMakeRequestId;
3777
- }
3778
- async send(request) {
3779
- return this.runRequestWithAfterMiddleware(request);
3780
- }
3781
- /**
3782
- * Runs beforeRequest, executeRequest, then the full afterRequest middleware
3783
- * chain. Used by send() and by the retry() callback so that when a
3784
- * middleware calls retry(), the retried response also goes through all
3785
- * afterRequest middleware (e.g. session renewal, retry). Middleware
3786
- * must use request.attributes.retryAttempt (or similar) to avoid infinite
3787
- * recursion when they trigger retries.
3788
- */
3789
- async runRequestWithAfterMiddleware(request) {
3790
- const preparedRequest = await this.runBeforeRequestMiddleware(
3791
- this.withClientDefaults(request)
3792
- );
3793
- let response = await this.executeRequest(preparedRequest);
3794
- for (const middleware of this.middleware.afterRequest ?? []) {
3795
- let retried = false;
3796
- response = await middleware({
3797
- request: preparedRequest,
3798
- response,
3799
- retry: (nextRequest = preparedRequest) => {
3800
- retried = true;
3801
- return this.runRequestWithAfterMiddleware(nextRequest);
3802
- }
3803
- });
3804
- if (retried) {
3805
- return response;
3806
- }
3807
- }
3808
- return response;
3809
- }
3810
- withClientDefaults(request) {
3811
- const url = this.resolveUrl(request.url);
3812
- const headers = {
3813
- ...request.headers ?? {},
3814
- ...this.config.xApiVersion !== void 0 ? { [HEADER_API_VERSION]: this.config.xApiVersion } : {}
3815
- };
3816
- return {
3817
- ...request,
3818
- url,
3819
- headers,
3820
- // Only when absent: a retry or a post-renewal re-send arrives with the
3821
- // first attempt's id already on it, and keeping it is the whole point.
3822
- attributes: Attributes.getRequestId(request.attributes) === null ? Attributes.concat(
3823
- request.attributes ?? Attributes.empty,
3824
- Attributes.requestId(this.makeRequestId())
3825
- ) : request.attributes
3826
- };
3827
- }
3828
- /**
3829
- * Resolves a request URL against the client's baseUrl.
3830
- *
3831
- * @internal Public only for testing. Do not use in application code; use
3832
- * {@link HttpClient.send} with a path and the client will resolve the URL.
3833
- */
3834
- resolveUrl(url) {
3835
- if (url.startsWith("http://") || url.startsWith("https://")) {
3836
- return url;
3837
- }
3838
- const base2 = this.config.baseUrl.replace(/\/$/, "");
3839
- const path = url.startsWith("/") ? url : `/${url}`;
3840
- return base2 + path;
3841
- }
3842
- async runBeforeRequestMiddleware(initialRequest) {
3843
- let request = initialRequest;
3844
- for (const middleware of this.middleware.beforeRequest ?? []) {
3845
- request = await middleware(request);
3846
- }
3847
- return request;
3848
- }
3849
- /**
3850
- * One physical attempt, logged as one line.
3851
- *
3852
- * A non-2xx is a `warn` rather than an `error` because the wire does not
3853
- * know whether it is a failure: the retry middleware may turn a 503 into a
3854
- * success, and the token registry reads a 404 as "not listed". The namespace
3855
- * above decides, and logs the `error` when it does.
3856
- */
3857
- async executeRequest(request) {
3858
- const requestId2 = Attributes.getRequestId(request.attributes);
3859
- const log = requestId2 === null ? this.log : this.log.child({ requestId: requestId2 });
3860
- const attempt = Attributes.getRetryAttempt(request.attributes) + 1;
3861
- const startedAt = Date.now();
3862
- log.debug(() => ({
3863
- msg: "request sent",
3864
- fields: describeRequestUnredacted(request)
3865
- }));
3866
- try {
3867
- const response = await makeRequest(request);
3868
- const elapsed = Date.now() - startedAt;
3869
- const outcome = () => ({
3870
- msg: "request completed",
3871
- fields: {
3872
- ...identifyRequest(request),
3873
- "http.response.status_code": response.status,
3874
- duration_ms: elapsed,
3875
- attempt
3876
- }
3877
- });
3878
- if (response.status >= 200 && response.status < 300) {
3879
- log.info(outcome);
3880
- } else {
3881
- log.warn(outcome);
3882
- }
3883
- log.debug(() => ({
3884
- msg: "response received",
3885
- fields: { body: response.body }
3886
- }));
3887
- return requestId2 === null ? response : { ...response, requestId: requestId2 };
3888
- } catch (error) {
3889
- const elapsed = Date.now() - startedAt;
3890
- log.warning(
3891
- () => ({
3892
- msg: "request threw",
3893
- fields: {
3894
- ...identifyRequest(request),
3895
- duration_ms: elapsed,
3896
- attempt
3897
- }
3898
- }),
3899
- error
3900
- );
3901
- throw error;
3902
- }
3903
- }
3904
- };
3905
- function identifyRequest(request) {
3906
- const { host, path } = splitUrl(request.url);
3907
- return {
3908
- "http.request.method": request.method,
3909
- "server.address": host,
3910
- "url.path": path
3911
- };
3912
- }
3913
- function splitUrl(url) {
3914
- try {
3915
- const parsed = new URL(url);
3916
- return { host: parsed.host, path: parsed.pathname };
3917
- } catch (_) {
3918
- return { host: null, path: url };
3919
- }
3920
- }
3921
- function defaultMakeRequestId() {
3922
- return Math.random().toString(36).slice(2, 10).padEnd(8, "0");
3923
- }
3924
- function describeRequestUnredacted(request) {
3925
- return {
3926
- "http.request.method": request.method,
3927
- "url.full": buildUrlWithQueryParams(request.url, request.queryParams),
3928
- headers: request.headers,
3929
- ...request.method === "POST" ? { body: request.body } : {}
3930
- };
3931
- }
3932
-
3933
- // src/universal/types/token-metadata.ts
3934
- var TokenLogoUrl = (value) => value;
3935
- var TokenLogo = {
3936
- /** `baseUrl` is the registry origin; registry URLs are root-relative. */
3937
- fromDto: (dto, baseUrl) => dto.kind === "VECTOR" ? { kind: "VECTOR", url: resolveLogoUrl(dto.url, baseUrl) } : {
3938
- kind: "RASTER",
3939
- original: logoImageFromDto(dto.original, baseUrl),
3940
- variants: dto.variants.map((v) => logoImageFromDto(v, baseUrl))
3941
- }
3942
- };
3943
- var TokenMetadata = {
3944
- /** `baseUrl` is the registry origin; registry logo URLs are root-relative. */
3945
- fromDto: (dto, baseUrl) => {
3946
- assertSupportedSchemaVersion(dto.schema_version);
3947
- return {
3948
- identifier: {
3949
- chain: EthereumChain(dto.chain),
3950
- address: EvmContractAddress(dto.address)
3951
- },
3952
- name: dto.name,
3953
- symbol: AssetSymbol(dto.symbol),
3954
- decimals: AssetDecimals(dto.decimals),
3955
- logo: TokenLogo.fromDto(dto.logo, baseUrl),
3956
- logoDark: dto.logo_dark === void 0 ? null : TokenLogo.fromDto(dto.logo_dark, baseUrl)
3957
- };
3958
- },
3959
- /**
3960
- * Maps the complete registry snapshot to every token it lists across the
3961
- * chains this SDK models, skipping native coins and chains outside
3962
- * {@link EthereumChain} (e.g. Solana) rather than failing on them — the
3963
- * registry may serve chains ahead of the SDK's type surface.
3964
- */
3965
- fromRegistryDto: (dto, baseUrl) => {
3966
- assertSupportedSchemaVersion(dto.schema_version);
3967
- return dto.chains.flatMap((chainDto) => {
3968
- let chain;
3969
- try {
3970
- chain = EthereumChain(chainDto.chain);
3971
- } catch {
3972
- return [];
3973
- }
3974
- return tokensOfChain(chain, chainDto.assets, baseUrl);
3975
- });
3976
- },
3977
- /**
3978
- * Maps a chain snapshot to the tokens it lists, skipping the chain's native
3979
- * coin (`kind: 'COIN'`, no contract address).
3980
- */
3981
- fromChainAssetsDto: (dto, baseUrl) => {
3982
- assertSupportedSchemaVersion(dto.schema_version);
3983
- return tokensOfChain(EthereumChain(dto.chain), dto.assets, baseUrl);
3984
- }
3985
- };
3986
- function tokensOfChain(chain, assets, baseUrl) {
3987
- return assets.filter((asset) => asset.kind === "TOKEN" && asset.address !== void 0).map((asset) => ({
3988
- identifier: {
3989
- chain,
3990
- // The filter above cannot narrow `address` for the type checker.
3991
- address: EvmContractAddress(asset.address)
3992
- },
3993
- name: asset.name,
3994
- symbol: AssetSymbol(asset.symbol),
3995
- decimals: AssetDecimals(asset.decimals),
3996
- logo: TokenLogo.fromDto(asset.logo, baseUrl),
3997
- logoDark: asset.logo_dark === void 0 ? null : TokenLogo.fromDto(asset.logo_dark, baseUrl)
3998
- }));
3999
- }
4000
- function assertSupportedSchemaVersion(version) {
4001
- if (version !== 1) {
4002
- throw new ValidationError(
4003
- `Unsupported token registry schema_version: ${version}`
4004
- );
4005
- }
4006
- }
4007
- var logoImageFromDto = (dto, baseUrl) => ({
4008
- url: resolveLogoUrl(dto.url, baseUrl),
4009
- width: dto.width,
4010
- height: dto.height
4011
- });
4012
- var resolveLogoUrl = (url, baseUrl) => TokenLogoUrl(
4013
- url.startsWith("http") ? url : `${baseUrl.replace(/\/$/, "")}${url}`
4014
- );
4015
-
4016
- // src/universal/api/nabu/tokens.ts
4017
- function createNabuApiClient(baseUrl, logger = null) {
4018
- return new HttpClient({ baseUrl }, {}, logger);
4019
- }
4020
- async function fetchTokenMetadata(client, token) {
4021
- const address = checksummed(token.address);
4022
- let response;
4023
- try {
4024
- response = await client.send({
4025
- method: "GET",
4026
- url: `/${token.chain}/token/${address}`
4027
- });
4028
- } catch (error) {
4029
- if (isRegistryHtmlFallback(error)) {
4030
- return null;
4031
- }
4032
- throw error;
4033
- }
4034
- if (response.status === 404) {
4035
- return null;
4036
- }
4037
- assertOk(response);
4038
- if (response.body === null) {
4039
- throw new ValidationError(
4040
- `Token registry returned an empty body for token "${address}" on "${token.chain}"`
4041
- );
4042
- }
4043
- return TokenMetadata.fromDto(response.body, client.config.baseUrl);
4044
- }
4045
- async function fetchTokensMetadata(client, chain) {
4046
- let response;
4047
- try {
4048
- response = await client.send({
4049
- method: "GET",
4050
- url: `/${chain}/assets.json`
4051
- });
4052
- } catch (error) {
4053
- if (isRegistryHtmlFallback(error)) {
4054
- throw new ValidationError(
4055
- `Token registry returned non-JSON for the "${chain}" snapshot`
4056
- );
4057
- }
4058
- throw error;
4059
- }
4060
- assertOk(response);
4061
- if (response.body === null) {
4062
- throw new ValidationError(
4063
- `Token registry returned an empty "${chain}" snapshot`
4064
- );
4065
- }
4066
- return TokenMetadata.fromChainAssetsDto(response.body, client.config.baseUrl);
4067
- }
4068
- async function fetchAllTokensMetadata(client) {
4069
- let response;
4070
- try {
4071
- response = await client.send({
4072
- method: "GET",
4073
- url: `/assets.json`
4074
- });
4075
- } catch (error) {
4076
- if (isRegistryHtmlFallback(error)) {
4077
- throw new ValidationError(
4078
- "Token registry returned non-JSON for the complete snapshot"
4079
- );
4080
- }
4081
- throw error;
4082
- }
4083
- assertOk(response);
4084
- if (response.body === null) {
4085
- throw new ValidationError(
4086
- "Token registry returned an empty complete snapshot"
4087
- );
4088
- }
4089
- return TokenMetadata.fromRegistryDto(response.body, client.config.baseUrl);
4090
- }
4091
- function isRegistryHtmlFallback(error) {
4092
- return error instanceof HttpError && error.response.status >= 200 && error.response.status < 300;
4093
- }
4094
- function assertOk(response) {
4095
- if (response.status < 200 || response.status >= 300) {
4096
- throw new HttpError(response);
4097
- }
4098
- }
4099
- function checksummed(address) {
4100
- try {
4101
- return (0, import_viem5.getAddress)(address);
4102
- } catch (_) {
4103
- throw new ValidationError(`Invalid EVM contract address: "${address}"`);
4104
- }
4105
- }
4106
-
4107
- // src/universal/core/tokens/tokens-namespace.ts
4108
- var TokensNamespaceImpl = class {
4109
- /**
4110
- * Takes the registry origin rather than a `UniversalNamespaceContext`: the
4111
- * registry is unauthenticated and on its own host, so the frontline sender
4112
- * and the auth check would both be dead weight here.
4113
- */
4114
- constructor(baseUrl, logger = null) {
4115
- this.api = createNabuApiClient(baseUrl, logger);
4116
- this.log = internalLogger(logger, "TOKENS");
4117
- }
4118
- get(token) {
4119
- return this.log.wrap(
4120
- "get",
4121
- token,
4122
- () => fetchTokenMetadata(this.api, token)
4123
- );
4124
- }
4125
- list(chain) {
4126
- return this.log.wrap(
4127
- "list",
4128
- chain,
4129
- () => chain === void 0 ? fetchAllTokensMetadata(this.api) : fetchTokensMetadata(this.api, chain)
4130
- );
4131
- }
4132
- };
4133
-
4134
- // src/universal/types/offer-option-address.ts
4135
- var OfferOptionAddressId = (value) => value;
4136
- var OfferOptionAddress = {
4137
- /** Maps the API DTO into the SDK offer-option-address domain model. */
4138
- fromDto: (dto) => ({
4139
- id: OfferOptionAddressId(dto.id),
4140
- offerOptionId: OfferOptionId(dto.offer_option_id),
4141
- address: EvmWalletAddress(dto.address),
4142
- protocol: dto.protocol,
4143
- createdAt: new Date(dto.created_at)
4144
- })
4145
- };
4146
- var ConnectExternalWalletParams = {
4147
- /** Maps connect-wallet params into the API DTO payload. */
4148
- toDto: (params) => ({
4149
- offer_option_id: params.offerOptionId,
4150
- wallet_address: params.walletAddress,
4151
- chain: params.chain,
4152
- signature: params.signature
4153
- })
4154
- };
4155
-
4156
- // src/universal/types/wallet-ownership-challenge.ts
4157
- var WalletOwnershipChallenge = {
4158
- /** Maps the API DTO into the SDK wallet-ownership-challenge domain model. */
4159
- fromDto: (dto) => ({
4160
- message: dto.message,
4161
- expiresAt: new Date(dto.expires_at)
4162
- })
4163
- };
4164
- var CreateWalletOwnershipChallengeParams = {
4165
- /**
4166
- * Maps challenge-request params into the API DTO payload. The discriminated
4167
- * union guarantees SIWE fields are present exactly when `challengeType` is
4168
- * `siwe`, so the mapping narrows on the discriminant.
4169
- */
4170
- toDto: (params) => {
4171
- switch (params.challengeType) {
4172
- case "plain":
4173
- return {
4174
- wallet_address: params.walletAddress,
4175
- chain: params.chain,
4176
- challenge_type: "plain"
4177
- };
4178
- case "siwe":
4179
- return {
4180
- wallet_address: params.walletAddress,
4181
- chain: params.chain,
4182
- challenge_type: "siwe",
4183
- domain: params.domain,
4184
- uri: params.uri,
4185
- statement: params.statement
4186
- };
4187
- default: {
4188
- const _exhaustive = params;
4189
- return _exhaustive;
4190
- }
4191
- }
4192
- }
4193
- };
4194
-
4195
- // src/universal/api/frontline/wallet-connect.ts
4196
- async function createWalletOwnershipChallenge(api, params) {
4197
- const dto = await api.send({
4198
- method: "POST",
4199
- url: "/v1/wallet-ownership",
4200
- body: CreateWalletOwnershipChallengeParams.toDto(params),
4201
- attributes: Attributes.protected()
4202
- });
4203
- return WalletOwnershipChallenge.fromDto(dto);
4204
- }
4205
- async function connectExternalWallet(api, params) {
4206
- const dto = await api.send({
4207
- method: "POST",
4208
- url: `/v1/offers/${params.offerId}/addresses`,
4209
- body: ConnectExternalWalletParams.toDto(params),
4210
- attributes: Attributes.protected()
4211
- });
4212
- return OfferOptionAddress.fromDto(dto);
4213
- }
4214
- async function listOptionAddresses(api, offerId, offerOptionId) {
4215
- const { data } = await api.send({
4216
- method: "GET",
4217
- url: `/v1/offers/${offerId}/addresses`,
4218
- queryParams: { offer_option_id: offerOptionId },
4219
- attributes: Attributes.protected()
4220
- });
4221
- return data.map(OfferOptionAddress.fromDto);
4222
- }
4223
- async function removeOptionAddress(api, offerId, addressId) {
4224
- const dto = await api.send({
4225
- method: "DELETE",
4226
- url: `/v1/offers/${offerId}/addresses/${addressId}`,
4227
- attributes: Attributes.protected()
4228
- });
4229
- return OfferOptionAddress.fromDto(dto);
4230
- }
4231
-
4232
- // src/universal/core/wallets/wallets-namespace.ts
4233
- var WalletsNamespaceImpl = class {
4234
- constructor(ctx) {
4235
- this.ctx = ctx;
4236
- this.log = internalLogger(ctx.logger, "WALLETS");
4237
- }
4238
- async createOwnershipChallenge(params) {
4239
- return this.log.wrap("createOwnershipChallenge", params, async () => {
4240
- await this.ctx.ensureUserAuthenticated();
4241
- return createWalletOwnershipChallenge(
4242
- this.ctx.api,
4243
- params
4244
- );
4245
- });
4246
- }
4247
- async connectExternal(params) {
4248
- return this.log.wrap("connectExternal", params, async () => {
4249
- await this.ctx.ensureUserAuthenticated();
4250
- return connectExternalWallet(this.ctx.api, params);
4251
- });
4252
- }
4253
- async list(params) {
4254
- return this.log.wrap("list", params, async () => {
4255
- await this.ctx.ensureUserAuthenticated();
4256
- return listOptionAddresses(
4257
- this.ctx.api,
4258
- params.offerId,
4259
- params.offerOptionId
4260
- );
4261
- });
4262
- }
4263
- async remove(params) {
4264
- return this.log.wrap("remove", params, async () => {
4265
- await this.ctx.ensureUserAuthenticated();
4266
- return removeOptionAddress(
4267
- this.ctx.api,
4268
- params.offerId,
4269
- params.addressId
4270
- );
4271
- });
4272
- }
4273
- };
4274
-
4275
- // src/universal/types/blockchain/wallet-error.ts
4276
- var RedactedWalletError = {
4277
- fromWalletError: (error) => error.type === "unknown" ? { type: "unknown" } : error
4278
- };
4279
-
4280
- // src/universal/types/blockchain/wallet-selection.ts
4281
- var WalletSelection = {
4282
- /**
4283
- * Every wallet in display order - embedded first, then the external one -
4284
- * each address once. Addresses compare case-insensitively, so a host that
4285
- * hands the same wallet over as both embedded and external sees it once.
4286
- */
4287
- all: (selection) => {
4288
- const seen = /* @__PURE__ */ new Set();
4289
- return [
4290
- ...selection.embedded,
4291
- ...selection.external === null ? [] : [selection.external]
4292
- ].filter((wallet) => {
4293
- const key = wallet.address.toLowerCase();
4294
- if (seen.has(key)) return false;
4295
- seen.add(key);
4296
- return true;
4297
- });
4298
- }
4299
- };
4300
-
4301
- // src/universal/types/oauth-session.ts
4302
- var ClientCredentialsOAuth = (value) => value;
4303
- var OAuthRefreshToken = (value) => value;
4304
- var OAuthSession = {
4305
- fromDto: (dto) => {
4306
- const expiresAt = new Date(Date.now() + dto.expires_in * 1e3);
4307
- return {
4308
- accessToken: {
4309
- value: dto.access_token,
4310
- expiresAt
4311
- },
4312
- ...dto.refresh_token != null && dto.refresh_token !== "" ? { refreshToken: OAuthRefreshToken(dto.refresh_token) } : void 0
4313
- };
4314
- }
4315
- };
4316
-
4317
- // src/universal/types/time.ts
4318
- var MAX_EPOCH_MILLIS = 864e13;
4319
- var EpochMillis = {
4320
- /**
4321
- * @throws {@link ValidationError} unless `value` is an integer a `Date` can
4322
- * represent: at most {@link MAX_EPOCH_MILLIS} either side of the epoch.
4323
- */
4324
- of: (value) => {
4325
- if (!Number.isInteger(value) || Math.abs(value) > MAX_EPOCH_MILLIS) {
4326
- throw new ValidationError(
4327
- `EpochMillis must be an integer within \xB1${MAX_EPOCH_MILLIS}, got ${value}`
4328
- );
4329
- }
4330
- return value;
4331
- },
4332
- /** The wall clock. Code that needs the time takes a `TimeEff` instead. */
4333
- now: () => EpochMillis.of(Date.now()),
4334
- /** @throws {@link ValidationError} for an invalid `Date`. */
4335
- fromDate: (date) => EpochMillis.of(date.getTime()),
4336
- /** How long after `from` the instant `to` is; negative if it is before. */
4337
- elapsed: (from, to) => Millis.of(to - from),
4338
- plus: (at, duration) => EpochMillis.of(at + duration)
4339
- };
4340
- var Millis = {
4341
- of: (value) => value
4342
- };
4343
- var Seconds = {
4344
- /**
4345
- * @throws {@link ValidationError} unless `value` is a non-negative integer.
4346
- */
4347
- of: (value) => {
4348
- if (!Number.isInteger(value) || value < 0) {
4349
- throw new ValidationError(
4350
- `Seconds must be a non-negative integer, got ${value}`
4351
- );
4352
- }
4353
- return value;
4354
- },
4355
- toMillis: (value) => Millis.of(value * 1e3)
4356
- };
4357
- function isExpired({
4358
- expiresAt,
4359
- now,
4360
- buffer = Millis.of(0)
4361
- }) {
4362
- return now >= expiresAt - buffer;
4363
- }
4364
-
4365
- // src/universal/types/user.ts
4366
- var UserId = (value) => value;
4367
- var UserEmail = (value) => value;
4368
- var User = {
4369
- fromDto: (dto) => ({
4370
- id: UserId(dto.id),
4371
- email: UserEmail(dto.email)
4372
- })
4373
- };
4374
- // Annotate the CommonJS export names for ESM import in node:
4375
- 0 && (module.exports = {
4376
- AllowWalletResponse,
4377
- Asset,
4378
- AssetCode,
4379
- AssetDecimals,
4380
- AssetIconUrl,
4381
- AssetId,
4382
- AssetSymbol,
4383
- AsyncOfferDetail,
4384
- AuthorizationCode,
4385
- BPS_DENOM,
4386
- Blockchain,
4387
- BlockchainAmount,
4388
- Bps,
4389
- CENTRIFUGE_POLL_INTERVAL_MS,
4390
- CentrifugeNamespaceImpl,
4391
- CentrifugeVaultBuyTransaction,
4392
- CentrifugeVaultClaimProceedsTransaction,
4393
- CentrifugeVaultClaimTransaction,
4394
- CentrifugeVaultLeg,
4395
- CentrifugeVaultLegId,
4396
- CentrifugeVaultPosition,
4397
- CentrifugeVaultRedeemPosition,
4398
- CentrifugeVaultStatus,
4399
- Chain,
4400
- ClientCredentialsOAuth,
4401
- ClientId,
4402
- ClientSecret,
4403
- CodeChallenge,
4404
- CodeVerifier,
4405
- CoinListTokenSaleNamespaceImpl,
4406
- ConnectExternalWalletParams,
4407
- CreateParticipationParams,
4408
- CreateWalletOwnershipChallengeParams,
4409
- Cursor,
4410
- DEFAULT_AMOUNT_TO_COMPUTE_PRICE,
4411
- DEFAULT_ONDO_AMOUNT_TO_COMPUTE_PRICE,
4412
- DEFAULT_ONDO_SELL_TOKENS_TO_COMPUTE_PRICE,
4413
- DEFAULT_SLIPPAGE_BPS,
4414
- DecimalString,
4415
- DocumentSubmission,
4416
- ERC20_ABI,
4417
- ETHEREUM_CHAINS,
4418
- EpochMillis,
4419
- Erc20NamespaceImpl,
4420
- EthereumChain,
4421
- EvmContractAddress,
4422
- EvmWalletAddress,
4423
- FaqItem,
4424
- FormattedAmountAssetUi,
4425
- FormattedAmountUi,
4426
- FormattedPercentUi,
4427
- HexEncodedTransactionData,
4428
- HttpError,
4429
- InvariantError,
4430
- Isin,
4431
- Iso2CountryCode,
4432
- KnownAssetSymbol,
4433
- KycToken,
4434
- Link,
4435
- MAX_ASSET_DECIMALS,
4436
- MAX_UINT_256,
4437
- MathError,
4438
- Milestone,
4439
- Millis,
4440
- NA_AMOUNT_ASSET_UI,
4441
- NotAuthenticatedError,
4442
- NotImplementedError,
4443
- OAuthRefreshToken,
4444
- OAuthSession,
4445
- ONDO_NOT_TRADABLE_CODE,
4446
- ONDO_POLL_INTERVAL_MS,
4447
- ONDO_QUOTE_MAX_TTL_MS,
4448
- ONDO_SETTLEMENT_ASSET,
4449
- ONDO_SUPPORTED_INPUT_ASSETS,
4450
- Offer,
4451
- OfferDetail,
4452
- OfferEditorial,
4453
- OfferId,
4454
- OfferOption,
4455
- OfferOptionAddress,
4456
- OfferOptionAddressId,
4457
- OfferOptionId,
4458
- OfferOptionSlug,
4459
- OfferSlug,
4460
- OfferSwapContract,
4461
- OfferToken,
4462
- OfferVaultContract,
4463
- OffersNamespaceImpl,
4464
- OndoBuyTransaction,
4465
- OndoNamespaceImpl,
4466
- OndoQuote,
4467
- OndoSellTransaction,
4468
- OndoTradingStatus,
4469
- PKCEState,
4470
- PaginatedResponse,
4471
- PaginationParams,
4472
- Participation,
4473
- ParticipationId,
4474
- ParticipationsPaginationParams,
4475
- PauseFlags,
4476
- Pii,
4477
- PiiAddress,
4478
- PiiJurisdiction,
4479
- RedactedWalletError,
4480
- RedirectUri,
4481
- Requirement,
4482
- RequirementId,
4483
- RequirementStatusInfo,
4484
- RequirementsNamespaceImpl,
4485
- SLIPPAGE_OPTIONS_BPS,
4486
- SOLANA_CHAINS,
4487
- STABLE_DECIMALS,
4488
- SUPERSTATE_ISSUER_NAME,
4489
- SUPERSTATE_SUPPORTED_INPUT_ASSETS,
4490
- SUPERSTATE_SWAP_ABI,
4491
- SUPERSTATE_SWAP_CONTRACT_ADDRESS_SEPOLIA,
4492
- SWAP_LEVEL,
4493
- SWAP_POLL_INTERVAL_MS,
4494
- Seconds,
4495
- ShortenedWalletAddress,
4496
- SolanaChain,
4497
- StablecoinSymbol,
4498
- SuperstateSwapNamespaceImpl,
4499
- SwapPreview,
4500
- SwapQuote,
4501
- SwapStatus,
4502
- TOKEN_REGISTRY,
4503
- TermItem,
4504
- Ticker,
4505
- TokenLogo,
4506
- TokenLogoUrl,
4507
- TokenMetadata,
4508
- TokenRegistrySnapshot,
4509
- TokensNamespaceImpl,
4510
- TxExplorerUrl,
4511
- USDC,
4512
- USDC_SYMBOL,
4513
- USDT,
4514
- USDT_SYMBOL,
4515
- User,
4516
- UserEmail,
4517
- UserId,
4518
- ValidationError,
4519
- WalletAddress,
4520
- WalletOwnershipChallenge,
4521
- WalletSelection,
4522
- WalletsNamespaceImpl,
4523
- apiErrorCode,
4524
- applyBps,
4525
- assertUint256,
4526
- assetAmount,
4527
- blockchainAmountFromRawOrThrow,
4528
- chainFromId,
4529
- computeOndoBuyPrice,
4530
- computeOndoSellPrice,
4531
- computePrice,
4532
- computeSlip,
4533
- decodeSwappedOutputAmount,
4534
- fetchAllPages,
4535
- formatAmount,
4536
- formatBpsAsPercent,
4537
- formatCompactAmount,
4538
- formatRawAmount,
4539
- formatShareAmount,
4540
- formattedPricePerShare,
4541
- formattedUsdPrice,
4542
- generatePKCEParams,
4543
- getChainId,
4544
- getNetworkName,
4545
- isChain,
4546
- isExpired,
4547
- isOfferType,
4548
- isOndoNotTradableError,
4549
- isSwapAvailable,
4550
- offerDisplayTokens,
4551
- ondoQuoteOfferDeadline,
4552
- parseBlockchainAmount,
4553
- parseUint256,
4554
- resolveCentrifugeVaults,
4555
- shortenAddress,
4556
- superstateSwapContractAddress,
4557
- swapSpender,
4558
- txExplorerUrl,
4559
- usdAmount,
4560
- viemChain
4561
- });
4562
- //# sourceMappingURL=index.cjs.map