@rhea-finance/cross-chain-aggregation-dex 2.0.4 → 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
  };
@@ -1213,6 +1234,112 @@ function normalizeTimestamp(value) {
1213
1234
  return Number.isNaN(date.getTime()) ? void 0 : date.toISOString();
1214
1235
  }
1215
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
+
1216
1343
  // src/mca/quote.ts
1217
1344
  function serializeMcaQuoteRequest(request, signer) {
1218
1345
  const mcaAccountId = request.mcaAccountId.trim();
@@ -1228,13 +1355,10 @@ function serializeMcaQuoteRequest(request, signer) {
1228
1355
  if (!identityKey) {
1229
1356
  throw invalidRequest("signer identityKey is required");
1230
1357
  }
1231
- if (request.flow === "withdraw" && !/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(
1232
- request.collateral.decreaseAmountBurrow.trim()
1233
- )) {
1234
- throw invalidRequest(
1235
- "collateral.decreaseAmountBurrow must be a non-negative decimal string"
1236
- );
1237
- }
1358
+ const decreaseCollateral = request.flow === "withdraw" ? resolveMcaDecreaseCollateral(
1359
+ request.collateral.decreaseAmountBurrow,
1360
+ "collateral.decreaseAmountBurrow"
1361
+ ) : void 0;
1238
1362
  const mca = {
1239
1363
  flow: request.flow,
1240
1364
  mcaAccountId,
@@ -1243,8 +1367,8 @@ function serializeMcaQuoteRequest(request, signer) {
1243
1367
  identityKey
1244
1368
  },
1245
1369
  ...request.flow === "deposit" ? { useAsCollateral: request.collateral.useAsCollateral } : {
1246
- needDecreaseCollateral: request.collateral.needDecrease,
1247
- decreaseCollateralAmountBurrow: request.collateral.decreaseAmountBurrow,
1370
+ needDecreaseCollateral: decreaseCollateral.needDecrease,
1371
+ decreaseCollateralAmountBurrow: decreaseCollateral.decreaseAmountBurrow,
1248
1372
  ...request.collateral.withdrawAll ? { withdrawAll: true } : {}
1249
1373
  },
1250
1374
  ...request.recipientMsgSignatures ? { recipientMsgSignatures: [...request.recipientMsgSignatures] } : {},
@@ -1899,7 +2023,8 @@ var McaSwapService = class {
1899
2023
  is_cross_chain: true,
1900
2024
  tx_type: "mca-withdraw-relayer",
1901
2025
  multi_addr: input.quote.mcaAccountId,
1902
- swapId: orderId
2026
+ swapId: orderId,
2027
+ ...request.confidentiality ? { confidentiality: request.confidentiality } : {}
1903
2028
  };
1904
2029
  this.relayerReports.set(executionId, reportRequest);
1905
2030
  const result = {
@@ -2296,10 +2421,30 @@ var SwapClient = class {
2296
2421
  getHistoryRaw(params, options = {}) {
2297
2422
  return this.api.getHistory(params, options);
2298
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
+ }
2299
2442
  async getHistory(request, options = {}) {
2300
2443
  const raw = await this.api.getHistory(
2301
2444
  {
2302
2445
  sender: request.sender,
2446
+ ...request.mode ? { mode: request.mode } : {},
2447
+ ...request.walletToken ? { walletToken: request.walletToken } : {},
2303
2448
  ...request.page !== void 0 ? { pageNumber: request.page } : {},
2304
2449
  ...request.pageSize !== void 0 ? { pageSize: request.pageSize } : {}
2305
2450
  },
@@ -2350,10 +2495,39 @@ var SwapClient = class {
2350
2495
  router: build.router,
2351
2496
  tx_type: reportContext?.txType ?? (build.isCrossChain ? "cross-chain" : "same-chain"),
2352
2497
  ...reportContext?.multiAddr ? { multi_addr: reportContext.multiAddr } : {},
2353
- ...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 } : {}
2354
2500
  };
2355
2501
  }
2356
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
+ }
2357
2531
  function isMcaQuoteRequest(request) {
2358
2532
  if (!("flow" in request) || !("mcaAccountId" in request)) return false;
2359
2533
  const flow = Reflect.get(request, "flow");
@@ -2400,48 +2574,6 @@ function delay(ms, signal) {
2400
2574
  });
2401
2575
  }
2402
2576
 
2403
- // src/mca/collateral.ts
2404
- function resolveMcaWithdrawPolicy(input) {
2405
- const collateral = parseDecimal(input.collateralBalance, "collateralBalance");
2406
- const available = parseDecimal(input.availableBalance, "availableBalance");
2407
- const amount = parseDecimal(input.amountIn, "amountIn");
2408
- const needDecrease = collateral.digits > 0n;
2409
- return {
2410
- needDecrease,
2411
- decreaseAmountBurrow: needDecrease ? input.collateralBalance.trim() : "0",
2412
- withdrawAll: input.isMax || available.digits > 0n && isAtLeastWithdrawAllThreshold(amount, available)
2413
- };
2414
- }
2415
- function isAtLeastWithdrawAllThreshold(amount, available) {
2416
- const [amountScaled, availableScaled] = alignScale(amount, available);
2417
- return amountScaled * 1000000n >= availableScaled * 999999n;
2418
- }
2419
- function alignScale(a, b) {
2420
- const scale = Math.max(a.scale, b.scale);
2421
- return [
2422
- a.digits * pow10(scale - a.scale),
2423
- b.digits * pow10(scale - b.scale)
2424
- ];
2425
- }
2426
- function parseDecimal(value, field) {
2427
- const trimmed = value.trim();
2428
- if (!/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed)) {
2429
- throw new SwapSdkError(
2430
- "INVALID_REQUEST",
2431
- "quote",
2432
- `${field} must be a non-negative decimal string`
2433
- );
2434
- }
2435
- const [integer = "0", fraction = ""] = trimmed.split(".");
2436
- return {
2437
- digits: BigInt(`${integer}${fraction}`),
2438
- scale: fraction.length
2439
- };
2440
- }
2441
- function pow10(exponent) {
2442
- return 10n ** BigInt(exponent);
2443
- }
2444
-
2445
- 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 };
2446
2578
  //# sourceMappingURL=index.mjs.map
2447
2579
  //# sourceMappingURL=index.mjs.map