@rhea-finance/cross-chain-aggregation-dex 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -95,14 +95,33 @@ var ApiClient = class {
95
95
  retryableOperation: true,
96
96
  query: {
97
97
  sender: params.sender,
98
+ mode: params.mode,
98
99
  pageNumber: params.pageNumber,
99
100
  pageSize: params.pageSize
100
- }
101
+ },
102
+ ...params.mode === "confidential" && params.walletToken ? { authenticationToken: params.walletToken } : {}
103
+ });
104
+ }
105
+ createHistoryAuthChallenge(body, options = {}) {
106
+ return this.request("/api/swap/history/auth/challenge", "history", {
107
+ ...options,
108
+ method: "POST",
109
+ body
110
+ });
111
+ }
112
+ verifyHistoryAuthChallenge(body, options = {}) {
113
+ return this.request("/api/swap/history/auth/verify", "history", {
114
+ ...options,
115
+ method: "POST",
116
+ body
101
117
  });
102
118
  }
103
119
  async request(path, stage, options) {
104
120
  const url = this.buildUrl(path, options.query);
105
- const headers = await this.buildHeaders(options.idempotencyKey);
121
+ const headers = await this.buildHeaders(
122
+ options.idempotencyKey,
123
+ options.authenticationToken
124
+ );
106
125
  const retry = this.retryConfig();
107
126
  let attempt = 1;
108
127
  for (; ; ) {
@@ -254,12 +273,13 @@ var ApiClient = class {
254
273
  const suffix = search.toString();
255
274
  return suffix ? `${this.baseUrl}${path}?${suffix}` : `${this.baseUrl}${path}`;
256
275
  }
257
- async buildHeaders(idempotencyKey) {
276
+ async buildHeaders(idempotencyKey, authenticationToken) {
258
277
  const configured = typeof this.config.headers === "function" ? await this.config.headers() : this.config.headers ?? {};
259
278
  const token = this.config.getAccessToken ? await this.config.getAccessToken() : this.config.apiKey;
260
279
  return {
261
280
  "Content-Type": "application/json",
262
281
  ...token ? { Authorization: `Bearer ${token}` } : {},
282
+ ...authenticationToken ? { Authentication: `Bearer ${authenticationToken}` } : {},
263
283
  ...idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {},
264
284
  ...configured
265
285
  };
@@ -941,6 +961,7 @@ function serializeQuoteRequest(request) {
941
961
  amountIn: request.amountIn,
942
962
  slippage: request.slippageBps,
943
963
  quoteWaitingTimeMs: request.quoteWaitingTimeMs ?? DEFAULT_QUOTE_WAITING_TIME_MS,
964
+ ...request.confidentiality ? { confidentiality: request.confidentiality } : {},
944
965
  sender: request.sender.trim(),
945
966
  ...request.recipient?.trim() ? { recipient: request.recipient.trim() } : {}
946
967
  };
@@ -975,7 +996,7 @@ function normalizeQuote(request, raw, receivedAt = Date.now()) {
975
996
  estimatedOut: bestRoute.amountOut,
976
997
  minAmountOut: bestRoute.minAmountOut,
977
998
  route: bestRoute,
978
- alternatives: raw.allQuotes.flatMap((route) => {
999
+ alternatives: readQuoteAlternatives(raw.allQuotes).flatMap((route) => {
979
1000
  try {
980
1001
  const normalized = normalizeRoute(route, false);
981
1002
  return normalized ? [normalized] : [];
@@ -989,6 +1010,13 @@ function normalizeQuote(request, raw, receivedAt = Date.now()) {
989
1010
  raw
990
1011
  };
991
1012
  }
1013
+ function readQuoteAlternatives(value) {
1014
+ if (!Array.isArray(value)) return [];
1015
+ return value.filter(isRecord);
1016
+ }
1017
+ function isRecord(value) {
1018
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1019
+ }
992
1020
  function validateQuoteRequest(request) {
993
1021
  assertBaseUnitAmount(request.amountIn);
994
1022
  if (!Number.isInteger(request.slippageBps) || request.slippageBps < 0) {
@@ -1206,6 +1234,112 @@ function normalizeTimestamp(value) {
1206
1234
  return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
1207
1235
  }
1208
1236
 
1237
+ // src/mca/collateral.ts
1238
+ function resolveMcaWithdrawPolicy(input) {
1239
+ const decreaseCollateral = resolveMcaRequiredCollateralDecrease({
1240
+ amountBurrow: input.amountBurrow,
1241
+ suppliedBalance: input.suppliedBalance
1242
+ });
1243
+ const available = parseDecimal(input.availableBalance, "availableBalance");
1244
+ const amount = parseDecimal(input.amountIn, "amountIn");
1245
+ return {
1246
+ ...decreaseCollateral,
1247
+ withdrawAll: input.isMax || available.digits > 0n && isAtLeastWithdrawAllThreshold(amount, available)
1248
+ };
1249
+ }
1250
+ function resolveMcaRequiredCollateralDecrease(input) {
1251
+ const amount = parseBurrowDecimal(input.amountBurrow, "amountBurrow");
1252
+ const supplied = parseBurrowDecimal(
1253
+ input.suppliedBalance,
1254
+ "suppliedBalance"
1255
+ );
1256
+ const [amountScaled, suppliedScaled] = alignScale(amount, supplied);
1257
+ const decreaseScaled = amountScaled > suppliedScaled ? amountScaled - suppliedScaled : 0n;
1258
+ return resolveParsedMcaDecreaseCollateral({
1259
+ digits: decreaseScaled,
1260
+ scale: Math.max(amount.scale, supplied.scale)
1261
+ });
1262
+ }
1263
+ function resolveMcaDecreaseCollateral(decreaseAmountBurrow, field = "decreaseAmountBurrow") {
1264
+ const parsed = parseBurrowDecimal(decreaseAmountBurrow, field);
1265
+ return resolveParsedMcaDecreaseCollateral(parsed);
1266
+ }
1267
+ function resolveParsedMcaDecreaseCollateral(parsed) {
1268
+ const needDecrease = parsed.digits > 0n;
1269
+ return {
1270
+ needDecrease,
1271
+ decreaseAmountBurrow: needDecrease ? formatDecimal(parsed) : "0"
1272
+ };
1273
+ }
1274
+ function isAtLeastWithdrawAllThreshold(amount, available) {
1275
+ const [amountScaled, availableScaled] = alignScale(amount, available);
1276
+ return amountScaled * 1000000n >= availableScaled * 999999n;
1277
+ }
1278
+ function alignScale(a, b) {
1279
+ const scale = Math.max(a.scale, b.scale);
1280
+ return [
1281
+ a.digits * pow10(scale - a.scale),
1282
+ b.digits * pow10(scale - b.scale)
1283
+ ];
1284
+ }
1285
+ function parseDecimal(value, field) {
1286
+ const trimmed = value.trim();
1287
+ if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
1288
+ throw new SwapSdkError(
1289
+ "INVALID_REQUEST",
1290
+ "quote",
1291
+ `${field} must be a non-negative decimal string`
1292
+ );
1293
+ }
1294
+ const [integer = "0", fraction = ""] = trimmed.split(".");
1295
+ return {
1296
+ digits: BigInt(`${integer}${fraction}`),
1297
+ scale: fraction.length
1298
+ };
1299
+ }
1300
+ function parseBurrowDecimal(value, field) {
1301
+ const trimmed = value.trim();
1302
+ const match = /^(?:([0-9]+)(?:\.([0-9]*))?|\.([0-9]+))(?:[eE]([+-]?[0-9]+))?$/.exec(
1303
+ trimmed
1304
+ );
1305
+ if (!match) {
1306
+ throw new SwapSdkError(
1307
+ "INVALID_REQUEST",
1308
+ "quote",
1309
+ `${field} must be a non-negative decimal string`
1310
+ );
1311
+ }
1312
+ const integer = match[1] ?? "0";
1313
+ const fraction = match[2] ?? match[3] ?? "";
1314
+ const exponent = Number(match[4] ?? "0");
1315
+ if (!Number.isSafeInteger(exponent) || Math.abs(exponent) > 1e5) {
1316
+ throw new SwapSdkError(
1317
+ "INVALID_REQUEST",
1318
+ "quote",
1319
+ `${field} exponent is out of range`
1320
+ );
1321
+ }
1322
+ let digits = BigInt(`${integer}${fraction}` || "0");
1323
+ let scale = fraction.length - exponent;
1324
+ if (scale < 0) {
1325
+ digits *= pow10(-scale);
1326
+ scale = 0;
1327
+ }
1328
+ return { digits, scale };
1329
+ }
1330
+ function formatDecimal(value) {
1331
+ if (value.digits === 0n) return "0";
1332
+ if (value.scale === 0) return value.digits.toString();
1333
+ const padded = value.digits.toString().padStart(value.scale + 1, "0");
1334
+ const splitAt = padded.length - value.scale;
1335
+ const integer = padded.slice(0, splitAt);
1336
+ const fraction = padded.slice(splitAt).replace(/0+$/, "");
1337
+ return fraction ? `${integer}.${fraction}` : integer;
1338
+ }
1339
+ function pow10(exponent) {
1340
+ return 10n ** BigInt(exponent);
1341
+ }
1342
+
1209
1343
  // src/mca/quote.ts
1210
1344
  function serializeMcaQuoteRequest(request, signer) {
1211
1345
  const mcaAccountId = request.mcaAccountId.trim();
@@ -1221,13 +1355,10 @@ function serializeMcaQuoteRequest(request, signer) {
1221
1355
  if (!identityKey) {
1222
1356
  throw invalidRequest("signer identityKey is required");
1223
1357
  }
1224
- if (request.flow === "withdraw" && !/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(
1225
- request.collateral.decreaseAmountBurrow.trim()
1226
- )) {
1227
- throw invalidRequest(
1228
- "collateral.decreaseAmountBurrow must be a non-negative decimal string"
1229
- );
1230
- }
1358
+ const decreaseCollateral = request.flow === "withdraw" ? resolveMcaDecreaseCollateral(
1359
+ request.collateral.decreaseAmountBurrow,
1360
+ "collateral.decreaseAmountBurrow"
1361
+ ) : void 0;
1231
1362
  const mca = {
1232
1363
  flow: request.flow,
1233
1364
  mcaAccountId,
@@ -1236,8 +1367,8 @@ function serializeMcaQuoteRequest(request, signer) {
1236
1367
  identityKey
1237
1368
  },
1238
1369
  ...request.flow === "deposit" ? { useAsCollateral: request.collateral.useAsCollateral } : {
1239
- needDecreaseCollateral: request.collateral.needDecrease,
1240
- decreaseCollateralAmountBurrow: request.collateral.decreaseAmountBurrow,
1370
+ needDecreaseCollateral: decreaseCollateral.needDecrease,
1371
+ decreaseCollateralAmountBurrow: decreaseCollateral.decreaseAmountBurrow,
1241
1372
  ...request.collateral.withdrawAll ? { withdrawAll: true } : {}
1242
1373
  },
1243
1374
  ...request.recipientMsgSignatures ? { recipientMsgSignatures: [...request.recipientMsgSignatures] } : {},
@@ -1892,7 +2023,8 @@ var McaSwapService = class {
1892
2023
  is_cross_chain: true,
1893
2024
  tx_type: "mca-withdraw-relayer",
1894
2025
  multi_addr: input.quote.mcaAccountId,
1895
- swapId: orderId
2026
+ swapId: orderId,
2027
+ ...request.confidentiality ? { confidentiality: request.confidentiality } : {}
1896
2028
  };
1897
2029
  this.relayerReports.set(executionId, reportRequest);
1898
2030
  const result = {
@@ -2289,10 +2421,30 @@ var SwapClient = class {
2289
2421
  getHistoryRaw(params, options = {}) {
2290
2422
  return this.api.getHistory(params, options);
2291
2423
  }
2424
+ createHistoryAuthChallenge(request, options = {}) {
2425
+ return this.api.createHistoryAuthChallenge(request, options);
2426
+ }
2427
+ verifyHistoryAuthChallenge(request, options = {}) {
2428
+ return this.api.verifyHistoryAuthChallenge(request, options);
2429
+ }
2430
+ async authorizeConfidentialHistory(request, signChallenge, options = {}) {
2431
+ const challenge = await this.createHistoryAuthChallenge(request, options);
2432
+ assertHistoryChallengeMatchesRequest(challenge, request);
2433
+ const proof = await signChallenge(challenge);
2434
+ const verifyRequest = {
2435
+ challengeId: challenge.challengeId,
2436
+ proof
2437
+ };
2438
+ const token = await this.verifyHistoryAuthChallenge(verifyRequest, options);
2439
+ assertHistoryTokenMatchesChallenge(token, challenge);
2440
+ return token;
2441
+ }
2292
2442
  async getHistory(request, options = {}) {
2293
2443
  const raw = await this.api.getHistory(
2294
2444
  {
2295
2445
  sender: request.sender,
2446
+ ...request.mode ? { mode: request.mode } : {},
2447
+ ...request.walletToken ? { walletToken: request.walletToken } : {},
2296
2448
  ...request.page !== void 0 ? { pageNumber: request.page } : {},
2297
2449
  ...request.pageSize !== void 0 ? { pageSize: request.pageSize } : {}
2298
2450
  },
@@ -2343,10 +2495,39 @@ var SwapClient = class {
2343
2495
  router: build.router,
2344
2496
  tx_type: reportContext?.txType ?? (build.isCrossChain ? "cross-chain" : "same-chain"),
2345
2497
  ...reportContext?.multiAddr ? { multi_addr: reportContext.multiAddr } : {},
2346
- ...reportContext?.swapId ?? result.orderId ? { swapId: reportContext?.swapId ?? result.orderId } : {}
2498
+ ...reportContext?.swapId ?? result.orderId ? { swapId: reportContext?.swapId ?? result.orderId } : {},
2499
+ ...request.confidentiality ? { confidentiality: request.confidentiality } : {}
2347
2500
  };
2348
2501
  }
2349
2502
  };
2503
+ function assertHistoryChallengeMatchesRequest(challenge, request) {
2504
+ const expectedMca = request.mcaAccountId?.trim();
2505
+ const principalMatches = expectedMca ? challenge.principalType === "mca" && challenge.mcaAccountId?.toLowerCase() === expectedMca.toLowerCase() : challenge.principalType === "wallet" && !challenge.mcaAccountId;
2506
+ const identityMatches = request.identityKey ? normalizeHistoryIdentity(challenge.chainFamily, challenge.identityKey) === normalizeHistoryIdentity(challenge.chainFamily, request.identityKey) : true;
2507
+ if (challenge.chainFamily !== request.chainFamily || challenge.chainId !== request.chainId || normalizeHistoryAddress(challenge.chainFamily, challenge.walletAddress) !== normalizeHistoryAddress(request.chainFamily, request.walletAddress) || !identityMatches || !principalMatches || !challenge.queryAddress) {
2508
+ throw new SwapSdkError(
2509
+ "INVALID_API_RESPONSE",
2510
+ "history",
2511
+ "Confidential history challenge does not match the requested wallet or MCA"
2512
+ );
2513
+ }
2514
+ }
2515
+ function assertHistoryTokenMatchesChallenge(token, challenge) {
2516
+ const principalMatches = token.principalType === challenge.principalType && (challenge.principalType === "mca" ? token.mcaAccountId?.toLowerCase() === challenge.mcaAccountId?.toLowerCase() : !token.mcaAccountId);
2517
+ if (!principalMatches || token.queryAddress !== challenge.queryAddress) {
2518
+ throw new SwapSdkError(
2519
+ "INVALID_API_RESPONSE",
2520
+ "history",
2521
+ "Confidential history authorization returned a different principal"
2522
+ );
2523
+ }
2524
+ }
2525
+ function normalizeHistoryAddress(chain, value) {
2526
+ return chain === "evm" || chain === "aptos" || chain === "sui" ? value.toLowerCase() : value;
2527
+ }
2528
+ function normalizeHistoryIdentity(chain, value) {
2529
+ return chain === "evm" || chain === "aptos" || chain === "sui" || chain === "btc" || chain === "zcash" ? value.toLowerCase().replace(/^0x/, "") : value;
2530
+ }
2350
2531
  function isMcaQuoteRequest(request) {
2351
2532
  if (!("flow" in request) || !("mcaAccountId" in request)) return false;
2352
2533
  const flow = Reflect.get(request, "flow");
@@ -2393,48 +2574,6 @@ function delay(ms, signal) {
2393
2574
  });
2394
2575
  }
2395
2576
 
2396
- // src/mca/collateral.ts
2397
- function resolveMcaWithdrawPolicy(input) {
2398
- const collateral = parseDecimal(input.collateralBalance, "collateralBalance");
2399
- const available = parseDecimal(input.availableBalance, "availableBalance");
2400
- const amount = parseDecimal(input.amountIn, "amountIn");
2401
- const needDecrease = collateral.digits > 0n;
2402
- return {
2403
- needDecrease,
2404
- decreaseAmountBurrow: needDecrease ? input.collateralBalance.trim() : "0",
2405
- withdrawAll: input.isMax || available.digits > 0n && isAtLeastWithdrawAllThreshold(amount, available)
2406
- };
2407
- }
2408
- function isAtLeastWithdrawAllThreshold(amount, available) {
2409
- const [amountScaled, availableScaled] = alignScale(amount, available);
2410
- return amountScaled * 1000000n >= availableScaled * 999999n;
2411
- }
2412
- function alignScale(a, b) {
2413
- const scale = Math.max(a.scale, b.scale);
2414
- return [
2415
- a.digits * pow10(scale - a.scale),
2416
- b.digits * pow10(scale - b.scale)
2417
- ];
2418
- }
2419
- function parseDecimal(value, field) {
2420
- const trimmed = value.trim();
2421
- if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2422
- throw new SwapSdkError(
2423
- "INVALID_REQUEST",
2424
- "quote",
2425
- `${field} must be a non-negative decimal string`
2426
- );
2427
- }
2428
- const [integer = "0", fraction = ""] = trimmed.split(".");
2429
- return {
2430
- digits: BigInt(`${integer}${fraction}`),
2431
- scale: fraction.length
2432
- };
2433
- }
2434
- function pow10(exponent) {
2435
- return 10n ** BigInt(exponent);
2436
- }
2437
-
2438
- export { ApiClient, DEFAULT_MCA_SIGNER_PRIORITY, ExecutorRegistry, SwapClient, SwapSdkError, asSwapSdkError, assertBaseUnitAmount, buildMcaWithdrawRelayerRequest, buildNearMcaWithdrawTransactions, createExecutionId, extractMcaWithdrawBusiness, extractMcaWithdrawDepositAddress, extractMcaWithdrawSignerWallet, formatMcaWallet, formatUnits, fromApiChain, isSameMcaSignerIdentity, normalizeBuild, normalizeHistory, normalizeHistoryStatus, normalizeMcaQuote, normalizeOrderStatus, normalizeQuote, parseUnits, resolveMcaWithdrawPolicy, selectMcaSigner, serializeMcaQuoteRequest, serializeQuoteRequest, toApiAssetAddress, toApiChain };
2577
+ export { ApiClient, DEFAULT_MCA_SIGNER_PRIORITY, ExecutorRegistry, SwapClient, SwapSdkError, asSwapSdkError, assertBaseUnitAmount, buildMcaWithdrawRelayerRequest, buildNearMcaWithdrawTransactions, createExecutionId, extractMcaWithdrawBusiness, extractMcaWithdrawDepositAddress, extractMcaWithdrawSignerWallet, formatMcaWallet, formatUnits, fromApiChain, isSameMcaSignerIdentity, normalizeBuild, normalizeHistory, normalizeHistoryStatus, normalizeMcaQuote, normalizeOrderStatus, normalizeQuote, parseUnits, resolveMcaDecreaseCollateral, resolveMcaRequiredCollateralDecrease, resolveMcaWithdrawPolicy, selectMcaSigner, serializeMcaQuoteRequest, serializeQuoteRequest, toApiAssetAddress, toApiChain };
2439
2578
  //# sourceMappingURL=index.mjs.map
2440
2579
  //# sourceMappingURL=index.mjs.map