@zkp2p/sdk 0.7.1 → 0.7.2

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
@@ -1,8 +1,8 @@
1
1
  export { TAKER_TIER_CAPS, TAKER_TIER_FEE_DISCOUNT_BPS, TAKER_TIER_ORDER, TAKER_TIER_SCHEDULE, ZERO_RATE_MANAGER_ID, classifyDelegationState, getDelegationRoute, getNextTakerTier, getTakerTierFeeDiscountBps, isZeroRateManagerId, normalizeRateManagerId, normalizeRegistry } from './chunk-BQINCOSO.mjs';
2
2
  import { ValidationError, APIError, NetworkError } from './chunk-GHQK65J2.mjs';
3
3
  export { APIError, ContractError, ErrorCode, NetworkError, ValidationError, ZKP2PError } from './chunk-GHQK65J2.mjs';
4
- import { getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-NMIFJSZ3.mjs';
5
- export { asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getGatingServiceAddress, getPaymentMethodsCatalog, getRateManagerContracts, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-NMIFJSZ3.mjs';
4
+ import { getContracts, getRateManagerContracts, getPaymentMethodsCatalog, resolvePaymentMethodHashFromCatalog, getGatingServiceAddress, parseBigIntLike, resolveFiatCurrencyBytes32, resolvePaymentMethodNameFromHash } from './chunk-ZM4ZP5GQ.mjs';
5
+ export { asciiToBytes32, enrichPvDepositView, enrichPvIntentView, ensureBytes32, getContracts, getGatingServiceAddress, getPaymentMethodsCatalog, getRateManagerContracts, parseDepositView, parseIntentView, resolveFiatCurrencyBytes32, resolvePaymentMethodHash, resolvePaymentMethodHashFromCatalog, resolvePaymentMethodNameFromHash } from './chunk-ZM4ZP5GQ.mjs';
6
6
  import { Currency, currencyKeccak256 } from './chunk-ZFBH4HD7.mjs';
7
7
  export { Currency, currencyInfo, getCurrencyCodeFromHash, getCurrencyInfoFromCountryCode, getCurrencyInfoFromHash, isSupportedCurrencyHash, mapConversionRatesToOnchainMinRate } from './chunk-ZFBH4HD7.mjs';
8
8
  import './chunk-J5LGTIGS.mjs';
@@ -1125,6 +1125,44 @@ function resolvePlatformAttestationConfig(platformName) {
1125
1125
  return config;
1126
1126
  }
1127
1127
 
1128
+ // src/utils/logger.ts
1129
+ var currentLevel = "info";
1130
+ function setLogLevel(level) {
1131
+ currentLevel = level;
1132
+ }
1133
+ function shouldLog(level) {
1134
+ switch (currentLevel) {
1135
+ case "debug":
1136
+ return true;
1137
+ case "info":
1138
+ return level !== "debug";
1139
+ case "error":
1140
+ return level === "error";
1141
+ default:
1142
+ return true;
1143
+ }
1144
+ }
1145
+ var logger = {
1146
+ debug: (...args) => {
1147
+ if (shouldLog("debug")) {
1148
+ console.log("[DEBUG]", ...args);
1149
+ }
1150
+ },
1151
+ info: (...args) => {
1152
+ if (shouldLog("info")) {
1153
+ console.log("[INFO]", ...args);
1154
+ }
1155
+ },
1156
+ warn: (...args) => {
1157
+ if (shouldLog("info")) {
1158
+ console.warn("[WARN]", ...args);
1159
+ }
1160
+ },
1161
+ error: (...args) => {
1162
+ console.error("[ERROR]", ...args);
1163
+ }
1164
+ };
1165
+
1128
1166
  // src/client/IntentOperations.ts
1129
1167
  var INTENT_MIN_AT_SIGNAL_ABI = [
1130
1168
  {
@@ -1638,16 +1676,24 @@ var IntentOperations = class {
1638
1676
  async readIntentMinAtSignal(intentHash, orchestratorAddress) {
1639
1677
  const address = orchestratorAddress ?? this.config.getOrchestratorV2Address();
1640
1678
  if (!address) return void 0;
1679
+ const read = async () => this.config.getPublicClient().readContract({
1680
+ address,
1681
+ abi: INTENT_MIN_AT_SIGNAL_ABI,
1682
+ functionName: "getIntentMinAtSignal",
1683
+ args: [intentHash]
1684
+ });
1641
1685
  try {
1642
- const value = await this.config.getPublicClient().readContract({
1643
- address,
1644
- abi: INTENT_MIN_AT_SIGNAL_ABI,
1645
- functionName: "getIntentMinAtSignal",
1646
- args: [intentHash]
1647
- });
1648
- return value.toString();
1649
- } catch {
1650
- return void 0;
1686
+ return (await read()).toString();
1687
+ } catch (error) {
1688
+ logger.warn(
1689
+ `[sdk] getIntentMinAtSignal read failed for ${intentHash}; retrying once`,
1690
+ error instanceof Error ? error.message : error
1691
+ );
1692
+ try {
1693
+ return (await read()).toString();
1694
+ } catch {
1695
+ return void 0;
1696
+ }
1651
1697
  }
1652
1698
  }
1653
1699
  };
@@ -1932,7 +1978,7 @@ var ProtocolViewerReader = class {
1932
1978
  if (inputCount === null) {
1933
1979
  throw new Error("Configured ProtocolViewer ABI does not expose getDeposit");
1934
1980
  }
1935
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-N5SJ4KHJ.mjs');
1981
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-GG6UQKLO.mjs');
1936
1982
  if (inputCount >= 3) {
1937
1983
  return tryContexts(
1938
1984
  protocolViewerContexts,
@@ -2011,7 +2057,7 @@ var ProtocolViewerReader = class {
2011
2057
  return Promise.all(ids.map((id) => this.config.host.getPvDepositById(id)));
2012
2058
  }
2013
2059
  const bn = ids.map((id) => typeof id === "bigint" ? id : parseRawDepositId(id));
2014
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-N5SJ4KHJ.mjs');
2060
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-GG6UQKLO.mjs');
2015
2061
  if (inputCount >= 2) {
2016
2062
  const requests = ids.map((id, index) => ({
2017
2063
  index,
@@ -2116,7 +2162,7 @@ var ProtocolViewerReader = class {
2116
2162
  if (!protocolViewerAddress || !protocolViewerAbi || inputCount === null) {
2117
2163
  return this.config.host.getPvAccountDepositsFromIndexer(owner);
2118
2164
  }
2119
- const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-N5SJ4KHJ.mjs');
2165
+ const { parseDepositView: parseDepositView2 } = await import('./protocolViewerParsers-GG6UQKLO.mjs');
2120
2166
  const { address, abi } = this.config.host.requireProtocolViewer();
2121
2167
  if (inputCount >= 2) {
2122
2168
  const readAndFilter = async (raw2) => {
@@ -2187,7 +2233,7 @@ var ProtocolViewerReader = class {
2187
2233
  if (protocolViewerEntries.length === 0) {
2188
2234
  throw new Error("ProtocolViewer not available for this network");
2189
2235
  }
2190
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-N5SJ4KHJ.mjs');
2236
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-GG6UQKLO.mjs');
2191
2237
  const intentsByHash = /* @__PURE__ */ new Map();
2192
2238
  let attemptedRead = false;
2193
2239
  let hadSuccessfulRead = false;
@@ -2295,7 +2341,7 @@ var ProtocolViewerReader = class {
2295
2341
  if (protocolViewerEntries.length === 0) {
2296
2342
  throw new Error("ProtocolViewer not available for this network");
2297
2343
  }
2298
- const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-N5SJ4KHJ.mjs');
2344
+ const { parseIntentView: parseIntentView2 } = await import('./protocolViewerParsers-GG6UQKLO.mjs');
2299
2345
  let lastError;
2300
2346
  for (const pvEntry of protocolViewerEntries) {
2301
2347
  const inputCount = this.pvEntryFunctionInputCount(pvEntry, "getIntent");
@@ -2350,478 +2396,162 @@ var ProtocolViewerReader = class {
2350
2396
  }
2351
2397
  };
2352
2398
 
2353
- // src/client/VaultOperations.ts
2354
- var VaultOperations = class {
2355
- constructor(config) {
2356
- this.config = config;
2399
+ // src/indexer/client.ts
2400
+ var IndexerHttpError = class extends Error {
2401
+ constructor(status, statusText, options) {
2402
+ super(`Indexer request failed: ${status} ${statusText}`);
2403
+ this.name = "IndexerHttpError";
2404
+ this.status = status;
2405
+ this.retryAfterSeconds = options?.retryAfterSeconds;
2357
2406
  }
2358
- supportsInlineOracleRateConfig(params) {
2359
- const escrowContext = this.config.host.resolveEscrowContext({
2360
- escrowAddress: params?.escrowAddress
2361
- });
2362
- return escrowCurrencyHasOracleConfig(escrowContext.abi);
2407
+ };
2408
+ function parseRetryAfterSeconds(rawHeader) {
2409
+ if (!rawHeader) return void 0;
2410
+ const parsedSeconds = Number(rawHeader);
2411
+ if (Number.isFinite(parsedSeconds) && parsedSeconds >= 0) {
2412
+ return Math.ceil(parsedSeconds);
2363
2413
  }
2364
- resolveRateManagerRegistryContract(registryAddress) {
2365
- const abi = this.config.getRateManagerRegistryAbi();
2366
- if (!abi) {
2367
- throw this.buildRateManagerUnavailableError("Rate manager registry not available");
2368
- }
2369
- if (registryAddress) {
2370
- return {
2371
- address: registryAddress,
2372
- abi
2373
- };
2374
- }
2375
- const address = this.config.getRateManagerRegistryAddress();
2376
- if (!address) {
2377
- throw this.buildRateManagerUnavailableError("Rate manager registry not available");
2414
+ const parsedDateMs = Date.parse(rawHeader);
2415
+ if (!Number.isFinite(parsedDateMs)) return void 0;
2416
+ const secondsUntilRetry = Math.ceil((parsedDateMs - Date.now()) / 1e3);
2417
+ return Math.max(0, secondsUntilRetry);
2418
+ }
2419
+ function createAbortError() {
2420
+ const error = new Error("The operation was aborted");
2421
+ error.name = "AbortError";
2422
+ return error;
2423
+ }
2424
+ function delay(ms, signal) {
2425
+ if (ms <= 0) {
2426
+ return Promise.resolve();
2427
+ }
2428
+ return new Promise((resolve, reject) => {
2429
+ if (signal?.aborted) {
2430
+ reject(createAbortError());
2431
+ return;
2378
2432
  }
2379
- return {
2380
- address,
2381
- abi
2433
+ const timer = setTimeout(() => {
2434
+ signal?.removeEventListener("abort", onAbort);
2435
+ resolve();
2436
+ }, ms);
2437
+ const onAbort = () => {
2438
+ clearTimeout(timer);
2439
+ signal?.removeEventListener("abort", onAbort);
2440
+ reject(createAbortError());
2382
2441
  };
2442
+ signal?.addEventListener("abort", onAbort);
2443
+ });
2444
+ }
2445
+ var IndexerClient = class {
2446
+ constructor(endpoint, options = {}) {
2447
+ this.endpoint = endpoint;
2448
+ this.options = options;
2449
+ this.hasLoggedTokenProviderError = false;
2383
2450
  }
2384
- buildRateManagerUnavailableError(reason) {
2385
- const initError = this.config.getRateManagerInitError();
2386
- if (!initError) {
2387
- return new Error(reason);
2451
+ async resolveAuthorizationToken() {
2452
+ if (this.options.getAuthorizationToken) {
2453
+ try {
2454
+ const token = await this.options.getAuthorizationToken();
2455
+ return token ?? void 0;
2456
+ } catch (error) {
2457
+ if (this.options.onAuthorizationTokenError) {
2458
+ this.options.onAuthorizationTokenError(error);
2459
+ } else if (!this.hasLoggedTokenProviderError) {
2460
+ this.hasLoggedTokenProviderError = true;
2461
+ console.warn(
2462
+ "[IndexerClient] getAuthorizationToken failed; continuing without Authorization header",
2463
+ error
2464
+ );
2465
+ }
2466
+ return void 0;
2467
+ }
2388
2468
  }
2389
- return new Error(
2390
- `${reason}. Rate manager contracts failed to initialize: ${initError.message}`
2391
- );
2469
+ return this.options.authorizationToken;
2392
2470
  }
2393
- buildCreateRateManagerConfig(config) {
2394
- const registryAbi = this.config.getRateManagerRegistryAbi();
2395
- const includeDepositHook = abiTupleHasComponent(
2396
- registryAbi,
2397
- "createRateManager",
2398
- "depositHook"
2399
- );
2400
- const includeMinLiquidity = abiTupleHasComponent(
2401
- registryAbi,
2402
- "createRateManager",
2403
- "minLiquidity"
2404
- );
2405
- const result = {
2406
- manager: config.manager,
2407
- feeRecipient: config.feeRecipient,
2408
- maxFee: config.maxFee,
2409
- fee: config.fee
2410
- };
2411
- if (includeDepositHook) {
2412
- result.depositHook = config.depositHook ?? ZERO_ADDRESS;
2471
+ async _post(request, init) {
2472
+ const token = await this.resolveAuthorizationToken();
2473
+ const headers2 = new Headers(init?.headers);
2474
+ if (!headers2.has("Content-Type")) {
2475
+ headers2.set("Content-Type", "application/json");
2413
2476
  }
2414
- if (includeMinLiquidity) {
2415
- result.minLiquidity = config.minLiquidity ?? 0n;
2477
+ if (token && !headers2.has("Authorization")) {
2478
+ headers2.set("Authorization", token.startsWith("Bearer ") ? token : `Bearer ${token}`);
2416
2479
  }
2417
- result.name = config.name;
2418
- result.uri = config.uri;
2419
- return result;
2420
- }
2421
- buildSetRateManagerConfigArgs(params) {
2422
- const registryAbi = this.config.getRateManagerRegistryAbi();
2423
- const includeHook = abiFunctionHasInput(registryAbi, "setRateManagerConfig", "_newHook") || abiFunctionHasInput(registryAbi, "setRateManagerConfig", "newHook");
2424
- if (includeHook) {
2425
- return [
2426
- params.rateManagerId,
2427
- params.newManager,
2428
- params.newFeeRecipient,
2429
- params.newHook ?? ZERO_ADDRESS,
2430
- params.newName,
2431
- params.newUri
2432
- ];
2480
+ if (this.options.apiKey && !headers2.has("x-api-key")) {
2481
+ headers2.set("x-api-key", this.options.apiKey);
2433
2482
  }
2434
- return [
2435
- params.rateManagerId,
2436
- params.newManager,
2437
- params.newFeeRecipient,
2438
- params.newName,
2439
- params.newUri
2440
- ];
2441
- }
2442
- prepareRateManagerRegistryTransaction(opts) {
2443
- const contract = this.resolveRateManagerRegistryContract(opts.registry);
2444
- const functionName = resolveAbiFunctionName(contract.abi, opts.functionNames);
2445
- return this.config.host.prepareContractTransaction({
2446
- address: contract.address,
2447
- abi: contract.abi,
2448
- functionName,
2449
- args: opts.args,
2450
- txOverrides: opts.txOverrides
2451
- });
2452
- }
2453
- prepareCreateRateManagerTransaction(params) {
2454
- return this.prepareRateManagerRegistryTransaction({
2455
- functionNames: ["createRateManager"],
2456
- args: [this.buildCreateRateManagerConfig(params.config)],
2457
- txOverrides: params.txOverrides
2458
- });
2459
- }
2460
- prepareSetVaultRateTransaction(params) {
2461
- return this.prepareRateManagerRegistryTransaction({
2462
- functionNames: ["setRate", "setMinRate"],
2463
- args: [params.rateManagerId, params.paymentMethodHash, params.currencyHash, params.rate],
2464
- txOverrides: params.txOverrides
2465
- });
2466
- }
2467
- prepareSetVaultRatesBatchTransaction(params) {
2468
- return this.prepareRateManagerRegistryTransaction({
2469
- functionNames: ["setRateBatch", "setMinRatesBatch"],
2470
- args: [params.rateManagerId, params.paymentMethods, params.currencies, params.rates],
2471
- txOverrides: params.txOverrides
2472
- });
2473
- }
2474
- prepareSetOracleRateConfigTransaction(params) {
2475
- const escrowContext = this.config.host.resolveEscrowContext({
2476
- escrowAddress: params.escrowAddress,
2477
- depositId: params.depositId
2483
+ const res = await fetch(this.endpoint, {
2484
+ method: "POST",
2485
+ headers: headers2,
2486
+ body: JSON.stringify(request),
2487
+ cache: "no-store",
2488
+ ...init
2478
2489
  });
2479
- if (escrowContext.version !== "v2") {
2480
- throw new Error("setOracleRateConfig requires EscrowV2");
2490
+ if (!res.ok) {
2491
+ throw new IndexerHttpError(res.status, res.statusText, {
2492
+ retryAfterSeconds: parseRetryAfterSeconds(res.headers.get("Retry-After"))
2493
+ });
2481
2494
  }
2482
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfig"]);
2483
- return this.config.host.prepareEscrowTransaction({
2484
- functionName,
2485
- args: [
2486
- parseRawDepositId(params.depositId),
2487
- params.paymentMethodHash,
2488
- params.currencyHash,
2489
- normalizeOracleRateConfig(params.config)
2490
- ],
2491
- txOverrides: params.txOverrides,
2492
- escrowAddress: escrowContext.address,
2493
- escrowAbi: escrowContext.abi
2494
- });
2495
- }
2496
- prepareRemoveOracleRateConfigTransaction(params) {
2497
- const escrowContext = this.config.host.resolveEscrowContext({
2498
- escrowAddress: params.escrowAddress,
2499
- depositId: params.depositId
2500
- });
2501
- if (escrowContext.version !== "v2") {
2502
- throw new Error("removeOracleRateConfig requires EscrowV2");
2503
- }
2504
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["removeOracleRateConfig"]);
2505
- return this.config.host.prepareEscrowTransaction({
2506
- functionName,
2507
- args: [parseRawDepositId(params.depositId), params.paymentMethodHash, params.currencyHash],
2508
- txOverrides: params.txOverrides,
2509
- escrowAddress: escrowContext.address,
2510
- escrowAbi: escrowContext.abi
2511
- });
2512
- }
2513
- prepareSetOracleRateConfigBatchTransaction(params) {
2514
- const escrowContext = this.config.host.resolveEscrowContext({
2515
- escrowAddress: params.escrowAddress,
2516
- depositId: params.depositId
2517
- });
2518
- if (escrowContext.version !== "v2") {
2519
- throw new Error("setOracleRateConfigBatch requires EscrowV2");
2520
- }
2521
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfigBatch"]);
2522
- return this.config.host.prepareEscrowTransaction({
2523
- functionName,
2524
- args: [
2525
- parseRawDepositId(params.depositId),
2526
- params.paymentMethods,
2527
- params.currencies,
2528
- params.configs.map((group) => group.map((config) => normalizeOracleRateConfig(config)))
2529
- ],
2530
- txOverrides: params.txOverrides,
2531
- escrowAddress: escrowContext.address,
2532
- escrowAbi: escrowContext.abi
2533
- });
2534
- }
2535
- prepareUpdateCurrencyConfigBatchTransaction(params) {
2536
- const escrowContext = this.config.host.resolveEscrowContext({
2537
- escrowAddress: params.escrowAddress,
2538
- depositId: params.depositId
2539
- });
2540
- if (escrowContext.version !== "v2") {
2541
- throw new Error("updateCurrencyConfigBatch requires EscrowV2");
2542
- }
2543
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["updateCurrencyConfigBatch"]);
2544
- return this.config.host.prepareEscrowTransaction({
2545
- functionName,
2546
- args: [
2547
- parseRawDepositId(params.depositId),
2548
- params.paymentMethods,
2549
- params.updates.map(
2550
- (group) => group.map((update) => ({
2551
- code: update.code,
2552
- minConversionRate: typeof update.minConversionRate === "bigint" ? update.minConversionRate : BigInt(update.minConversionRate),
2553
- updateOracle: update.updateOracle,
2554
- oracleRateConfig: normalizeOracleRateConfig(update.oracleRateConfig)
2555
- }))
2556
- )
2557
- ],
2558
- txOverrides: params.txOverrides,
2559
- escrowAddress: escrowContext.address,
2560
- escrowAbi: escrowContext.abi
2561
- });
2562
- }
2563
- prepareDeactivateCurrenciesBatchTransaction(params) {
2564
- const escrowContext = this.config.host.resolveEscrowContext({
2565
- escrowAddress: params.escrowAddress,
2566
- depositId: params.depositId
2567
- });
2568
- if (escrowContext.version !== "v2") {
2569
- throw new Error("deactivateCurrenciesBatch requires EscrowV2");
2495
+ const json = await res.json();
2496
+ if (json.errors?.length) {
2497
+ const msg = json.errors.map((e) => e.message).join(", ");
2498
+ throw new Error(`GraphQL errors: ${msg}`);
2570
2499
  }
2571
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["deactivateCurrenciesBatch"]);
2572
- return this.config.host.prepareEscrowTransaction({
2573
- functionName,
2574
- args: [parseRawDepositId(params.depositId), params.paymentMethods, params.currencyCodes],
2575
- txOverrides: params.txOverrides,
2576
- escrowAddress: escrowContext.address,
2577
- escrowAbi: escrowContext.abi
2578
- });
2579
- }
2580
- prepareSetVaultConfigTransaction(params) {
2581
- return this.prepareRateManagerRegistryTransaction({
2582
- functionNames: ["setRateManagerConfig"],
2583
- args: this.buildSetRateManagerConfigArgs(params),
2584
- txOverrides: params.txOverrides
2585
- });
2500
+ if (!json.data) throw new Error("No data returned from indexer");
2501
+ return json.data;
2586
2502
  }
2587
- async getDepositRateManager(escrow, depositId) {
2588
- const id = parseRawDepositId(depositId);
2589
- const escrowContext = this.config.host.resolveEscrowContext({
2590
- escrowAddress: escrow,
2591
- depositId
2592
- });
2593
- if (getRateManagerReadFunction(escrowContext.abi, "getDepositRateManager")) {
2594
- const result = await this.config.getPublicClient().readContract({
2595
- address: escrowContext.address,
2596
- abi: escrowContext.abi,
2597
- functionName: "getDepositRateManager",
2598
- args: [id]
2599
- });
2600
- if (result && result.length >= 2) {
2601
- return {
2602
- registry: result[0],
2603
- rateManagerId: result[1]
2604
- };
2503
+ async query(request, init) {
2504
+ const retries = Math.max(0, init?.retries ?? 1);
2505
+ const rateLimitRetries = Math.max(0, init?.rateLimitRetries ?? 2);
2506
+ const maxAttempts = 1 + Math.max(retries, rateLimitRetries);
2507
+ const {
2508
+ retries: _unusedRetries,
2509
+ rateLimitRetries: _unusedRateLimitRetries,
2510
+ ...requestInit
2511
+ } = init ?? {};
2512
+ let attempts = 0;
2513
+ let rateLimitAttempt = 0;
2514
+ let standardRetryAttempt = 0;
2515
+ let lastErr;
2516
+ while (attempts < maxAttempts) {
2517
+ try {
2518
+ return await this._post(request, requestInit);
2519
+ } catch (e) {
2520
+ lastErr = e;
2521
+ attempts += 1;
2522
+ if (requestInit.signal?.aborted) {
2523
+ throw e;
2524
+ }
2525
+ const hasAttemptsRemaining = attempts < maxAttempts;
2526
+ if (e instanceof IndexerHttpError && e.status === 429 && rateLimitAttempt < rateLimitRetries && hasAttemptsRemaining) {
2527
+ rateLimitAttempt += 1;
2528
+ const waitSeconds = e.retryAfterSeconds !== void 0 ? Math.max(0, e.retryAfterSeconds) : 1;
2529
+ await delay(waitSeconds * 1e3, requestInit.signal ?? void 0);
2530
+ continue;
2531
+ }
2532
+ if (!hasAttemptsRemaining || standardRetryAttempt >= retries) {
2533
+ break;
2534
+ }
2535
+ standardRetryAttempt += 1;
2536
+ await delay(200 * standardRetryAttempt, requestInit.signal ?? void 0);
2605
2537
  }
2606
2538
  }
2607
- const controllerAddress = this.config.getRateManagerControllerAddress();
2608
- const controllerAbi = this.config.getRateManagerControllerAbi();
2609
- if (!controllerAddress || !controllerAbi) {
2610
- throw this.buildRateManagerUnavailableError("Rate manager controller not available");
2611
- }
2612
- const legacyResult = await this.config.getPublicClient().readContract({
2613
- address: controllerAddress,
2614
- abi: controllerAbi,
2615
- functionName: "getDepositRateManager",
2616
- args: [escrow, id]
2617
- });
2618
- return {
2619
- registry: legacyResult[0],
2620
- rateManagerId: legacyResult[1]
2621
- };
2622
- }
2623
- async getManagerFee(escrow, depositId) {
2624
- const id = parseRawDepositId(depositId);
2625
- const escrowContext = this.config.host.resolveEscrowContext({
2626
- escrowAddress: escrow,
2627
- depositId
2628
- });
2629
- if (getRateManagerReadFunction(escrowContext.abi, "getManagerFee")) {
2630
- const result2 = await this.config.getPublicClient().readContract({
2631
- address: escrowContext.address,
2632
- abi: escrowContext.abi,
2633
- functionName: "getManagerFee",
2634
- args: [id]
2635
- });
2636
- return parseManagerFeeFromRead(result2);
2637
- }
2638
- const controllerAddress = this.config.getRateManagerControllerAddress();
2639
- const controllerAbi = this.config.getRateManagerControllerAbi();
2640
- if (!controllerAddress || !controllerAbi) {
2641
- throw this.buildRateManagerUnavailableError("Rate manager controller not available");
2642
- }
2643
- const result = await this.config.getPublicClient().readContract({
2644
- address: controllerAddress,
2645
- abi: controllerAbi,
2646
- functionName: "getManagerFee",
2647
- args: [escrow, id]
2648
- });
2649
- return parseManagerFeeFromRead(result);
2650
- }
2651
- async getEffectiveRate(params) {
2652
- const escrowContext = this.config.host.resolveEscrowContext({
2653
- escrowAddress: params.escrow,
2654
- depositId: params.depositId
2655
- });
2656
- const id = parseRawDepositId(params.depositId);
2657
- return await this.config.getPublicClient().readContract({
2658
- address: escrowContext.address,
2659
- abi: escrowContext.abi,
2660
- functionName: "getEffectiveRate",
2661
- args: [id, params.paymentMethod, params.fiatCurrency]
2662
- });
2663
- }
2664
- };
2665
- var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && abi.some(
2666
- (item) => item.type === "function" && item.name === functionName
2667
- );
2668
-
2669
- // src/indexer/client.ts
2670
- var IndexerHttpError = class extends Error {
2671
- constructor(status, statusText, options) {
2672
- super(`Indexer request failed: ${status} ${statusText}`);
2673
- this.name = "IndexerHttpError";
2674
- this.status = status;
2675
- this.retryAfterSeconds = options?.retryAfterSeconds;
2539
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
2676
2540
  }
2677
2541
  };
2678
- function parseRetryAfterSeconds(rawHeader) {
2679
- if (!rawHeader) return void 0;
2680
- const parsedSeconds = Number(rawHeader);
2681
- if (Number.isFinite(parsedSeconds) && parsedSeconds >= 0) {
2682
- return Math.ceil(parsedSeconds);
2683
- }
2684
- const parsedDateMs = Date.parse(rawHeader);
2685
- if (!Number.isFinite(parsedDateMs)) return void 0;
2686
- const secondsUntilRetry = Math.ceil((parsedDateMs - Date.now()) / 1e3);
2687
- return Math.max(0, secondsUntilRetry);
2688
- }
2689
- function createAbortError() {
2690
- const error = new Error("The operation was aborted");
2691
- error.name = "AbortError";
2692
- return error;
2693
- }
2694
- function delay(ms, signal) {
2695
- if (ms <= 0) {
2696
- return Promise.resolve();
2697
- }
2698
- return new Promise((resolve, reject) => {
2699
- if (signal?.aborted) {
2700
- reject(createAbortError());
2701
- return;
2702
- }
2703
- const timer = setTimeout(() => {
2704
- signal?.removeEventListener("abort", onAbort);
2705
- resolve();
2706
- }, ms);
2707
- const onAbort = () => {
2708
- clearTimeout(timer);
2709
- signal?.removeEventListener("abort", onAbort);
2710
- reject(createAbortError());
2711
- };
2712
- signal?.addEventListener("abort", onAbort);
2713
- });
2714
- }
2715
- var IndexerClient = class {
2716
- constructor(endpoint, options = {}) {
2717
- this.endpoint = endpoint;
2718
- this.options = options;
2719
- this.hasLoggedTokenProviderError = false;
2720
- }
2721
- async resolveAuthorizationToken() {
2722
- if (this.options.getAuthorizationToken) {
2723
- try {
2724
- const token = await this.options.getAuthorizationToken();
2725
- return token ?? void 0;
2726
- } catch (error) {
2727
- if (this.options.onAuthorizationTokenError) {
2728
- this.options.onAuthorizationTokenError(error);
2729
- } else if (!this.hasLoggedTokenProviderError) {
2730
- this.hasLoggedTokenProviderError = true;
2731
- console.warn(
2732
- "[IndexerClient] getAuthorizationToken failed; continuing without Authorization header",
2733
- error
2734
- );
2735
- }
2736
- return void 0;
2737
- }
2738
- }
2739
- return this.options.authorizationToken;
2740
- }
2741
- async _post(request, init) {
2742
- const token = await this.resolveAuthorizationToken();
2743
- const headers2 = new Headers(init?.headers);
2744
- if (!headers2.has("Content-Type")) {
2745
- headers2.set("Content-Type", "application/json");
2746
- }
2747
- if (token && !headers2.has("Authorization")) {
2748
- headers2.set("Authorization", token.startsWith("Bearer ") ? token : `Bearer ${token}`);
2749
- }
2750
- if (this.options.apiKey && !headers2.has("x-api-key")) {
2751
- headers2.set("x-api-key", this.options.apiKey);
2752
- }
2753
- const res = await fetch(this.endpoint, {
2754
- method: "POST",
2755
- headers: headers2,
2756
- body: JSON.stringify(request),
2757
- cache: "no-store",
2758
- ...init
2759
- });
2760
- if (!res.ok) {
2761
- throw new IndexerHttpError(res.status, res.statusText, {
2762
- retryAfterSeconds: parseRetryAfterSeconds(res.headers.get("Retry-After"))
2763
- });
2764
- }
2765
- const json = await res.json();
2766
- if (json.errors?.length) {
2767
- const msg = json.errors.map((e) => e.message).join(", ");
2768
- throw new Error(`GraphQL errors: ${msg}`);
2769
- }
2770
- if (!json.data) throw new Error("No data returned from indexer");
2771
- return json.data;
2772
- }
2773
- async query(request, init) {
2774
- const retries = Math.max(0, init?.retries ?? 1);
2775
- const rateLimitRetries = Math.max(0, init?.rateLimitRetries ?? 2);
2776
- const maxAttempts = 1 + Math.max(retries, rateLimitRetries);
2777
- const {
2778
- retries: _unusedRetries,
2779
- rateLimitRetries: _unusedRateLimitRetries,
2780
- ...requestInit
2781
- } = init ?? {};
2782
- let attempts = 0;
2783
- let rateLimitAttempt = 0;
2784
- let standardRetryAttempt = 0;
2785
- let lastErr;
2786
- while (attempts < maxAttempts) {
2787
- try {
2788
- return await this._post(request, requestInit);
2789
- } catch (e) {
2790
- lastErr = e;
2791
- attempts += 1;
2792
- if (requestInit.signal?.aborted) {
2793
- throw e;
2794
- }
2795
- const hasAttemptsRemaining = attempts < maxAttempts;
2796
- if (e instanceof IndexerHttpError && e.status === 429 && rateLimitAttempt < rateLimitRetries && hasAttemptsRemaining) {
2797
- rateLimitAttempt += 1;
2798
- const waitSeconds = e.retryAfterSeconds !== void 0 ? Math.max(0, e.retryAfterSeconds) : 1;
2799
- await delay(waitSeconds * 1e3, requestInit.signal ?? void 0);
2800
- continue;
2801
- }
2802
- if (!hasAttemptsRemaining || standardRetryAttempt >= retries) {
2803
- break;
2804
- }
2805
- standardRetryAttempt += 1;
2806
- await delay(200 * standardRetryAttempt, requestInit.signal ?? void 0);
2807
- }
2808
- }
2809
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
2810
- }
2811
- };
2812
- function defaultIndexerEndpoint(env = "PRODUCTION") {
2813
- switch (env) {
2814
- case "PRODUCTION":
2815
- return "https://indexer.zkp2p.xyz/v1/graphql";
2816
- case "PREPRODUCTION":
2817
- return "https://indexer-preprod.zkp2p.xyz/v1/graphql";
2818
- case "STAGING":
2819
- return "https://indexer-staging.zkp2p.xyz/v1/graphql";
2820
- case "DEV":
2821
- case "LOCAL":
2822
- return "https://indexer-staging.zkp2p.xyz/v1/graphql";
2823
- default:
2824
- return "https://indexer.zkp2p.xyz/v1/graphql";
2542
+ function defaultIndexerEndpoint(env = "PRODUCTION") {
2543
+ switch (env) {
2544
+ case "PRODUCTION":
2545
+ return "https://indexer.zkp2p.xyz/v1/graphql";
2546
+ case "PREPRODUCTION":
2547
+ return "https://indexer-preprod.zkp2p.xyz/v1/graphql";
2548
+ case "STAGING":
2549
+ return "https://indexer-staging.zkp2p.xyz/v1/graphql";
2550
+ case "DEV":
2551
+ case "LOCAL":
2552
+ return "https://indexer-staging.zkp2p.xyz/v1/graphql";
2553
+ default:
2554
+ return "https://indexer.zkp2p.xyz/v1/graphql";
2825
2555
  }
2826
2556
  }
2827
2557
 
@@ -4265,7 +3995,11 @@ var IndexerDepositService = class {
4265
3995
  (pm) => (pm.paymentMethodHash ?? "").toLowerCase() === target
4266
3996
  );
4267
3997
  return match?.payeeDetailsHash ?? null;
4268
- } catch {
3998
+ } catch (error) {
3999
+ logger.warn(
4000
+ "[sdk] resolvePayeeHash lookup failed; returning null",
4001
+ error instanceof Error ? error.message : error
4002
+ );
4269
4003
  return null;
4270
4004
  }
4271
4005
  }
@@ -4427,1222 +4161,1784 @@ var IndexerDepositService = class {
4427
4161
  }
4428
4162
  };
4429
4163
 
4430
- // src/indexer/rateManagerService.ts
4431
- var DEFAULT_LIMIT2 = 50;
4432
- var RATE_MANAGER_HISTORY_PAGE_SIZE = 250;
4433
- var EVM_ADDRESS_REGEX = /^0x[a-f0-9]{40}$/;
4434
- function normalizeRateManagerId2(value) {
4435
- if (!value) return "";
4436
- return value.toLowerCase();
4164
+ // src/referral.ts
4165
+ var normalizeReferralCode = (code) => code.trim().toUpperCase();
4166
+ var isValidReferralCode = (code) => /^[A-Z0-9]{6}$/.test(normalizeReferralCode(code));
4167
+ var REFERRAL_SIGNATURE_DOMAIN = { name: "ZKP2PReferral", version: "1" };
4168
+ var REFERRAL_SIGNATURE_TYPES = {
4169
+ CreateCode: [
4170
+ { name: "wallet", type: "address" },
4171
+ { name: "audience", type: "string" },
4172
+ { name: "issuedAt", type: "uint256" }
4173
+ ],
4174
+ RedeemCode: [
4175
+ { name: "wallet", type: "address" },
4176
+ { name: "code", type: "string" },
4177
+ { name: "referrer", type: "address" },
4178
+ { name: "audience", type: "string" },
4179
+ { name: "issuedAt", type: "uint256" }
4180
+ ],
4181
+ RenameCode: [
4182
+ { name: "wallet", type: "address" },
4183
+ { name: "oldCode", type: "string" },
4184
+ { name: "newCode", type: "string" },
4185
+ { name: "audience", type: "string" },
4186
+ { name: "issuedAt", type: "uint256" }
4187
+ ]
4188
+ };
4189
+
4190
+ // src/adapters/api.ts
4191
+ function createHeaders(apiKey, authorizationToken) {
4192
+ const headers2 = { "Content-Type": "application/json" };
4193
+ if (apiKey) headers2["x-api-key"] = apiKey;
4194
+ if (authorizationToken) {
4195
+ headers2.Authorization = authorizationToken.startsWith("Bearer ") ? authorizationToken : `Bearer ${authorizationToken}`;
4196
+ }
4197
+ return headers2;
4437
4198
  }
4438
- function normalizeAddress3(value) {
4439
- if (!value) return "";
4440
- return value.toLowerCase();
4199
+ function withApiBase(baseApiUrl) {
4200
+ const trimmed = (baseApiUrl || "").trim();
4201
+ let base2 = trimmed.replace(/\/+$/, "");
4202
+ base2 = base2.replace(/\/v1$/i, "");
4203
+ base2 = base2.replace(/\/v2$/i, "");
4204
+ return base2;
4441
4205
  }
4442
- function escapeLikePatternLiteral(value) {
4443
- return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
4206
+ async function apiFetch({
4207
+ url,
4208
+ method = "GET",
4209
+ body,
4210
+ apiKey,
4211
+ authorizationToken,
4212
+ timeoutMs,
4213
+ retryCount = 3,
4214
+ retryDelayMs = 1e3
4215
+ }) {
4216
+ const endpoint = url.replace(/^[^/]*\/\/[^/]*/, "");
4217
+ return withRetry(
4218
+ async () => {
4219
+ let res;
4220
+ try {
4221
+ const options = {
4222
+ method,
4223
+ headers: createHeaders(apiKey, authorizationToken)
4224
+ };
4225
+ if (body && method !== "GET") {
4226
+ options.body = JSON.stringify(body);
4227
+ }
4228
+ res = await fetch(url, options);
4229
+ } catch (error) {
4230
+ throw new NetworkError("Failed to connect to API server", { endpoint, error });
4231
+ }
4232
+ if (!res.ok) {
4233
+ const errorText = await res.text();
4234
+ throw parseAPIError(res, errorText);
4235
+ }
4236
+ return res.json();
4237
+ },
4238
+ retryCount,
4239
+ retryDelayMs,
4240
+ timeoutMs
4241
+ );
4444
4242
  }
4445
- function parseScopedRateManagerFilterId(value) {
4446
- const trimmed = value.trim().toLowerCase();
4447
- if (!trimmed) return null;
4448
- const separatorIndex = trimmed.indexOf(":");
4449
- if (separatorIndex <= 0) return null;
4450
- const rateManagerAddress = normalizeAddress3(trimmed.slice(0, separatorIndex));
4451
- const rateManagerId = normalizeRateManagerId2(trimmed.slice(separatorIndex + 1));
4452
- if (!EVM_ADDRESS_REGEX.test(rateManagerAddress) || !rateManagerId) {
4453
- return null;
4243
+ function unwrapResponseObject(payload) {
4244
+ if (payload && typeof payload === "object" && "responseObject" in payload) {
4245
+ return payload.responseObject;
4454
4246
  }
4455
- return { rateManagerAddress, rateManagerId };
4247
+ return payload;
4456
4248
  }
4457
- function getManagerScopeKey(rateManagerId, rateManagerAddress) {
4458
- const normalizedId = normalizeRateManagerId2(rateManagerId);
4459
- const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
4460
- return normalizedRateManagerAddress ? `${normalizedRateManagerAddress}:${normalizedId}` : normalizedId;
4249
+ function requireAuthorizationToken(authorizationToken, endpoint) {
4250
+ if (!authorizationToken) {
4251
+ throw new ValidationError(
4252
+ `authorizationToken is required for ${endpoint}`,
4253
+ "authorizationToken"
4254
+ );
4255
+ }
4256
+ return authorizationToken;
4461
4257
  }
4462
- function extractRateManagerAddressFromScopedId(id) {
4463
- if (!id) return null;
4464
- const parts = id.split("_");
4465
- if (parts.length < 3) return null;
4466
- const rateManagerAddress = parts[1] ?? "";
4467
- return rateManagerAddress.startsWith("0x") ? rateManagerAddress.toLowerCase() : null;
4258
+ function requireReferralWriteAuth(authorizationToken, signature, endpoint) {
4259
+ if (authorizationToken && signature) {
4260
+ throw new ValidationError(
4261
+ `Use either authorizationToken or signature for ${endpoint}, not both`,
4262
+ "authorizationToken"
4263
+ );
4264
+ }
4265
+ if (!authorizationToken && !signature) {
4266
+ throw new ValidationError(
4267
+ `authorizationToken or signature is required for ${endpoint}`,
4268
+ "authorizationToken"
4269
+ );
4270
+ }
4271
+ return authorizationToken;
4468
4272
  }
4469
- function buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress) {
4470
- const normalizedId = escapeLikePatternLiteral(normalizeRateManagerId2(rateManagerId));
4471
- const normalizedRateManagerAddress = escapeLikePatternLiteral(
4472
- normalizeAddress3(rateManagerAddress)
4473
- );
4474
- return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
4273
+ function requireEscrowAddress(escrowAddress, endpoint) {
4274
+ if (!escrowAddress) {
4275
+ throw new ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
4276
+ }
4277
+ return escrowAddress;
4475
4278
  }
4476
- function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
4477
- return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
4279
+ function normalizeReferralAddress(address, field) {
4280
+ const normalized = address.trim().toLowerCase();
4281
+ if (!isValidHexAddress(normalized)) {
4282
+ throw new ValidationError(`${field} must be a valid Ethereum address`, field);
4283
+ }
4284
+ return normalized;
4478
4285
  }
4479
- function normalizeCompositeDepositId(depositId, escrowAddress) {
4480
- const normalizedDepositId = depositId.trim().toLowerCase();
4481
- if (!normalizedDepositId) return "";
4482
- if (normalizedDepositId.includes("_")) return normalizedDepositId;
4483
- const normalizedEscrow = normalizeAddress3(escrowAddress);
4484
- if (normalizedEscrow) {
4485
- return `${normalizedEscrow}_${normalizedDepositId}`;
4286
+ function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
4287
+ const normalized = withApiBase(baseApiUrl).toLowerCase();
4288
+ if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
4289
+ return "PREPRODUCTION";
4486
4290
  }
4487
- return normalizedDepositId;
4488
- }
4489
- function extractDepositIdOnContract(compositeDepositId) {
4490
- if (!compositeDepositId) return null;
4491
- const parts = compositeDepositId.split("_");
4492
- const rawDepositId = parts[parts.length - 1];
4493
- return rawDepositId && /^\d+$/.test(rawDepositId) ? rawDepositId : null;
4494
- }
4495
- function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
4496
- if (!compositeDepositId) return null;
4497
- const [escrowAddress] = compositeDepositId.split("_");
4498
- return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
4499
- }
4500
- function parseRateManagerFilterIds(rateManagerIds) {
4501
- const bare = /* @__PURE__ */ new Set();
4502
- const scoped = /* @__PURE__ */ new Map();
4503
- for (const value of rateManagerIds) {
4504
- const scopedRateManager = parseScopedRateManagerFilterId(value);
4505
- if (scopedRateManager) {
4506
- scoped.set(
4507
- getManagerScopeKey(scopedRateManager.rateManagerId, scopedRateManager.rateManagerAddress),
4508
- scopedRateManager
4509
- );
4510
- continue;
4511
- }
4512
- if (value.includes(":")) {
4513
- continue;
4514
- }
4515
- const normalizedRateManagerId = normalizeRateManagerId2(value);
4516
- if (normalizedRateManagerId) {
4517
- bare.add(normalizedRateManagerId);
4518
- }
4291
+ if (normalized.includes("staging") || normalized.includes("/staging/") || normalized.includes("localhost") || normalized.includes("127.0.0.1")) {
4292
+ return "STAGING";
4519
4293
  }
4520
- return { bare, scoped };
4521
- }
4522
- function buildDepositScopeKey(scope) {
4523
- return `${scope.escrow}:${scope.depositIdOnContract}`;
4294
+ return "PRODUCTION";
4524
4295
  }
4525
- function toSafeBigInt(value) {
4526
- if (!value) return 0n;
4296
+ async function withOptionalTimeout(promise, timeoutMs, endpoint) {
4297
+ if (!timeoutMs || timeoutMs <= 0) return promise;
4298
+ let timer;
4527
4299
  try {
4528
- return parseBigIntLike(value);
4529
- } catch {
4530
- return 0n;
4300
+ return await Promise.race([
4301
+ promise,
4302
+ new Promise((_, reject) => {
4303
+ timer = setTimeout(() => {
4304
+ reject(new NetworkError("Request timed out", { endpoint }));
4305
+ }, timeoutMs);
4306
+ })
4307
+ ]);
4308
+ } finally {
4309
+ if (timer) clearTimeout(timer);
4531
4310
  }
4532
4311
  }
4533
- function compareBigInt(a, b, direction) {
4534
- if (a === b) return 0;
4535
- if (direction === "asc") return a < b ? -1 : 1;
4536
- return a > b ? -1 : 1;
4312
+ function toDateFromUnixSeconds(value) {
4313
+ if (!value) return void 0;
4314
+ const numeric = Number(value);
4315
+ if (!Number.isFinite(numeric) || numeric <= 0) return void 0;
4316
+ return new Date(numeric * 1e3);
4537
4317
  }
4538
- function parseEventCursorId(id) {
4539
- if (!id) return null;
4540
- const [chainIdRaw, blockNumberRaw, logIndexRaw] = id.split("_");
4541
- if (!chainIdRaw || !blockNumberRaw || !logIndexRaw) return null;
4542
- if (!/^\d+$/.test(chainIdRaw) || !/^\d+$/.test(blockNumberRaw) || !/^\d+$/.test(logIndexRaw)) {
4543
- return null;
4544
- }
4318
+ function toBigIntSafe(value) {
4319
+ if (value === null || value === void 0) return 0n;
4545
4320
  try {
4546
- return {
4547
- chainId: BigInt(chainIdRaw),
4548
- blockNumber: BigInt(blockNumberRaw),
4549
- logIndex: BigInt(logIndexRaw)
4550
- };
4321
+ return BigInt(value);
4551
4322
  } catch {
4552
- return null;
4323
+ return 0n;
4553
4324
  }
4554
4325
  }
4555
- function compareEventCursorIdsByRecency(leftId, rightId) {
4556
- const left = parseEventCursorId(leftId);
4557
- const right = parseEventCursorId(rightId);
4558
- if (left && right) {
4559
- if (left.chainId !== right.chainId) {
4560
- return left.chainId > right.chainId ? -1 : 1;
4561
- }
4562
- if (left.blockNumber !== right.blockNumber) {
4563
- return left.blockNumber > right.blockNumber ? -1 : 1;
4564
- }
4565
- if (left.logIndex !== right.logIndex) {
4566
- return left.logIndex > right.logIndex ? -1 : 1;
4326
+ function normalizeOwnerDepositsStatus(status) {
4327
+ if (!status) return void 0;
4328
+ if (status === "WITHDRAWN") return "CLOSED";
4329
+ return status;
4330
+ }
4331
+ function buildLegacyVerifierCurrencies(deposit) {
4332
+ const currenciesByMethod = /* @__PURE__ */ new Map();
4333
+ for (const currency of deposit.currencies ?? []) {
4334
+ const methodHash = currency.paymentMethodHash;
4335
+ const resolvedConversionRate = currency.conversionRate ?? currency.minConversionRate;
4336
+ if (resolvedConversionRate === null || resolvedConversionRate === void 0) {
4337
+ logger.warn(
4338
+ `[sdk] Skipping currency with missing conversion rate (deposit ${deposit.depositId}, currency ${currency.currencyCode})`
4339
+ );
4340
+ continue;
4567
4341
  }
4568
- return 0;
4342
+ const bucket = currenciesByMethod.get(methodHash) ?? [];
4343
+ bucket.push({
4344
+ currencyCode: currency.currencyCode,
4345
+ conversionRate: resolvedConversionRate,
4346
+ minConversionRate: currency.minConversionRate,
4347
+ managerRate: currency.managerRate ?? null,
4348
+ rateManagerId: currency.rateManagerId ?? null
4349
+ });
4350
+ currenciesByMethod.set(methodHash, bucket);
4569
4351
  }
4570
- return (rightId ?? "").localeCompare(leftId ?? "");
4571
- }
4572
- function isAggregateOrderField(field) {
4573
- return field === "currentDelegatedBalance" || field === "totalFilledVolume";
4352
+ return currenciesByMethod;
4574
4353
  }
4575
- function normalizeRateManagerEntity(manager) {
4354
+ function convertIndexerDepositToLegacyApiDeposit(deposit) {
4355
+ const currenciesByMethod = buildLegacyVerifierCurrencies(deposit);
4356
+ const verifiers = (deposit.paymentMethods ?? []).filter((paymentMethod) => paymentMethod.active !== false).map((paymentMethod) => ({
4357
+ depositId: Number(deposit.depositId),
4358
+ verifier: "",
4359
+ methodHash: paymentMethod.paymentMethodHash,
4360
+ intentGatingService: paymentMethod.intentGatingService,
4361
+ payeeDetailsHash: paymentMethod.payeeDetailsHash,
4362
+ data: "0x",
4363
+ currencies: currenciesByMethod.get(paymentMethod.paymentMethodHash) ?? []
4364
+ }));
4365
+ const remainingDeposits = toBigIntSafe(deposit.remainingDeposits);
4366
+ const outstandingIntentAmount = toBigIntSafe(deposit.outstandingIntentAmount);
4367
+ const totalAmountTaken = toBigIntSafe(deposit.totalAmountTaken);
4368
+ const totalWithdrawn = toBigIntSafe(deposit.totalWithdrawn);
4369
+ const amount = remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn;
4576
4370
  return {
4577
- ...manager,
4578
- rateManagerAddress: normalizeAddress3(manager.rateManagerAddress)
4371
+ id: Number(deposit.depositId),
4372
+ depositor: deposit.depositor,
4373
+ token: deposit.token,
4374
+ amount: amount.toString(),
4375
+ remainingDeposits: deposit.remainingDeposits,
4376
+ intentAmountMin: deposit.intentAmountMin,
4377
+ intentAmountMax: deposit.intentAmountMax,
4378
+ acceptingIntents: deposit.acceptingIntents,
4379
+ outstandingIntentAmount: deposit.outstandingIntentAmount,
4380
+ availableLiquidity: deposit.remainingDeposits,
4381
+ status: deposit.status,
4382
+ totalIntents: deposit.totalIntents,
4383
+ signaledIntents: deposit.signaledIntents,
4384
+ fulfilledIntents: deposit.fulfilledIntents,
4385
+ prunedIntents: deposit.prunedIntents,
4386
+ totalAmountTaken: deposit.totalAmountTaken,
4387
+ totalWithdrawn: deposit.totalWithdrawn,
4388
+ successRateBps: deposit.successRateBps,
4389
+ rateManagerId: deposit.rateManagerId ?? null,
4390
+ vaultName: null,
4391
+ rateManagerRegistry: null,
4392
+ createdAt: toDateFromUnixSeconds(deposit.timestamp),
4393
+ updatedAt: toDateFromUnixSeconds(deposit.updatedAt),
4394
+ verifiers
4579
4395
  };
4580
4396
  }
4581
- function toDelegationEntityFromDeposit(deposit) {
4582
- const rateManagerId = normalizeRateManagerId2(deposit.rateManagerId);
4583
- if (!rateManagerId) return null;
4584
- const delegatedAt = deposit.delegatedAt ?? null;
4585
- return {
4586
- id: deposit.id,
4587
- chainId: deposit.chainId,
4588
- rateManagerId,
4589
- rateManagerAddress: normalizeAddress3(deposit.rateManagerAddress) || null,
4590
- depositId: deposit.id,
4591
- delegatedAt,
4592
- createdAt: delegatedAt ?? deposit.updatedAt,
4593
- updatedAt: deposit.updatedAt
4594
- };
4397
+ async function apiPostDepositDetails(req, baseApiUrl, timeoutMs) {
4398
+ return apiFetch({
4399
+ url: `${withApiBase(baseApiUrl)}/v2/makers/create`,
4400
+ method: "POST",
4401
+ body: req,
4402
+ timeoutMs
4403
+ });
4595
4404
  }
4596
- var IndexerRateManagerService = class {
4597
- constructor(client) {
4598
- this.client = client;
4599
- }
4600
- buildRateManagerScopeWhere(rateManagerIds) {
4601
- if (!rateManagerIds?.length) return void 0;
4602
- const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
4603
- const scopeConditions = [];
4604
- if (bare.size > 0) {
4605
- scopeConditions.push({
4606
- rateManagerId: { _in: [...bare] }
4607
- });
4608
- }
4609
- for (const scopedRateManager of scoped.values()) {
4610
- scopeConditions.push({
4611
- rateManagerId: { _eq: scopedRateManager.rateManagerId },
4612
- rateManagerAddress: { _eq: scopedRateManager.rateManagerAddress }
4613
- });
4614
- }
4615
- if (scopeConditions.length === 1) {
4616
- return scopeConditions[0];
4617
- }
4618
- if (scopeConditions.length > 1) {
4619
- return { _or: scopeConditions };
4405
+ async function apiGetQuote(req, baseApiUrl, timeoutMs, apiKey) {
4406
+ if (req.quotesToReturn !== void 0) {
4407
+ if (!Number.isInteger(req.quotesToReturn) || req.quotesToReturn < 1) {
4408
+ throw new ValidationError("quotesToReturn must be a positive integer", "quotesToReturn");
4620
4409
  }
4621
- return void 0;
4622
4410
  }
4623
- buildWhere(filter) {
4624
- if (!filter) return void 0;
4625
- const where = {};
4626
- if (filter.manager) {
4627
- where.manager = { _ilike: filter.manager };
4628
- }
4629
- if (filter.name) {
4630
- where.name = { _ilike: `%${filter.name}%` };
4631
- }
4632
- if (filter.maxFee) {
4633
- where.maxFee = { _lte: filter.maxFee };
4634
- }
4635
- const scopeWhere = this.buildRateManagerScopeWhere(filter.rateManagerIds);
4636
- if (scopeWhere) {
4637
- Object.assign(where, scopeWhere);
4638
- }
4639
- return Object.keys(where).length ? where : void 0;
4411
+ if (!isValidHexAddress(req.user)) {
4412
+ throw new ValidationError("user must be a valid Ethereum address", "user");
4640
4413
  }
4641
- buildAggregateWhere(filter) {
4642
- return this.buildRateManagerScopeWhere(filter?.rateManagerIds) ?? {};
4414
+ if (!isValidHexAddress(req.recipient)) {
4415
+ throw new ValidationError("recipient must be a valid Ethereum address", "recipient");
4643
4416
  }
4644
- buildLegacyAggregateWhere(filter) {
4645
- const rateManagerIds = filter?.rateManagerIds;
4646
- if (!rateManagerIds?.length) return {};
4647
- const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
4648
- const scopeConditions = [];
4649
- if (bare.size > 0) {
4650
- scopeConditions.push({
4651
- rateManagerId: { _in: [...bare] }
4652
- });
4653
- }
4654
- for (const scopedRateManager of scoped.values()) {
4655
- scopeConditions.push({
4656
- rateManagerId: { _eq: scopedRateManager.rateManagerId },
4657
- id: {
4658
- _ilike: buildRateManagerAddressScopedIdPattern(
4659
- scopedRateManager.rateManagerId,
4660
- scopedRateManager.rateManagerAddress
4661
- )
4662
- }
4663
- });
4664
- }
4665
- if (scopeConditions.length === 1) {
4666
- return scopeConditions[0] ?? {};
4667
- }
4668
- if (scopeConditions.length > 1) {
4669
- return { _or: scopeConditions };
4670
- }
4671
- return {};
4672
- }
4673
- buildOrderBy(pagination) {
4674
- const rawField = pagination?.orderBy ?? "createdAt";
4675
- const field = isAggregateOrderField(rawField) ? "createdAt" : rawField;
4676
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
4677
- return [{ [field]: direction }];
4678
- }
4679
- toRateManagerListItems(result) {
4680
- const managers = (result.RateManager ?? []).map(normalizeRateManagerEntity);
4681
- const aggregatesByScope = /* @__PURE__ */ new Map();
4682
- for (const aggregate of result.ManagerAggregateStats ?? []) {
4683
- const aggregateRateManagerAddress = normalizeAddress3(aggregate.rateManagerAddress) || extractRateManagerAddressFromScopedId(aggregate.id);
4684
- const scopeKey = getManagerScopeKey(aggregate.rateManagerId, aggregateRateManagerAddress);
4685
- aggregatesByScope.set(scopeKey, aggregate);
4686
- }
4687
- return managers.map((manager) => ({
4688
- manager,
4689
- aggregate: aggregatesByScope.get(
4690
- getManagerScopeKey(manager.rateManagerId, normalizeAddress3(manager.rateManagerAddress))
4691
- ) ?? aggregatesByScope.get(getManagerScopeKey(manager.rateManagerId)) ?? null
4692
- }));
4417
+ if (!isValidHexAddress(req.destinationToken)) {
4418
+ throw new ValidationError(
4419
+ "destinationToken must be a valid Ethereum address",
4420
+ "destinationToken"
4421
+ );
4693
4422
  }
4694
- applyHookFilter(rows, hasHook) {
4695
- if (hasHook === void 0) return rows;
4696
- return hasHook ? [] : rows;
4423
+ const isExactFiat = req.isExactFiat !== false;
4424
+ const endpoint = isExactFiat ? "exact-fiat" : "exact-token";
4425
+ let url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
4426
+ if (req.quotesToReturn) url += `?quotesToReturn=${req.quotesToReturn}`;
4427
+ const requestBody = {
4428
+ ...req,
4429
+ [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
4430
+ amount: void 0,
4431
+ isExactFiat: void 0,
4432
+ quotesToReturn: void 0,
4433
+ includePrivateOrderbooks: req.includePrivateOrderbooks
4434
+ };
4435
+ Object.keys(requestBody).forEach((k) => requestBody[k] === void 0 && delete requestBody[k]);
4436
+ return apiFetch({
4437
+ url,
4438
+ method: "POST",
4439
+ body: requestBody,
4440
+ apiKey,
4441
+ timeoutMs
4442
+ });
4443
+ }
4444
+ async function apiGetQuotesBestByPlatform(req, baseApiUrl, timeoutMs, apiKey) {
4445
+ const isExactFiat = req.isExactFiat !== false;
4446
+ const endpoint = isExactFiat ? "best-by-platform" : "best-by-platform-exact-token";
4447
+ const url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
4448
+ const requestBody = {
4449
+ ...req,
4450
+ [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
4451
+ amount: void 0,
4452
+ isExactFiat: void 0,
4453
+ referrerFeeConfig: void 0
4454
+ };
4455
+ Object.keys(requestBody).forEach(
4456
+ (key) => requestBody[key] === void 0 && delete requestBody[key]
4457
+ );
4458
+ return apiFetch({
4459
+ url,
4460
+ method: "POST",
4461
+ body: requestBody,
4462
+ apiKey,
4463
+ timeoutMs
4464
+ });
4465
+ }
4466
+ async function apiGetPayeeDetails(req, baseApiUrl, timeoutMs) {
4467
+ return apiFetch({
4468
+ url: `${withApiBase(baseApiUrl)}/v2/makers/${req.processorName}/${req.hashedOnchainId}`,
4469
+ method: "GET",
4470
+ timeoutMs
4471
+ });
4472
+ }
4473
+ async function apiValidatePayeeDetails(req, baseApiUrl, timeoutMs) {
4474
+ const data = await apiFetch({
4475
+ url: `${withApiBase(baseApiUrl)}/v2/makers/validate`,
4476
+ method: "POST",
4477
+ body: req,
4478
+ timeoutMs
4479
+ });
4480
+ if (typeof data?.responseObject === "boolean") {
4481
+ return {
4482
+ ...data,
4483
+ responseObject: { isValid: data.responseObject }
4484
+ };
4697
4485
  }
4698
- async queryRateManagerList(variables, legacyVariables) {
4699
- try {
4700
- return await this.client.query({
4701
- query: RATE_MANAGER_LIST_QUERY,
4702
- variables
4703
- });
4704
- } catch (error) {
4705
- if (!isSchemaCompatibilityError(error)) {
4706
- throw error;
4707
- }
4708
- return this.client.query({
4709
- query: LEGACY_RATE_MANAGER_LIST_QUERY,
4710
- variables: legacyVariables
4711
- });
4712
- }
4486
+ return data;
4487
+ }
4488
+ async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs) {
4489
+ const escrowAddress = requireEscrowAddress(
4490
+ req.escrowAddress,
4491
+ "apiGetOwnerDeposits requires escrowAddress"
4492
+ );
4493
+ const indexerEndpoint = defaultIndexerEndpoint(inferIndexerEnvFromBaseApiUrl(baseApiUrl));
4494
+ const indexerClient = new IndexerClient(indexerEndpoint, {
4495
+ apiKey,
4496
+ authorizationToken: authToken
4497
+ });
4498
+ const service = new IndexerDepositService(indexerClient);
4499
+ const deposits = await withOptionalTimeout(
4500
+ service.fetchDepositsWithRelations(
4501
+ {
4502
+ depositor: req.ownerAddress,
4503
+ escrowAddress,
4504
+ escrowAddresses: req.escrowAddresses?.length ? req.escrowAddresses : void 0,
4505
+ status: normalizeOwnerDepositsStatus(req.status)
4506
+ },
4507
+ void 0,
4508
+ { includeIntents: false }
4509
+ ),
4510
+ timeoutMs,
4511
+ indexerEndpoint
4512
+ );
4513
+ return {
4514
+ success: true,
4515
+ message: "ok",
4516
+ responseObject: deposits.map(convertIndexerDepositToLegacyApiDeposit),
4517
+ statusCode: 200
4518
+ };
4519
+ }
4520
+ async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
4521
+ const normalizedOwner = req.owner.toLowerCase();
4522
+ const query = new URLSearchParams({
4523
+ owner: normalizedOwner,
4524
+ chainId: String(req.chainId)
4525
+ });
4526
+ const endpoint = `/v2/taker/tier?${query.toString()}`;
4527
+ return apiFetch({
4528
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
4529
+ method: "GET",
4530
+ timeoutMs
4531
+ });
4532
+ }
4533
+ async function apiGetReferralDashboard(opts) {
4534
+ const address = opts.address ? normalizeReferralAddress(opts.address, "address") : void 0;
4535
+ const endpoint = address ? `/v2/referral?${new URLSearchParams({ address }).toString()}` : "/v2/referral";
4536
+ const authorizationToken = address ? void 0 : requireAuthorizationToken(opts.authorizationToken, endpoint);
4537
+ const response = await apiFetch({
4538
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4539
+ method: "GET",
4540
+ authorizationToken,
4541
+ timeoutMs: opts.timeoutMs
4542
+ });
4543
+ return unwrapResponseObject(response);
4544
+ }
4545
+ async function apiGetReferralEarnings(opts) {
4546
+ const address = opts.address ? normalizeReferralAddress(opts.address, "address") : void 0;
4547
+ const endpoint = address ? `/v2/referral/earnings?${new URLSearchParams({ address }).toString()}` : "/v2/referral/earnings";
4548
+ const authorizationToken = address ? void 0 : requireAuthorizationToken(opts.authorizationToken, endpoint);
4549
+ const response = await apiFetch({
4550
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4551
+ method: "GET",
4552
+ authorizationToken,
4553
+ timeoutMs: opts.timeoutMs
4554
+ });
4555
+ return unwrapResponseObject(response);
4556
+ }
4557
+ async function apiLookupReferralCode(code, opts) {
4558
+ const normalizedCode = normalizeReferralCode(code);
4559
+ const endpoint = `/v2/referral/code/${encodeURIComponent(normalizedCode)}`;
4560
+ const response = await apiFetch({
4561
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4562
+ method: "GET",
4563
+ timeoutMs: opts.timeoutMs
4564
+ });
4565
+ return unwrapResponseObject(response);
4566
+ }
4567
+ async function apiCreateReferralCode(req, opts) {
4568
+ const endpoint = "/v2/referral/code";
4569
+ const authorizationToken = requireReferralWriteAuth(
4570
+ opts.authorizationToken,
4571
+ req.signature,
4572
+ endpoint
4573
+ );
4574
+ const response = await apiFetch({
4575
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4576
+ method: "POST",
4577
+ body: req.signature ? { signature: req.signature } : {},
4578
+ authorizationToken,
4579
+ timeoutMs: opts.timeoutMs
4580
+ });
4581
+ return unwrapResponseObject(response);
4582
+ }
4583
+ async function apiRedeemReferralCode(req, opts) {
4584
+ const endpoint = "/v2/referral/redeem";
4585
+ const authorizationToken = requireReferralWriteAuth(
4586
+ opts.authorizationToken,
4587
+ req.signature,
4588
+ endpoint
4589
+ );
4590
+ const response = await apiFetch({
4591
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4592
+ method: "POST",
4593
+ body: {
4594
+ code: normalizeReferralCode(req.code),
4595
+ ...req.signature ? { signature: req.signature } : {}
4596
+ },
4597
+ authorizationToken,
4598
+ timeoutMs: opts.timeoutMs
4599
+ });
4600
+ return unwrapResponseObject(response);
4601
+ }
4602
+ async function apiUpdateReferralCode(req, opts) {
4603
+ const endpoint = "/v2/referral/code";
4604
+ const authorizationToken = requireReferralWriteAuth(
4605
+ opts.authorizationToken,
4606
+ req.signature,
4607
+ endpoint
4608
+ );
4609
+ const response = await apiFetch({
4610
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
4611
+ method: "PATCH",
4612
+ body: {
4613
+ code: normalizeReferralCode(req.code),
4614
+ ...req.signature ? { signature: req.signature } : {}
4615
+ },
4616
+ authorizationToken,
4617
+ timeoutMs: opts.timeoutMs
4618
+ });
4619
+ return unwrapResponseObject(response);
4620
+ }
4621
+ async function apiUploadSellerCredential(processorName, payeeDetails, bundle, baseApiUrl, timeoutMs) {
4622
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
4623
+ payeeDetails
4624
+ )}/seller-credential`;
4625
+ return apiFetch({
4626
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
4627
+ method: "POST",
4628
+ body: bundle,
4629
+ timeoutMs
4630
+ });
4631
+ }
4632
+ async function apiUploadGoogleOAuthSellerCredential(processorName, payeeDetails, body, baseApiUrl, opts) {
4633
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
4634
+ payeeDetails
4635
+ )}/seller-credential/google-oauth`;
4636
+ return apiFetch({
4637
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
4638
+ method: "POST",
4639
+ body,
4640
+ timeoutMs: opts?.timeoutMs
4641
+ });
4642
+ }
4643
+ async function apiGetSellerCredentialStatus(processorName, payeeDetails, baseApiUrl, timeoutMs) {
4644
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
4645
+ payeeDetails
4646
+ )}/seller-credential/status`;
4647
+ return apiFetch({
4648
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
4649
+ method: "GET",
4650
+ timeoutMs
4651
+ });
4652
+ }
4653
+ async function apiVerifySellerPayment(platform, req, baseApiUrl, timeoutMs, apiKey) {
4654
+ const body = {
4655
+ txId: req.txId,
4656
+ chainId: req.chainId,
4657
+ intent: req.intent,
4658
+ ...req.metadata !== void 0 ? { metadata: req.metadata } : {}
4659
+ };
4660
+ return apiFetch({
4661
+ url: `${withApiBase(baseApiUrl)}/v2/verify/seller/${encodeURIComponent(platform)}`,
4662
+ method: "POST",
4663
+ body,
4664
+ apiKey,
4665
+ timeoutMs
4666
+ });
4667
+ }
4668
+ async function apiGetOrderbook(params, optsOrBaseApiUrl, timeoutMs) {
4669
+ const opts = typeof optsOrBaseApiUrl === "string" ? {
4670
+ baseApiUrl: optsOrBaseApiUrl,
4671
+ timeoutMs
4672
+ } : optsOrBaseApiUrl;
4673
+ const query = new URLSearchParams();
4674
+ Object.entries(params).forEach(([key, value]) => {
4675
+ if (value === void 0 || value === null) return;
4676
+ query.set(key, String(value));
4677
+ });
4678
+ const response = await apiFetch({
4679
+ url: `${withApiBase(opts.baseApiUrl)}/v2/orderbook?${query.toString()}`,
4680
+ method: "GET",
4681
+ timeoutMs: opts.timeoutMs
4682
+ });
4683
+ return response.responseObject;
4684
+ }
4685
+ async function apiGetDepositBundle(params, optsOrBaseApiUrl, timeoutMs) {
4686
+ const opts = typeof optsOrBaseApiUrl === "string" ? {
4687
+ baseApiUrl: optsOrBaseApiUrl,
4688
+ timeoutMs
4689
+ } : optsOrBaseApiUrl;
4690
+ const escrowAddress = requireEscrowAddress(
4691
+ params.escrowAddress,
4692
+ "apiGetDepositBundle requires escrowAddress"
4693
+ );
4694
+ const query = new URLSearchParams({ escrowAddress });
4695
+ if (params.dailySnapshotLimit !== void 0) {
4696
+ query.set("dailySnapshotLimit", String(params.dailySnapshotLimit));
4713
4697
  }
4714
- buildDelegationOrderBy(pagination) {
4715
- const rawField = pagination?.orderBy ?? "updatedAt";
4716
- const field = rawField === "createdAt" ? "delegatedAt" : rawField;
4717
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
4718
- return [{ [field]: direction }];
4698
+ const response = await apiFetch({
4699
+ url: `${withApiBase(opts.baseApiUrl)}/v2/deposits/${params.depositId}/bundle?${query.toString()}`,
4700
+ method: "GET",
4701
+ timeoutMs: opts.timeoutMs
4702
+ });
4703
+ return response.responseObject;
4704
+ }
4705
+
4706
+ // src/client/ReferralAccountOperations.ts
4707
+ var ReferralAccountOperations = class {
4708
+ constructor(config) {
4709
+ this.config = config;
4719
4710
  }
4720
- buildLegacyDelegationOrderBy(pagination) {
4721
- const rawField = pagination?.orderBy ?? "updatedAt";
4722
- const field = rawField === "delegatedAt" ? "createdAt" : rawField;
4723
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
4724
- return [{ [field]: direction }];
4711
+ async getReferralDashboard(opts) {
4712
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4713
+ const authorizationToken = opts?.address ? void 0 : await this.resolveAuthorizationToken(opts);
4714
+ return apiGetReferralDashboard({
4715
+ baseApiUrl,
4716
+ timeoutMs,
4717
+ authorizationToken,
4718
+ address: opts?.address
4719
+ });
4725
4720
  }
4726
- async fetchCurrentRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
4727
- const scopes = /* @__PURE__ */ new Map();
4728
- let offset = 0;
4729
- for (; ; ) {
4730
- const delegations = await this.fetchRateManagerDelegations(rateManagerId, {
4731
- limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
4732
- offset,
4733
- orderBy: "delegatedAt",
4734
- orderDirection: "desc",
4735
- rateManagerAddress: rateManagerAddress || void 0
4736
- });
4737
- for (const delegation of delegations) {
4738
- const escrow = extractEscrowAddressFromCompositeDepositId(delegation.depositId);
4739
- const depositIdOnContract = extractDepositIdOnContract(delegation.depositId);
4740
- if (!escrow || !depositIdOnContract) continue;
4741
- const scope = { escrow, depositIdOnContract };
4742
- scopes.set(buildDepositScopeKey(scope), scope);
4743
- }
4744
- if (delegations.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
4745
- break;
4746
- }
4747
- offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
4748
- }
4749
- return [...scopes.values()];
4721
+ async getReferralEarnings(opts) {
4722
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4723
+ const authorizationToken = opts?.address ? void 0 : await this.resolveAuthorizationToken(opts);
4724
+ return apiGetReferralEarnings({
4725
+ baseApiUrl,
4726
+ timeoutMs,
4727
+ authorizationToken,
4728
+ address: opts?.address
4729
+ });
4750
4730
  }
4751
- async fetchHistoricalRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
4752
- const normalizedId = normalizeRateManagerId2(rateManagerId);
4753
- const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
4754
- const scopes = /* @__PURE__ */ new Map();
4755
- const currentScopes = await this.fetchCurrentRateManagerDepositScopes(
4756
- normalizedId,
4757
- normalizedRateManagerAddress || void 0
4758
- );
4759
- for (const scope of currentScopes) {
4760
- scopes.set(buildDepositScopeKey(scope), scope);
4761
- }
4762
- try {
4763
- let offset = 0;
4764
- for (; ; ) {
4765
- const result = await this.client.query({
4766
- query: RATE_MANAGER_ASSIGNMENT_EVENTS_QUERY,
4767
- variables: {
4768
- setWhere: {
4769
- rateManagerId: { _eq: normalizedId },
4770
- ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
4771
- },
4772
- clearedWhere: {
4773
- rateManagerId: { _eq: normalizedId },
4774
- ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
4775
- },
4776
- limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
4777
- offset
4778
- }
4779
- });
4780
- const setEvents = result.EscrowV2_DepositRateManagerSet ?? [];
4781
- const clearedEvents = result.EscrowV2_DepositRateManagerCleared ?? [];
4782
- for (const event of [...setEvents, ...clearedEvents]) {
4783
- const escrow = normalizeAddress3(event.escrow);
4784
- const depositIdOnContract = event.depositIdOnContract?.toString() ?? "";
4785
- if (!escrow || !depositIdOnContract) continue;
4786
- const scope = { escrow, depositIdOnContract };
4787
- scopes.set(buildDepositScopeKey(scope), scope);
4788
- }
4789
- if (setEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE && clearedEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
4790
- break;
4791
- }
4792
- offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
4793
- }
4794
- } catch (error) {
4795
- if (!isSchemaCompatibilityError(error)) {
4796
- throw error;
4797
- }
4798
- }
4799
- return [...scopes.values()];
4731
+ async lookupReferralCode(code, opts) {
4732
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4733
+ return apiLookupReferralCode(code, { baseApiUrl, timeoutMs });
4800
4734
  }
4801
- async fetchRateManagers(pagination, filter) {
4802
- const orderBy = pagination?.orderBy ?? "createdAt";
4803
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
4804
- const limit = pagination?.limit ?? DEFAULT_LIMIT2;
4805
- const offset = pagination?.offset ?? 0;
4806
- const where = this.buildWhere(filter);
4807
- const aggregateWhere = this.buildAggregateWhere(filter);
4808
- const legacyAggregateWhere = this.buildLegacyAggregateWhere(filter);
4809
- if (isAggregateOrderField(orderBy)) {
4810
- const result2 = await this.queryRateManagerList(
4811
- {
4812
- where,
4813
- aggregateWhere,
4814
- order_by: [{ createdAt: "desc" }]
4815
- },
4816
- {
4817
- where,
4818
- aggregateWhere: legacyAggregateWhere,
4819
- order_by: [{ createdAt: "desc" }]
4820
- }
4821
- );
4822
- const scopedRows = this.applyHookFilter(this.toRateManagerListItems(result2), filter?.hasHook);
4823
- const sorted = scopedRows.sort((a, b) => {
4824
- const av = orderBy === "currentDelegatedBalance" ? toSafeBigInt(a.aggregate?.currentDelegatedBalance) : toSafeBigInt(a.aggregate?.totalFilledVolume);
4825
- const bv = orderBy === "currentDelegatedBalance" ? toSafeBigInt(b.aggregate?.currentDelegatedBalance) : toSafeBigInt(b.aggregate?.totalFilledVolume);
4826
- const aggregateCmp = compareBigInt(av, bv, direction);
4827
- if (aggregateCmp !== 0) return aggregateCmp;
4828
- const createdAtCmp = compareBigInt(
4829
- toSafeBigInt(a.manager.createdAt),
4830
- toSafeBigInt(b.manager.createdAt),
4831
- "desc"
4832
- );
4833
- if (createdAtCmp !== 0) return createdAtCmp;
4834
- return a.manager.rateManagerId.localeCompare(b.manager.rateManagerId);
4835
- });
4836
- return sorted.slice(offset, offset + limit);
4837
- }
4838
- const result = await this.queryRateManagerList(
4839
- {
4840
- where,
4841
- aggregateWhere,
4842
- order_by: this.buildOrderBy(pagination),
4843
- limit,
4844
- offset
4845
- },
4846
- {
4847
- where,
4848
- aggregateWhere: legacyAggregateWhere,
4849
- order_by: this.buildOrderBy(pagination),
4850
- limit,
4851
- offset
4852
- }
4853
- );
4854
- return this.applyHookFilter(this.toRateManagerListItems(result), filter?.hasHook);
4735
+ async createReferralCode(opts) {
4736
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4737
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
4738
+ return apiCreateReferralCode({}, { baseApiUrl, timeoutMs, authorizationToken });
4855
4739
  }
4856
- async fetchRateManagerDetail(rateManagerId, options) {
4857
- if (!rateManagerId) return null;
4858
- const normalizedId = normalizeRateManagerId2(rateManagerId);
4859
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
4860
- const baseVariables = {
4861
- managerWhere: {
4862
- rateManagerId: { _eq: normalizedId },
4863
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4864
- },
4865
- rateWhere: {
4866
- rateManagerId: { _eq: normalizedId },
4867
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4868
- },
4869
- aggregateWhere: {
4870
- rateManagerId: { _eq: normalizedId },
4871
- ...normalizedRateManagerAddress ? {
4872
- id: {
4873
- _ilike: buildRateManagerAddressScopedIdPattern(
4874
- normalizedId,
4875
- normalizedRateManagerAddress
4876
- )
4877
- }
4878
- } : {}
4879
- },
4880
- statsWhere: {
4881
- rateManagerId: { _eq: normalizedId },
4882
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4883
- },
4884
- delegationWhere: {
4885
- rateManagerId: { _eq: normalizedId },
4886
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4887
- },
4888
- statsLimit: options?.statsLimit ?? 20
4889
- };
4890
- const legacyVariables = {
4891
- ...baseVariables,
4892
- floorWhere: {
4893
- rateManagerId: { _eq: normalizedId },
4894
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4895
- }
4740
+ async createReferralCodeWithSignature(opts) {
4741
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4742
+ const signature = await this.signCreateReferralCode(opts);
4743
+ return apiCreateReferralCode({ signature }, { baseApiUrl, timeoutMs });
4744
+ }
4745
+ async redeemReferralCode(code, opts) {
4746
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4747
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
4748
+ return apiRedeemReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
4749
+ }
4750
+ async redeemReferralCodeWithSignature(code, opts) {
4751
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4752
+ const normalizedCode = normalizeReferralCode(code);
4753
+ const lookup = opts?.referrerWalletAddress ? void 0 : await this.lookupReferralCode(normalizedCode, { baseApiUrl, timeoutMs });
4754
+ const referrerWalletAddress = opts?.referrerWalletAddress ?? lookup?.referrerWalletAddress;
4755
+ if (!referrerWalletAddress) {
4756
+ throw new ValidationError(
4757
+ "referrerWalletAddress is required for referral signature auth",
4758
+ "referrerWalletAddress"
4759
+ );
4760
+ }
4761
+ if (lookup && !lookup.isActive) {
4762
+ throw new ValidationError("Referral code is not active", "code");
4763
+ }
4764
+ const signature = await this.signRedeemReferralCode(
4765
+ normalizedCode,
4766
+ referrerWalletAddress,
4767
+ opts
4768
+ );
4769
+ return apiRedeemReferralCode({ code: normalizedCode, signature }, { baseApiUrl, timeoutMs });
4770
+ }
4771
+ async updateReferralCode(code, opts) {
4772
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4773
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
4774
+ return apiUpdateReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
4775
+ }
4776
+ async updateReferralCodeWithSignature(code, opts) {
4777
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
4778
+ const signature = await this.signRenameReferralCode(code, opts.oldCode, opts);
4779
+ return apiUpdateReferralCode({ code, signature }, { baseApiUrl, timeoutMs });
4780
+ }
4781
+ resolveRequestOptions(opts) {
4782
+ return {
4783
+ baseApiUrl: this.stripTrailingSlash(
4784
+ opts?.baseApiUrl ?? this.config.getBaseApiUrl() ?? DEFAULT_BASE_API_URL
4785
+ ),
4786
+ timeoutMs: opts?.timeoutMs ?? this.config.getApiTimeoutMs()
4896
4787
  };
4897
- let managerRaw;
4898
- let scopedRates = [];
4899
- let scopedRecentStats = [];
4900
- let scopedDelegations = [];
4901
- let aggregate = null;
4902
- try {
4903
- const result = await this.client.query({
4904
- query: RATE_MANAGER_DETAIL_QUERY,
4905
- variables: baseVariables
4906
- });
4907
- managerRaw = result.RateManager?.[0];
4908
- if (!managerRaw) return null;
4909
- const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
4910
- scopedRates = (result.RateManagerRate ?? []).filter(
4911
- (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
4788
+ }
4789
+ stripTrailingSlash(url) {
4790
+ return url.replace(/\/$/, "");
4791
+ }
4792
+ async resolveAuthorizationToken(opts) {
4793
+ if (opts?.authorizationToken !== void 0) {
4794
+ return opts.authorizationToken;
4795
+ }
4796
+ const provider = opts?.getAuthorizationToken ?? this.config.getAuthorizationTokenProvider();
4797
+ if (provider) {
4798
+ return await provider() ?? void 0;
4799
+ }
4800
+ return this.config.getAuthorizationToken();
4801
+ }
4802
+ resolveAudience(audience) {
4803
+ if (audience) return audience;
4804
+ if (this.config.getChainId() === hardhat.id) return "localhardhat";
4805
+ if (this.config.getRuntimeEnv() === "staging") return "base_staging";
4806
+ return "base_production";
4807
+ }
4808
+ resolveIssuedAt(issuedAt) {
4809
+ const resolved = issuedAt ?? Math.floor(Date.now() / 1e3);
4810
+ if (!Number.isInteger(resolved) || resolved <= 0) {
4811
+ throw new ValidationError("issuedAt must be a positive unix timestamp", "issuedAt");
4812
+ }
4813
+ return resolved;
4814
+ }
4815
+ getSigningAccount() {
4816
+ const walletClient = this.config.getWalletClient();
4817
+ const account = walletClient.account;
4818
+ if (!account) {
4819
+ throw new ValidationError(
4820
+ "walletClient account is required for referral signature auth",
4821
+ "walletClient.account"
4912
4822
  );
4913
- scopedRecentStats = (result.ManagerStats ?? []).filter((stats) => {
4914
- const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
4915
- return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
4916
- });
4917
- scopedDelegations = (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation)).filter(
4918
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
4823
+ }
4824
+ const rawAddress = typeof account === "string" ? account : account.address;
4825
+ const walletAddress = normalizeAddress(rawAddress);
4826
+ if (!walletAddress) {
4827
+ throw new ValidationError(
4828
+ "walletClient account address is required for referral signature auth",
4829
+ "walletClient.account"
4919
4830
  );
4920
- aggregate = (result.ManagerAggregateStats ?? []).find(
4921
- (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
4922
- ) ?? result.ManagerAggregateStats?.[0] ?? null;
4923
- } catch (error) {
4924
- if (!isSchemaCompatibilityError(error)) {
4925
- throw error;
4831
+ }
4832
+ return { account, walletAddress };
4833
+ }
4834
+ normalizeReferralWalletAddress(address, field) {
4835
+ const normalized = normalizeAddress(address.toLowerCase());
4836
+ if (!normalized) {
4837
+ throw new ValidationError(`${field} must be a valid Ethereum address`, field);
4838
+ }
4839
+ return normalized;
4840
+ }
4841
+ async signCreateReferralCode(opts) {
4842
+ const { account, walletAddress } = this.getSigningAccount();
4843
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
4844
+ const audience = this.resolveAudience(opts?.audience);
4845
+ const signature = await this.config.getWalletClient().signTypedData({
4846
+ account,
4847
+ domain: REFERRAL_SIGNATURE_DOMAIN,
4848
+ types: REFERRAL_SIGNATURE_TYPES,
4849
+ primaryType: "CreateCode",
4850
+ message: { wallet: walletAddress, audience, issuedAt: BigInt(issuedAt) }
4851
+ });
4852
+ return { walletAddress, signature, issuedAt, audience };
4853
+ }
4854
+ async signRedeemReferralCode(code, referrerWalletAddress, opts) {
4855
+ const { account, walletAddress } = this.getSigningAccount();
4856
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
4857
+ const audience = this.resolveAudience(opts?.audience);
4858
+ const normalizedCode = normalizeReferralCode(code);
4859
+ const referrer = this.normalizeReferralWalletAddress(
4860
+ referrerWalletAddress,
4861
+ "referrerWalletAddress"
4862
+ );
4863
+ const signature = await this.config.getWalletClient().signTypedData({
4864
+ account,
4865
+ domain: REFERRAL_SIGNATURE_DOMAIN,
4866
+ types: REFERRAL_SIGNATURE_TYPES,
4867
+ primaryType: "RedeemCode",
4868
+ message: {
4869
+ wallet: walletAddress,
4870
+ code: normalizedCode,
4871
+ referrer,
4872
+ audience,
4873
+ issuedAt: BigInt(issuedAt)
4926
4874
  }
4927
- const legacyResult = await this.client.query({
4928
- query: LEGACY_RATE_MANAGER_DETAIL_QUERY,
4929
- variables: legacyVariables
4930
- });
4931
- managerRaw = legacyResult.RateManager?.[0];
4932
- if (!managerRaw) return null;
4933
- const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
4934
- scopedRates = (legacyResult.RateManagerRate ?? []).filter(
4935
- (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
4936
- );
4937
- scopedRecentStats = (legacyResult.ManagerStats ?? []).filter((stats) => {
4938
- const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
4939
- return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
4940
- });
4941
- scopedDelegations = (legacyResult.RateManagerDelegation ?? []).filter(
4942
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
4943
- );
4944
- aggregate = (legacyResult.ManagerAggregateStats ?? []).find(
4945
- (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
4946
- ) ?? legacyResult.ManagerAggregateStats?.[0] ?? null;
4875
+ });
4876
+ return { walletAddress, signature, issuedAt, audience, referrer };
4877
+ }
4878
+ async signRenameReferralCode(newCode, oldCode, opts) {
4879
+ const { account, walletAddress } = this.getSigningAccount();
4880
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
4881
+ const audience = this.resolveAudience(opts?.audience);
4882
+ const normalizedOldCode = normalizeReferralCode(oldCode);
4883
+ const normalizedNewCode = normalizeReferralCode(newCode);
4884
+ const signature = await this.config.getWalletClient().signTypedData({
4885
+ account,
4886
+ domain: REFERRAL_SIGNATURE_DOMAIN,
4887
+ types: REFERRAL_SIGNATURE_TYPES,
4888
+ primaryType: "RenameCode",
4889
+ message: {
4890
+ wallet: walletAddress,
4891
+ oldCode: normalizedOldCode,
4892
+ newCode: normalizedNewCode,
4893
+ audience,
4894
+ issuedAt: BigInt(issuedAt)
4895
+ }
4896
+ });
4897
+ return { walletAddress, signature, issuedAt, audience, oldCode: normalizedOldCode };
4898
+ }
4899
+ };
4900
+
4901
+ // src/client/VaultOperations.ts
4902
+ var VaultOperations = class {
4903
+ constructor(config) {
4904
+ this.config = config;
4905
+ }
4906
+ supportsInlineOracleRateConfig(params) {
4907
+ const escrowContext = this.config.host.resolveEscrowContext({
4908
+ escrowAddress: params?.escrowAddress
4909
+ });
4910
+ return escrowCurrencyHasOracleConfig(escrowContext.abi);
4911
+ }
4912
+ resolveRateManagerRegistryContract(registryAddress) {
4913
+ const abi = this.config.getRateManagerRegistryAbi();
4914
+ if (!abi) {
4915
+ throw this.buildRateManagerUnavailableError("Rate manager registry not available");
4916
+ }
4917
+ if (registryAddress) {
4918
+ return {
4919
+ address: registryAddress,
4920
+ abi
4921
+ };
4922
+ }
4923
+ const address = this.config.getRateManagerRegistryAddress();
4924
+ if (!address) {
4925
+ throw this.buildRateManagerUnavailableError("Rate manager registry not available");
4947
4926
  }
4948
- if (!managerRaw) return null;
4949
- const manager = normalizeRateManagerEntity(managerRaw);
4950
4927
  return {
4951
- manager,
4952
- rates: scopedRates,
4953
- aggregate,
4954
- recentStats: scopedRecentStats,
4955
- delegations: scopedDelegations
4928
+ address,
4929
+ abi
4956
4930
  };
4957
4931
  }
4958
- async fetchRateManagerDelegations(rateManagerId, pagination) {
4959
- if (!rateManagerId) return [];
4960
- const normalizedId = normalizeRateManagerId2(rateManagerId);
4961
- const normalizedRateManagerAddress = normalizeAddress3(pagination?.rateManagerAddress);
4962
- const variables = {
4963
- where: {
4964
- rateManagerId: { _eq: normalizedId },
4965
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
4966
- },
4967
- order_by: this.buildDelegationOrderBy(pagination),
4968
- limit: pagination?.limit ?? DEFAULT_LIMIT2,
4969
- offset: pagination?.offset ?? 0
4932
+ buildRateManagerUnavailableError(reason) {
4933
+ const initError = this.config.getRateManagerInitError();
4934
+ if (!initError) {
4935
+ return new Error(reason);
4936
+ }
4937
+ return new Error(
4938
+ `${reason}. Rate manager contracts failed to initialize: ${initError.message}`
4939
+ );
4940
+ }
4941
+ buildCreateRateManagerConfig(config) {
4942
+ const registryAbi = this.config.getRateManagerRegistryAbi();
4943
+ const includeDepositHook = abiTupleHasComponent(
4944
+ registryAbi,
4945
+ "createRateManager",
4946
+ "depositHook"
4947
+ );
4948
+ const includeMinLiquidity = abiTupleHasComponent(
4949
+ registryAbi,
4950
+ "createRateManager",
4951
+ "minLiquidity"
4952
+ );
4953
+ const result = {
4954
+ manager: config.manager,
4955
+ feeRecipient: config.feeRecipient,
4956
+ maxFee: config.maxFee,
4957
+ fee: config.fee
4970
4958
  };
4971
- try {
4972
- const result = await this.client.query({
4973
- query: RATE_MANAGER_DELEGATIONS_QUERY,
4974
- variables
4975
- });
4976
- return (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation));
4977
- } catch (error) {
4978
- if (!isSchemaCompatibilityError(error)) {
4979
- throw error;
4980
- }
4981
- const legacyResult = await this.client.query({
4982
- query: LEGACY_RATE_MANAGER_DELEGATIONS_QUERY,
4983
- variables: {
4984
- ...variables,
4985
- order_by: this.buildLegacyDelegationOrderBy(pagination)
4986
- }
4987
- });
4988
- return legacyResult.RateManagerDelegation ?? [];
4959
+ if (includeDepositHook) {
4960
+ result.depositHook = config.depositHook ?? ZERO_ADDRESS;
4961
+ }
4962
+ if (includeMinLiquidity) {
4963
+ result.minLiquidity = config.minLiquidity ?? 0n;
4964
+ }
4965
+ result.name = config.name;
4966
+ result.uri = config.uri;
4967
+ return result;
4968
+ }
4969
+ buildSetRateManagerConfigArgs(params) {
4970
+ const registryAbi = this.config.getRateManagerRegistryAbi();
4971
+ const includeHook = abiFunctionHasInput(registryAbi, "setRateManagerConfig", "_newHook") || abiFunctionHasInput(registryAbi, "setRateManagerConfig", "newHook");
4972
+ if (includeHook) {
4973
+ return [
4974
+ params.rateManagerId,
4975
+ params.newManager,
4976
+ params.newFeeRecipient,
4977
+ params.newHook ?? ZERO_ADDRESS,
4978
+ params.newName,
4979
+ params.newUri
4980
+ ];
4981
+ }
4982
+ return [
4983
+ params.rateManagerId,
4984
+ params.newManager,
4985
+ params.newFeeRecipient,
4986
+ params.newName,
4987
+ params.newUri
4988
+ ];
4989
+ }
4990
+ prepareRateManagerRegistryTransaction(opts) {
4991
+ const contract = this.resolveRateManagerRegistryContract(opts.registry);
4992
+ const functionName = resolveAbiFunctionName(contract.abi, opts.functionNames);
4993
+ return this.config.host.prepareContractTransaction({
4994
+ address: contract.address,
4995
+ abi: contract.abi,
4996
+ functionName,
4997
+ args: opts.args,
4998
+ txOverrides: opts.txOverrides
4999
+ });
5000
+ }
5001
+ prepareCreateRateManagerTransaction(params) {
5002
+ return this.prepareRateManagerRegistryTransaction({
5003
+ functionNames: ["createRateManager"],
5004
+ args: [this.buildCreateRateManagerConfig(params.config)],
5005
+ txOverrides: params.txOverrides
5006
+ });
5007
+ }
5008
+ prepareSetVaultRateTransaction(params) {
5009
+ return this.prepareRateManagerRegistryTransaction({
5010
+ functionNames: ["setRate", "setMinRate"],
5011
+ args: [params.rateManagerId, params.paymentMethodHash, params.currencyHash, params.rate],
5012
+ txOverrides: params.txOverrides
5013
+ });
5014
+ }
5015
+ prepareSetVaultRatesBatchTransaction(params) {
5016
+ return this.prepareRateManagerRegistryTransaction({
5017
+ functionNames: ["setRateBatch", "setMinRatesBatch"],
5018
+ args: [params.rateManagerId, params.paymentMethods, params.currencies, params.rates],
5019
+ txOverrides: params.txOverrides
5020
+ });
5021
+ }
5022
+ prepareSetOracleRateConfigTransaction(params) {
5023
+ const escrowContext = this.config.host.resolveEscrowContext({
5024
+ escrowAddress: params.escrowAddress,
5025
+ depositId: params.depositId
5026
+ });
5027
+ if (escrowContext.version !== "v2") {
5028
+ throw new Error("setOracleRateConfig requires EscrowV2");
5029
+ }
5030
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfig"]);
5031
+ return this.config.host.prepareEscrowTransaction({
5032
+ functionName,
5033
+ args: [
5034
+ parseRawDepositId(params.depositId),
5035
+ params.paymentMethodHash,
5036
+ params.currencyHash,
5037
+ normalizeOracleRateConfig(params.config)
5038
+ ],
5039
+ txOverrides: params.txOverrides,
5040
+ escrowAddress: escrowContext.address,
5041
+ escrowAbi: escrowContext.abi
5042
+ });
5043
+ }
5044
+ prepareRemoveOracleRateConfigTransaction(params) {
5045
+ const escrowContext = this.config.host.resolveEscrowContext({
5046
+ escrowAddress: params.escrowAddress,
5047
+ depositId: params.depositId
5048
+ });
5049
+ if (escrowContext.version !== "v2") {
5050
+ throw new Error("removeOracleRateConfig requires EscrowV2");
4989
5051
  }
5052
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["removeOracleRateConfig"]);
5053
+ return this.config.host.prepareEscrowTransaction({
5054
+ functionName,
5055
+ args: [parseRawDepositId(params.depositId), params.paymentMethodHash, params.currencyHash],
5056
+ txOverrides: params.txOverrides,
5057
+ escrowAddress: escrowContext.address,
5058
+ escrowAbi: escrowContext.abi
5059
+ });
4990
5060
  }
4991
- async fetchManagerDailySnapshots(rateManagerId, options) {
4992
- if (!rateManagerId) return [];
4993
- const normalizedId = normalizeRateManagerId2(rateManagerId);
4994
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
4995
- try {
4996
- const result = await this.client.query({
4997
- query: MANAGER_DAILY_SNAPSHOTS_QUERY,
4998
- variables: {
4999
- where: {
5000
- rateManagerId: { _eq: normalizedId },
5001
- ...normalizedRateManagerAddress ? {
5002
- id: {
5003
- _ilike: buildRateManagerScopedIdPattern(
5004
- normalizedId,
5005
- normalizedRateManagerAddress
5006
- )
5007
- }
5008
- } : {}
5009
- },
5010
- order_by: [{ dayTimestamp: "asc" }],
5011
- limit: options?.limit ?? 365
5012
- }
5013
- });
5014
- return result.ManagerDailySnapshot ?? [];
5015
- } catch (error) {
5016
- if (!isSchemaCompatibilityError(error)) {
5017
- throw error;
5018
- }
5019
- return [];
5061
+ prepareSetOracleRateConfigBatchTransaction(params) {
5062
+ const escrowContext = this.config.host.resolveEscrowContext({
5063
+ escrowAddress: params.escrowAddress,
5064
+ depositId: params.depositId
5065
+ });
5066
+ if (escrowContext.version !== "v2") {
5067
+ throw new Error("setOracleRateConfigBatch requires EscrowV2");
5020
5068
  }
5069
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfigBatch"]);
5070
+ return this.config.host.prepareEscrowTransaction({
5071
+ functionName,
5072
+ args: [
5073
+ parseRawDepositId(params.depositId),
5074
+ params.paymentMethods,
5075
+ params.currencies,
5076
+ params.configs.map((group) => group.map((config) => normalizeOracleRateConfig(config)))
5077
+ ],
5078
+ txOverrides: params.txOverrides,
5079
+ escrowAddress: escrowContext.address,
5080
+ escrowAbi: escrowContext.abi
5081
+ });
5021
5082
  }
5022
- async fetchDelegationForDeposit(depositId, options) {
5023
- if (!depositId) return null;
5024
- const normalizedDepositId = normalizeCompositeDepositId(depositId, options?.escrowAddress);
5025
- try {
5026
- const result = await this.client.query({
5027
- query: DEPOSIT_DELEGATION_QUERY,
5028
- variables: {
5029
- depositId: normalizedDepositId
5030
- }
5031
- });
5032
- const delegationDeposit = result.Deposit?.[0];
5033
- if (!delegationDeposit) {
5034
- return null;
5035
- }
5036
- return toDelegationEntityFromDeposit(delegationDeposit) ?? null;
5037
- } catch (error) {
5038
- if (!isSchemaCompatibilityError(error)) {
5039
- throw error;
5040
- }
5041
- const legacyResult = await this.client.query({
5042
- query: LEGACY_DEPOSIT_DELEGATION_QUERY,
5043
- variables: {
5044
- depositId: normalizedDepositId
5045
- }
5046
- });
5047
- return legacyResult.RateManagerDelegation?.[0] ?? null;
5083
+ prepareUpdateCurrencyConfigBatchTransaction(params) {
5084
+ const escrowContext = this.config.host.resolveEscrowContext({
5085
+ escrowAddress: params.escrowAddress,
5086
+ depositId: params.depositId
5087
+ });
5088
+ if (escrowContext.version !== "v2") {
5089
+ throw new Error("updateCurrencyConfigBatch requires EscrowV2");
5048
5090
  }
5091
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["updateCurrencyConfigBatch"]);
5092
+ return this.config.host.prepareEscrowTransaction({
5093
+ functionName,
5094
+ args: [
5095
+ parseRawDepositId(params.depositId),
5096
+ params.paymentMethods,
5097
+ params.updates.map(
5098
+ (group) => group.map((update) => ({
5099
+ code: update.code,
5100
+ minConversionRate: typeof update.minConversionRate === "bigint" ? update.minConversionRate : BigInt(update.minConversionRate),
5101
+ updateOracle: update.updateOracle,
5102
+ oracleRateConfig: normalizeOracleRateConfig(update.oracleRateConfig)
5103
+ }))
5104
+ )
5105
+ ],
5106
+ txOverrides: params.txOverrides,
5107
+ escrowAddress: escrowContext.address,
5108
+ escrowAbi: escrowContext.abi
5109
+ });
5049
5110
  }
5050
- async fetchManualRateUpdates(rateManagerId, options) {
5051
- if (!rateManagerId) return [];
5052
- const normalizedId = normalizeRateManagerId2(rateManagerId);
5053
- try {
5054
- const result = await this.client.query({
5055
- query: MANUAL_RATE_UPDATES_QUERY,
5056
- variables: {
5057
- where: {
5058
- rateManagerId: { _eq: normalizedId }
5059
- },
5060
- order_by: [{ id: "desc" }],
5061
- limit: options?.limit ?? 100
5062
- }
5063
- });
5064
- return (result.RateManagerV1_RateManagerRateUpdated ?? []).map((e) => ({
5065
- ...e,
5066
- currency: e.currency ?? e.currencyCode ?? "",
5067
- minRate: e.minRate ?? e.rate ?? "0"
5068
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5069
- } catch (error) {
5070
- if (!isSchemaCompatibilityError(error)) {
5071
- throw error;
5072
- }
5073
- return [];
5111
+ prepareDeactivateCurrenciesBatchTransaction(params) {
5112
+ const escrowContext = this.config.host.resolveEscrowContext({
5113
+ escrowAddress: params.escrowAddress,
5114
+ depositId: params.depositId
5115
+ });
5116
+ if (escrowContext.version !== "v2") {
5117
+ throw new Error("deactivateCurrenciesBatch requires EscrowV2");
5074
5118
  }
5119
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["deactivateCurrenciesBatch"]);
5120
+ return this.config.host.prepareEscrowTransaction({
5121
+ functionName,
5122
+ args: [parseRawDepositId(params.depositId), params.paymentMethods, params.currencyCodes],
5123
+ txOverrides: params.txOverrides,
5124
+ escrowAddress: escrowContext.address,
5125
+ escrowAbi: escrowContext.abi
5126
+ });
5075
5127
  }
5076
- async fetchOracleConfigUpdates(rateManagerId, options) {
5077
- if (!rateManagerId) return [];
5078
- const normalizedId = normalizeRateManagerId2(rateManagerId);
5079
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
5080
- const limit = options?.limit ?? 100;
5081
- try {
5082
- const depositScopes = await this.fetchHistoricalRateManagerDepositScopes(
5083
- normalizedId,
5084
- normalizedRateManagerAddress || void 0
5085
- );
5086
- if (!depositScopes.length) {
5087
- return [];
5088
- }
5089
- const scopedKeys = new Set(depositScopes.map((scope) => buildDepositScopeKey(scope)));
5090
- const result = await this.client.query({
5091
- query: ORACLE_CONFIG_UPDATES_QUERY,
5092
- variables: {
5093
- where: {
5094
- _or: depositScopes.map((scope) => ({
5095
- _and: [
5096
- { depositId: { _eq: scope.depositIdOnContract } },
5097
- { escrow: { _eq: scope.escrow } }
5098
- ]
5099
- }))
5100
- },
5101
- order_by: [{ id: "desc" }],
5102
- limit
5103
- }
5128
+ prepareSetVaultConfigTransaction(params) {
5129
+ return this.prepareRateManagerRegistryTransaction({
5130
+ functionNames: ["setRateManagerConfig"],
5131
+ args: this.buildSetRateManagerConfigArgs(params),
5132
+ txOverrides: params.txOverrides
5133
+ });
5134
+ }
5135
+ async getDepositRateManager(escrow, depositId) {
5136
+ const id = parseRawDepositId(depositId);
5137
+ const escrowContext = this.config.host.resolveEscrowContext({
5138
+ escrowAddress: escrow,
5139
+ depositId
5140
+ });
5141
+ if (getRateManagerReadFunction(escrowContext.abi, "getDepositRateManager")) {
5142
+ const result = await this.config.getPublicClient().readContract({
5143
+ address: escrowContext.address,
5144
+ abi: escrowContext.abi,
5145
+ functionName: "getDepositRateManager",
5146
+ args: [id]
5104
5147
  });
5105
- return (result.EscrowV2_DepositOracleRateConfigSet ?? []).filter((event) => {
5106
- const escrow = normalizeAddress3(event.escrow);
5107
- const depositIdOnContract = event.depositIdOnContract ?? event.depositId?.toString?.() ?? "";
5108
- if (!escrow || !depositIdOnContract) return false;
5109
- return scopedKeys.has(
5110
- buildDepositScopeKey({
5111
- escrow,
5112
- depositIdOnContract
5113
- })
5114
- );
5115
- }).map((e) => ({
5116
- ...e,
5117
- rateManagerId: normalizedId,
5118
- escrow: normalizeAddress3(e.escrow) || void 0,
5119
- currency: e.currency ?? e.currencyCode ?? "",
5120
- depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
5121
- adapter: e.adapter ?? "",
5122
- spreadBps: e.spreadBps ?? 0
5123
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5124
- } catch (error) {
5125
- if (isSchemaCompatibilityError(error)) ; else {
5126
- throw error;
5148
+ if (result && result.length >= 2) {
5149
+ return {
5150
+ registry: result[0],
5151
+ rateManagerId: result[1]
5152
+ };
5127
5153
  }
5128
- const legacyResult = await this.client.query({
5129
- query: LEGACY_ORACLE_CONFIG_UPDATES_QUERY,
5130
- variables: {
5131
- where: {
5132
- rateManagerId: { _eq: normalizedId }
5133
- },
5134
- order_by: [{ id: "desc" }],
5135
- limit
5136
- }
5154
+ }
5155
+ const controllerAddress = this.config.getRateManagerControllerAddress();
5156
+ const controllerAbi = this.config.getRateManagerControllerAbi();
5157
+ if (!controllerAddress || !controllerAbi) {
5158
+ throw this.buildRateManagerUnavailableError("Rate manager controller not available");
5159
+ }
5160
+ const legacyResult = await this.config.getPublicClient().readContract({
5161
+ address: controllerAddress,
5162
+ abi: controllerAbi,
5163
+ functionName: "getDepositRateManager",
5164
+ args: [escrow, id]
5165
+ });
5166
+ return {
5167
+ registry: legacyResult[0],
5168
+ rateManagerId: legacyResult[1]
5169
+ };
5170
+ }
5171
+ async getManagerFee(escrow, depositId) {
5172
+ const id = parseRawDepositId(depositId);
5173
+ const escrowContext = this.config.host.resolveEscrowContext({
5174
+ escrowAddress: escrow,
5175
+ depositId
5176
+ });
5177
+ if (getRateManagerReadFunction(escrowContext.abi, "getManagerFee")) {
5178
+ const result2 = await this.config.getPublicClient().readContract({
5179
+ address: escrowContext.address,
5180
+ abi: escrowContext.abi,
5181
+ functionName: "getManagerFee",
5182
+ args: [id]
5137
5183
  });
5138
- return (legacyResult.RateManagerV1_DepositorFloorSet ?? []).map((e) => ({
5139
- ...e,
5140
- currency: e.currency ?? e.currencyCode ?? "",
5141
- depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
5142
- adapter: e.adapter ?? e.oracleAdapter ?? "",
5143
- spreadBps: e.spreadBps ?? e.floorSpreadBps ?? 0
5144
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5184
+ return parseManagerFeeFromRead(result2);
5185
+ }
5186
+ const controllerAddress = this.config.getRateManagerControllerAddress();
5187
+ const controllerAbi = this.config.getRateManagerControllerAbi();
5188
+ if (!controllerAddress || !controllerAbi) {
5189
+ throw this.buildRateManagerUnavailableError("Rate manager controller not available");
5145
5190
  }
5191
+ const result = await this.config.getPublicClient().readContract({
5192
+ address: controllerAddress,
5193
+ abi: controllerAbi,
5194
+ functionName: "getManagerFee",
5195
+ args: [escrow, id]
5196
+ });
5197
+ return parseManagerFeeFromRead(result);
5198
+ }
5199
+ async getEffectiveRate(params) {
5200
+ const escrowContext = this.config.host.resolveEscrowContext({
5201
+ escrowAddress: params.escrow,
5202
+ depositId: params.depositId
5203
+ });
5204
+ const id = parseRawDepositId(params.depositId);
5205
+ return await this.config.getPublicClient().readContract({
5206
+ address: escrowContext.address,
5207
+ abi: escrowContext.abi,
5208
+ functionName: "getEffectiveRate",
5209
+ args: [id, params.paymentMethod, params.fiatCurrency]
5210
+ });
5146
5211
  }
5147
5212
  };
5213
+ var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && abi.some(
5214
+ (item) => item.type === "function" && item.name === functionName
5215
+ );
5148
5216
 
5149
- // src/indexer/intentVerification.ts
5150
- async function fetchFulfillmentAndPayment(client, intentHash) {
5151
- return client.query({
5152
- query: FULFILLMENT_AND_PAYMENT_QUERY,
5153
- variables: { intentHash }
5154
- });
5217
+ // src/indexer/rateManagerService.ts
5218
+ var DEFAULT_LIMIT2 = 50;
5219
+ var RATE_MANAGER_HISTORY_PAGE_SIZE = 250;
5220
+ var EVM_ADDRESS_REGEX = /^0x[a-f0-9]{40}$/;
5221
+ function normalizeRateManagerId2(value) {
5222
+ if (!value) return "";
5223
+ return value.toLowerCase();
5155
5224
  }
5156
-
5157
- // src/utils/logger.ts
5158
- var currentLevel = "info";
5159
- function setLogLevel(level) {
5160
- currentLevel = level;
5225
+ function normalizeAddress3(value) {
5226
+ if (!value) return "";
5227
+ return value.toLowerCase();
5161
5228
  }
5162
- function shouldLog(level) {
5163
- switch (currentLevel) {
5164
- case "debug":
5165
- return true;
5166
- case "info":
5167
- return level !== "debug";
5168
- case "error":
5169
- return level === "error";
5170
- default:
5171
- return true;
5172
- }
5229
+ function escapeLikePatternLiteral(value) {
5230
+ return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
5173
5231
  }
5174
- var logger = {
5175
- debug: (...args) => {
5176
- if (shouldLog("debug")) {
5177
- console.log("[DEBUG]", ...args);
5178
- }
5179
- },
5180
- info: (...args) => {
5181
- if (shouldLog("info")) {
5182
- console.log("[INFO]", ...args);
5183
- }
5184
- },
5185
- warn: (...args) => {
5186
- if (shouldLog("info")) {
5187
- console.warn("[WARN]", ...args);
5188
- }
5189
- },
5190
- error: (...args) => {
5191
- console.error("[ERROR]", ...args);
5192
- }
5193
- };
5194
-
5195
- // src/referral.ts
5196
- var normalizeReferralCode = (code) => code.trim().toUpperCase();
5197
- var isValidReferralCode = (code) => /^[A-Z0-9]{6}$/.test(normalizeReferralCode(code));
5198
-
5199
- // src/adapters/api.ts
5200
- function createHeaders(apiKey, authorizationToken) {
5201
- const headers2 = { "Content-Type": "application/json" };
5202
- if (apiKey) headers2["x-api-key"] = apiKey;
5203
- if (authorizationToken) {
5204
- headers2.Authorization = authorizationToken.startsWith("Bearer ") ? authorizationToken : `Bearer ${authorizationToken}`;
5232
+ function parseScopedRateManagerFilterId(value) {
5233
+ const trimmed = value.trim().toLowerCase();
5234
+ if (!trimmed) return null;
5235
+ const separatorIndex = trimmed.indexOf(":");
5236
+ if (separatorIndex <= 0) return null;
5237
+ const rateManagerAddress = normalizeAddress3(trimmed.slice(0, separatorIndex));
5238
+ const rateManagerId = normalizeRateManagerId2(trimmed.slice(separatorIndex + 1));
5239
+ if (!EVM_ADDRESS_REGEX.test(rateManagerAddress) || !rateManagerId) {
5240
+ return null;
5205
5241
  }
5206
- return headers2;
5242
+ return { rateManagerAddress, rateManagerId };
5207
5243
  }
5208
- function withApiBase(baseApiUrl) {
5209
- const trimmed = (baseApiUrl || "").trim();
5210
- let base2 = trimmed.replace(/\/+$/, "");
5211
- base2 = base2.replace(/\/v1$/i, "");
5212
- base2 = base2.replace(/\/v2$/i, "");
5213
- return base2;
5244
+ function getManagerScopeKey(rateManagerId, rateManagerAddress) {
5245
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5246
+ const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
5247
+ return normalizedRateManagerAddress ? `${normalizedRateManagerAddress}:${normalizedId}` : normalizedId;
5214
5248
  }
5215
- async function apiFetch({
5216
- url,
5217
- method = "GET",
5218
- body,
5219
- apiKey,
5220
- authorizationToken,
5221
- timeoutMs,
5222
- retryCount = 3,
5223
- retryDelayMs = 1e3
5224
- }) {
5225
- const endpoint = url.replace(/^[^/]*\/\/[^/]*/, "");
5226
- return withRetry(
5227
- async () => {
5228
- let res;
5229
- try {
5230
- const options = {
5231
- method,
5232
- headers: createHeaders(apiKey, authorizationToken)
5233
- };
5234
- if (body && method !== "GET") {
5235
- options.body = JSON.stringify(body);
5236
- }
5237
- res = await fetch(url, options);
5238
- } catch (error) {
5239
- throw new NetworkError("Failed to connect to API server", { endpoint, error });
5240
- }
5241
- if (!res.ok) {
5242
- const errorText = await res.text();
5243
- throw parseAPIError(res, errorText);
5244
- }
5245
- return res.json();
5246
- },
5247
- retryCount,
5248
- retryDelayMs,
5249
- timeoutMs
5249
+ function extractRateManagerAddressFromScopedId(id) {
5250
+ if (!id) return null;
5251
+ const parts = id.split("_");
5252
+ if (parts.length < 3) return null;
5253
+ const rateManagerAddress = parts[1] ?? "";
5254
+ return rateManagerAddress.startsWith("0x") ? rateManagerAddress.toLowerCase() : null;
5255
+ }
5256
+ function buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress) {
5257
+ const normalizedId = escapeLikePatternLiteral(normalizeRateManagerId2(rateManagerId));
5258
+ const normalizedRateManagerAddress = escapeLikePatternLiteral(
5259
+ normalizeAddress3(rateManagerAddress)
5250
5260
  );
5261
+ return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
5251
5262
  }
5252
- function unwrapResponseObject(payload) {
5253
- if (payload && typeof payload === "object" && "responseObject" in payload) {
5254
- return payload.responseObject;
5255
- }
5256
- return payload;
5263
+ function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
5264
+ return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
5257
5265
  }
5258
- function requireAuthorizationToken(authorizationToken, endpoint) {
5259
- if (!authorizationToken) {
5260
- throw new ValidationError(`authorizationToken is required for ${endpoint}`, "authorizationToken");
5266
+ function normalizeCompositeDepositId(depositId, escrowAddress) {
5267
+ const normalizedDepositId = depositId.trim().toLowerCase();
5268
+ if (!normalizedDepositId) return "";
5269
+ if (normalizedDepositId.includes("_")) return normalizedDepositId;
5270
+ const normalizedEscrow = normalizeAddress3(escrowAddress);
5271
+ if (normalizedEscrow) {
5272
+ return `${normalizedEscrow}_${normalizedDepositId}`;
5261
5273
  }
5262
- return authorizationToken;
5274
+ return normalizedDepositId;
5263
5275
  }
5264
- function requireEscrowAddress(escrowAddress, endpoint) {
5265
- if (!escrowAddress) {
5266
- throw new ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
5267
- }
5268
- return escrowAddress;
5276
+ function extractDepositIdOnContract(compositeDepositId) {
5277
+ if (!compositeDepositId) return null;
5278
+ const parts = compositeDepositId.split("_");
5279
+ const rawDepositId = parts[parts.length - 1];
5280
+ return rawDepositId && /^\d+$/.test(rawDepositId) ? rawDepositId : null;
5269
5281
  }
5270
- function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
5271
- const normalized = withApiBase(baseApiUrl).toLowerCase();
5272
- if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
5273
- return "PREPRODUCTION";
5274
- }
5275
- if (normalized.includes("staging") || normalized.includes("/staging/") || normalized.includes("localhost") || normalized.includes("127.0.0.1")) {
5276
- return "STAGING";
5277
- }
5278
- return "PRODUCTION";
5282
+ function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
5283
+ if (!compositeDepositId) return null;
5284
+ const [escrowAddress] = compositeDepositId.split("_");
5285
+ return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
5279
5286
  }
5280
- async function withOptionalTimeout(promise, timeoutMs, endpoint) {
5281
- if (!timeoutMs || timeoutMs <= 0) return promise;
5282
- let timer;
5283
- try {
5284
- return await Promise.race([
5285
- promise,
5286
- new Promise((_, reject) => {
5287
- timer = setTimeout(() => {
5288
- reject(new NetworkError("Request timed out", { endpoint }));
5289
- }, timeoutMs);
5290
- })
5291
- ]);
5292
- } finally {
5293
- if (timer) clearTimeout(timer);
5287
+ function parseRateManagerFilterIds(rateManagerIds) {
5288
+ const bare = /* @__PURE__ */ new Set();
5289
+ const scoped = /* @__PURE__ */ new Map();
5290
+ for (const value of rateManagerIds) {
5291
+ const scopedRateManager = parseScopedRateManagerFilterId(value);
5292
+ if (scopedRateManager) {
5293
+ scoped.set(
5294
+ getManagerScopeKey(scopedRateManager.rateManagerId, scopedRateManager.rateManagerAddress),
5295
+ scopedRateManager
5296
+ );
5297
+ continue;
5298
+ }
5299
+ if (value.includes(":")) {
5300
+ continue;
5301
+ }
5302
+ const normalizedRateManagerId = normalizeRateManagerId2(value);
5303
+ if (normalizedRateManagerId) {
5304
+ bare.add(normalizedRateManagerId);
5305
+ }
5294
5306
  }
5307
+ return { bare, scoped };
5295
5308
  }
5296
- function toDateFromUnixSeconds(value) {
5297
- if (!value) return void 0;
5298
- const numeric = Number(value);
5299
- if (!Number.isFinite(numeric) || numeric <= 0) return void 0;
5300
- return new Date(numeric * 1e3);
5309
+ function buildDepositScopeKey(scope) {
5310
+ return `${scope.escrow}:${scope.depositIdOnContract}`;
5301
5311
  }
5302
- function toBigIntSafe(value) {
5303
- if (value === null || value === void 0) return 0n;
5312
+ function toSafeBigInt(value) {
5313
+ if (!value) return 0n;
5304
5314
  try {
5305
- return BigInt(value);
5315
+ return parseBigIntLike(value);
5306
5316
  } catch {
5307
5317
  return 0n;
5308
5318
  }
5309
5319
  }
5310
- function normalizeOwnerDepositsStatus(status) {
5311
- if (!status) return void 0;
5312
- if (status === "WITHDRAWN") return "CLOSED";
5313
- return status;
5320
+ function compareBigInt(a, b, direction) {
5321
+ if (a === b) return 0;
5322
+ if (direction === "asc") return a < b ? -1 : 1;
5323
+ return a > b ? -1 : 1;
5314
5324
  }
5315
- function buildLegacyVerifierCurrencies(deposit) {
5316
- const currenciesByMethod = /* @__PURE__ */ new Map();
5317
- for (const currency of deposit.currencies ?? []) {
5318
- const methodHash = currency.paymentMethodHash;
5319
- const resolvedConversionRate = currency.conversionRate ?? currency.minConversionRate;
5320
- if (resolvedConversionRate === null || resolvedConversionRate === void 0) {
5321
- logger.warn(
5322
- `[sdk] Skipping currency with missing conversion rate (deposit ${deposit.depositId}, currency ${currency.currencyCode})`
5323
- );
5324
- continue;
5325
+ function parseEventCursorId(id) {
5326
+ if (!id) return null;
5327
+ const [chainIdRaw, blockNumberRaw, logIndexRaw] = id.split("_");
5328
+ if (!chainIdRaw || !blockNumberRaw || !logIndexRaw) return null;
5329
+ if (!/^\d+$/.test(chainIdRaw) || !/^\d+$/.test(blockNumberRaw) || !/^\d+$/.test(logIndexRaw)) {
5330
+ return null;
5331
+ }
5332
+ try {
5333
+ return {
5334
+ chainId: BigInt(chainIdRaw),
5335
+ blockNumber: BigInt(blockNumberRaw),
5336
+ logIndex: BigInt(logIndexRaw)
5337
+ };
5338
+ } catch {
5339
+ return null;
5340
+ }
5341
+ }
5342
+ function compareEventCursorIdsByRecency(leftId, rightId) {
5343
+ const left = parseEventCursorId(leftId);
5344
+ const right = parseEventCursorId(rightId);
5345
+ if (left && right) {
5346
+ if (left.chainId !== right.chainId) {
5347
+ return left.chainId > right.chainId ? -1 : 1;
5325
5348
  }
5326
- const bucket = currenciesByMethod.get(methodHash) ?? [];
5327
- bucket.push({
5328
- currencyCode: currency.currencyCode,
5329
- conversionRate: resolvedConversionRate,
5330
- minConversionRate: currency.minConversionRate,
5331
- managerRate: currency.managerRate ?? null,
5332
- rateManagerId: currency.rateManagerId ?? null
5333
- });
5334
- currenciesByMethod.set(methodHash, bucket);
5349
+ if (left.blockNumber !== right.blockNumber) {
5350
+ return left.blockNumber > right.blockNumber ? -1 : 1;
5351
+ }
5352
+ if (left.logIndex !== right.logIndex) {
5353
+ return left.logIndex > right.logIndex ? -1 : 1;
5354
+ }
5355
+ return 0;
5335
5356
  }
5336
- return currenciesByMethod;
5357
+ return (rightId ?? "").localeCompare(leftId ?? "");
5337
5358
  }
5338
- function convertIndexerDepositToLegacyApiDeposit(deposit) {
5339
- const currenciesByMethod = buildLegacyVerifierCurrencies(deposit);
5340
- const verifiers = (deposit.paymentMethods ?? []).filter((paymentMethod) => paymentMethod.active !== false).map((paymentMethod) => ({
5341
- depositId: Number(deposit.depositId),
5342
- verifier: "",
5343
- methodHash: paymentMethod.paymentMethodHash,
5344
- intentGatingService: paymentMethod.intentGatingService,
5345
- payeeDetailsHash: paymentMethod.payeeDetailsHash,
5346
- data: "0x",
5347
- currencies: currenciesByMethod.get(paymentMethod.paymentMethodHash) ?? []
5348
- }));
5349
- const remainingDeposits = toBigIntSafe(deposit.remainingDeposits);
5350
- const outstandingIntentAmount = toBigIntSafe(deposit.outstandingIntentAmount);
5351
- const totalAmountTaken = toBigIntSafe(deposit.totalAmountTaken);
5352
- const totalWithdrawn = toBigIntSafe(deposit.totalWithdrawn);
5353
- const amount = remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn;
5359
+ function isAggregateOrderField(field) {
5360
+ return field === "currentDelegatedBalance" || field === "totalFilledVolume";
5361
+ }
5362
+ function normalizeRateManagerEntity(manager) {
5354
5363
  return {
5355
- id: Number(deposit.depositId),
5356
- depositor: deposit.depositor,
5357
- token: deposit.token,
5358
- amount: amount.toString(),
5359
- remainingDeposits: deposit.remainingDeposits,
5360
- intentAmountMin: deposit.intentAmountMin,
5361
- intentAmountMax: deposit.intentAmountMax,
5362
- acceptingIntents: deposit.acceptingIntents,
5363
- outstandingIntentAmount: deposit.outstandingIntentAmount,
5364
- availableLiquidity: deposit.remainingDeposits,
5365
- status: deposit.status,
5366
- totalIntents: deposit.totalIntents,
5367
- signaledIntents: deposit.signaledIntents,
5368
- fulfilledIntents: deposit.fulfilledIntents,
5369
- prunedIntents: deposit.prunedIntents,
5370
- totalAmountTaken: deposit.totalAmountTaken,
5371
- totalWithdrawn: deposit.totalWithdrawn,
5372
- successRateBps: deposit.successRateBps,
5373
- rateManagerId: deposit.rateManagerId ?? null,
5374
- vaultName: null,
5375
- rateManagerRegistry: null,
5376
- createdAt: toDateFromUnixSeconds(deposit.timestamp),
5377
- updatedAt: toDateFromUnixSeconds(deposit.updatedAt),
5378
- verifiers
5364
+ ...manager,
5365
+ rateManagerAddress: normalizeAddress3(manager.rateManagerAddress)
5379
5366
  };
5380
5367
  }
5381
- async function apiPostDepositDetails(req, baseApiUrl, timeoutMs) {
5382
- return apiFetch({
5383
- url: `${withApiBase(baseApiUrl)}/v2/makers/create`,
5384
- method: "POST",
5385
- body: req,
5386
- timeoutMs
5387
- });
5368
+ function toDelegationEntityFromDeposit(deposit) {
5369
+ const rateManagerId = normalizeRateManagerId2(deposit.rateManagerId);
5370
+ if (!rateManagerId) return null;
5371
+ const delegatedAt = deposit.delegatedAt ?? null;
5372
+ return {
5373
+ id: deposit.id,
5374
+ chainId: deposit.chainId,
5375
+ rateManagerId,
5376
+ rateManagerAddress: normalizeAddress3(deposit.rateManagerAddress) || null,
5377
+ depositId: deposit.id,
5378
+ delegatedAt,
5379
+ createdAt: delegatedAt ?? deposit.updatedAt,
5380
+ updatedAt: deposit.updatedAt
5381
+ };
5388
5382
  }
5389
- async function apiGetQuote(req, baseApiUrl, timeoutMs, apiKey) {
5390
- if (req.quotesToReturn !== void 0) {
5391
- if (!Number.isInteger(req.quotesToReturn) || req.quotesToReturn < 1) {
5392
- throw new ValidationError("quotesToReturn must be a positive integer", "quotesToReturn");
5383
+ var IndexerRateManagerService = class {
5384
+ constructor(client) {
5385
+ this.client = client;
5386
+ }
5387
+ buildRateManagerScopeWhere(rateManagerIds) {
5388
+ if (!rateManagerIds?.length) return void 0;
5389
+ const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
5390
+ const scopeConditions = [];
5391
+ if (bare.size > 0) {
5392
+ scopeConditions.push({
5393
+ rateManagerId: { _in: [...bare] }
5394
+ });
5395
+ }
5396
+ for (const scopedRateManager of scoped.values()) {
5397
+ scopeConditions.push({
5398
+ rateManagerId: { _eq: scopedRateManager.rateManagerId },
5399
+ rateManagerAddress: { _eq: scopedRateManager.rateManagerAddress }
5400
+ });
5401
+ }
5402
+ if (scopeConditions.length === 1) {
5403
+ return scopeConditions[0];
5404
+ }
5405
+ if (scopeConditions.length > 1) {
5406
+ return { _or: scopeConditions };
5407
+ }
5408
+ return void 0;
5409
+ }
5410
+ buildWhere(filter) {
5411
+ if (!filter) return void 0;
5412
+ const where = {};
5413
+ if (filter.manager) {
5414
+ where.manager = { _ilike: filter.manager };
5415
+ }
5416
+ if (filter.name) {
5417
+ where.name = { _ilike: `%${filter.name}%` };
5418
+ }
5419
+ if (filter.maxFee) {
5420
+ where.maxFee = { _lte: filter.maxFee };
5421
+ }
5422
+ const scopeWhere = this.buildRateManagerScopeWhere(filter.rateManagerIds);
5423
+ if (scopeWhere) {
5424
+ Object.assign(where, scopeWhere);
5425
+ }
5426
+ return Object.keys(where).length ? where : void 0;
5427
+ }
5428
+ buildAggregateWhere(filter) {
5429
+ return this.buildRateManagerScopeWhere(filter?.rateManagerIds) ?? {};
5430
+ }
5431
+ buildLegacyAggregateWhere(filter) {
5432
+ const rateManagerIds = filter?.rateManagerIds;
5433
+ if (!rateManagerIds?.length) return {};
5434
+ const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
5435
+ const scopeConditions = [];
5436
+ if (bare.size > 0) {
5437
+ scopeConditions.push({
5438
+ rateManagerId: { _in: [...bare] }
5439
+ });
5440
+ }
5441
+ for (const scopedRateManager of scoped.values()) {
5442
+ scopeConditions.push({
5443
+ rateManagerId: { _eq: scopedRateManager.rateManagerId },
5444
+ id: {
5445
+ _ilike: buildRateManagerAddressScopedIdPattern(
5446
+ scopedRateManager.rateManagerId,
5447
+ scopedRateManager.rateManagerAddress
5448
+ )
5449
+ }
5450
+ });
5451
+ }
5452
+ if (scopeConditions.length === 1) {
5453
+ return scopeConditions[0] ?? {};
5454
+ }
5455
+ if (scopeConditions.length > 1) {
5456
+ return { _or: scopeConditions };
5457
+ }
5458
+ return {};
5459
+ }
5460
+ buildOrderBy(pagination) {
5461
+ const rawField = pagination?.orderBy ?? "createdAt";
5462
+ const field = isAggregateOrderField(rawField) ? "createdAt" : rawField;
5463
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
5464
+ return [{ [field]: direction }];
5465
+ }
5466
+ toRateManagerListItems(result) {
5467
+ const managers = (result.RateManager ?? []).map(normalizeRateManagerEntity);
5468
+ const aggregatesByScope = /* @__PURE__ */ new Map();
5469
+ for (const aggregate of result.ManagerAggregateStats ?? []) {
5470
+ const aggregateRateManagerAddress = normalizeAddress3(aggregate.rateManagerAddress) || extractRateManagerAddressFromScopedId(aggregate.id);
5471
+ const scopeKey = getManagerScopeKey(aggregate.rateManagerId, aggregateRateManagerAddress);
5472
+ aggregatesByScope.set(scopeKey, aggregate);
5473
+ }
5474
+ return managers.map((manager) => ({
5475
+ manager,
5476
+ aggregate: aggregatesByScope.get(
5477
+ getManagerScopeKey(manager.rateManagerId, normalizeAddress3(manager.rateManagerAddress))
5478
+ ) ?? aggregatesByScope.get(getManagerScopeKey(manager.rateManagerId)) ?? null
5479
+ }));
5480
+ }
5481
+ applyHookFilter(rows, hasHook) {
5482
+ if (hasHook === void 0) return rows;
5483
+ return hasHook ? [] : rows;
5484
+ }
5485
+ async queryRateManagerList(variables, legacyVariables) {
5486
+ try {
5487
+ return await this.client.query({
5488
+ query: RATE_MANAGER_LIST_QUERY,
5489
+ variables
5490
+ });
5491
+ } catch (error) {
5492
+ if (!isSchemaCompatibilityError(error)) {
5493
+ throw error;
5494
+ }
5495
+ return this.client.query({
5496
+ query: LEGACY_RATE_MANAGER_LIST_QUERY,
5497
+ variables: legacyVariables
5498
+ });
5393
5499
  }
5394
5500
  }
5395
- if (!isValidHexAddress(req.user)) {
5396
- throw new ValidationError("user must be a valid Ethereum address", "user");
5501
+ buildDelegationOrderBy(pagination) {
5502
+ const rawField = pagination?.orderBy ?? "updatedAt";
5503
+ const field = rawField === "createdAt" ? "delegatedAt" : rawField;
5504
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
5505
+ return [{ [field]: direction }];
5397
5506
  }
5398
- if (!isValidHexAddress(req.recipient)) {
5399
- throw new ValidationError("recipient must be a valid Ethereum address", "recipient");
5507
+ buildLegacyDelegationOrderBy(pagination) {
5508
+ const rawField = pagination?.orderBy ?? "updatedAt";
5509
+ const field = rawField === "delegatedAt" ? "createdAt" : rawField;
5510
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
5511
+ return [{ [field]: direction }];
5400
5512
  }
5401
- if (!isValidHexAddress(req.destinationToken)) {
5402
- throw new ValidationError(
5403
- "destinationToken must be a valid Ethereum address",
5404
- "destinationToken"
5513
+ async fetchCurrentRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
5514
+ const scopes = /* @__PURE__ */ new Map();
5515
+ let offset = 0;
5516
+ for (; ; ) {
5517
+ const delegations = await this.fetchRateManagerDelegations(rateManagerId, {
5518
+ limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
5519
+ offset,
5520
+ orderBy: "delegatedAt",
5521
+ orderDirection: "desc",
5522
+ rateManagerAddress: rateManagerAddress || void 0
5523
+ });
5524
+ for (const delegation of delegations) {
5525
+ const escrow = extractEscrowAddressFromCompositeDepositId(delegation.depositId);
5526
+ const depositIdOnContract = extractDepositIdOnContract(delegation.depositId);
5527
+ if (!escrow || !depositIdOnContract) continue;
5528
+ const scope = { escrow, depositIdOnContract };
5529
+ scopes.set(buildDepositScopeKey(scope), scope);
5530
+ }
5531
+ if (delegations.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
5532
+ break;
5533
+ }
5534
+ offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
5535
+ }
5536
+ return [...scopes.values()];
5537
+ }
5538
+ async fetchHistoricalRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
5539
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5540
+ const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
5541
+ const scopes = /* @__PURE__ */ new Map();
5542
+ const currentScopes = await this.fetchCurrentRateManagerDepositScopes(
5543
+ normalizedId,
5544
+ normalizedRateManagerAddress || void 0
5405
5545
  );
5546
+ for (const scope of currentScopes) {
5547
+ scopes.set(buildDepositScopeKey(scope), scope);
5548
+ }
5549
+ try {
5550
+ let offset = 0;
5551
+ for (; ; ) {
5552
+ const result = await this.client.query({
5553
+ query: RATE_MANAGER_ASSIGNMENT_EVENTS_QUERY,
5554
+ variables: {
5555
+ setWhere: {
5556
+ rateManagerId: { _eq: normalizedId },
5557
+ ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
5558
+ },
5559
+ clearedWhere: {
5560
+ rateManagerId: { _eq: normalizedId },
5561
+ ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
5562
+ },
5563
+ limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
5564
+ offset
5565
+ }
5566
+ });
5567
+ const setEvents = result.EscrowV2_DepositRateManagerSet ?? [];
5568
+ const clearedEvents = result.EscrowV2_DepositRateManagerCleared ?? [];
5569
+ for (const event of [...setEvents, ...clearedEvents]) {
5570
+ const escrow = normalizeAddress3(event.escrow);
5571
+ const depositIdOnContract = event.depositIdOnContract?.toString() ?? "";
5572
+ if (!escrow || !depositIdOnContract) continue;
5573
+ const scope = { escrow, depositIdOnContract };
5574
+ scopes.set(buildDepositScopeKey(scope), scope);
5575
+ }
5576
+ if (setEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE && clearedEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
5577
+ break;
5578
+ }
5579
+ offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
5580
+ }
5581
+ } catch (error) {
5582
+ if (!isSchemaCompatibilityError(error)) {
5583
+ throw error;
5584
+ }
5585
+ }
5586
+ return [...scopes.values()];
5406
5587
  }
5407
- const isExactFiat = req.isExactFiat !== false;
5408
- const endpoint = isExactFiat ? "exact-fiat" : "exact-token";
5409
- let url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
5410
- if (req.quotesToReturn) url += `?quotesToReturn=${req.quotesToReturn}`;
5411
- const requestBody = {
5412
- ...req,
5413
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
5414
- amount: void 0,
5415
- isExactFiat: void 0,
5416
- quotesToReturn: void 0,
5417
- includePrivateOrderbooks: req.includePrivateOrderbooks
5418
- };
5419
- Object.keys(requestBody).forEach((k) => requestBody[k] === void 0 && delete requestBody[k]);
5420
- return apiFetch({
5421
- url,
5422
- method: "POST",
5423
- body: requestBody,
5424
- apiKey,
5425
- timeoutMs
5426
- });
5427
- }
5428
- async function apiGetQuotesBestByPlatform(req, baseApiUrl, timeoutMs, apiKey) {
5429
- const isExactFiat = req.isExactFiat !== false;
5430
- const endpoint = isExactFiat ? "best-by-platform" : "best-by-platform-exact-token";
5431
- const url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
5432
- const requestBody = {
5433
- ...req,
5434
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
5435
- amount: void 0,
5436
- isExactFiat: void 0,
5437
- referrerFeeConfig: void 0
5438
- };
5439
- Object.keys(requestBody).forEach(
5440
- (key) => requestBody[key] === void 0 && delete requestBody[key]
5441
- );
5442
- return apiFetch({
5443
- url,
5444
- method: "POST",
5445
- body: requestBody,
5446
- apiKey,
5447
- timeoutMs
5448
- });
5449
- }
5450
- async function apiGetPayeeDetails(req, baseApiUrl, timeoutMs) {
5451
- return apiFetch({
5452
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/${req.processorName}/${req.hashedOnchainId}`,
5453
- method: "GET",
5454
- timeoutMs
5455
- });
5456
- }
5457
- async function apiValidatePayeeDetails(req, baseApiUrl, timeoutMs) {
5458
- const data = await apiFetch({
5459
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/validate`,
5460
- method: "POST",
5461
- body: req,
5462
- timeoutMs
5463
- });
5464
- if (typeof data?.responseObject === "boolean") {
5588
+ async fetchRateManagers(pagination, filter) {
5589
+ const orderBy = pagination?.orderBy ?? "createdAt";
5590
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
5591
+ const limit = pagination?.limit ?? DEFAULT_LIMIT2;
5592
+ const offset = pagination?.offset ?? 0;
5593
+ const where = this.buildWhere(filter);
5594
+ const aggregateWhere = this.buildAggregateWhere(filter);
5595
+ const legacyAggregateWhere = this.buildLegacyAggregateWhere(filter);
5596
+ if (isAggregateOrderField(orderBy)) {
5597
+ const result2 = await this.queryRateManagerList(
5598
+ {
5599
+ where,
5600
+ aggregateWhere,
5601
+ order_by: [{ createdAt: "desc" }]
5602
+ },
5603
+ {
5604
+ where,
5605
+ aggregateWhere: legacyAggregateWhere,
5606
+ order_by: [{ createdAt: "desc" }]
5607
+ }
5608
+ );
5609
+ const scopedRows = this.applyHookFilter(this.toRateManagerListItems(result2), filter?.hasHook);
5610
+ const sorted = scopedRows.sort((a, b) => {
5611
+ const av = orderBy === "currentDelegatedBalance" ? toSafeBigInt(a.aggregate?.currentDelegatedBalance) : toSafeBigInt(a.aggregate?.totalFilledVolume);
5612
+ const bv = orderBy === "currentDelegatedBalance" ? toSafeBigInt(b.aggregate?.currentDelegatedBalance) : toSafeBigInt(b.aggregate?.totalFilledVolume);
5613
+ const aggregateCmp = compareBigInt(av, bv, direction);
5614
+ if (aggregateCmp !== 0) return aggregateCmp;
5615
+ const createdAtCmp = compareBigInt(
5616
+ toSafeBigInt(a.manager.createdAt),
5617
+ toSafeBigInt(b.manager.createdAt),
5618
+ "desc"
5619
+ );
5620
+ if (createdAtCmp !== 0) return createdAtCmp;
5621
+ return a.manager.rateManagerId.localeCompare(b.manager.rateManagerId);
5622
+ });
5623
+ return sorted.slice(offset, offset + limit);
5624
+ }
5625
+ const result = await this.queryRateManagerList(
5626
+ {
5627
+ where,
5628
+ aggregateWhere,
5629
+ order_by: this.buildOrderBy(pagination),
5630
+ limit,
5631
+ offset
5632
+ },
5633
+ {
5634
+ where,
5635
+ aggregateWhere: legacyAggregateWhere,
5636
+ order_by: this.buildOrderBy(pagination),
5637
+ limit,
5638
+ offset
5639
+ }
5640
+ );
5641
+ return this.applyHookFilter(this.toRateManagerListItems(result), filter?.hasHook);
5642
+ }
5643
+ async fetchRateManagerDetail(rateManagerId, options) {
5644
+ if (!rateManagerId) return null;
5645
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5646
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
5647
+ const baseVariables = {
5648
+ managerWhere: {
5649
+ rateManagerId: { _eq: normalizedId },
5650
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5651
+ },
5652
+ rateWhere: {
5653
+ rateManagerId: { _eq: normalizedId },
5654
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5655
+ },
5656
+ aggregateWhere: {
5657
+ rateManagerId: { _eq: normalizedId },
5658
+ ...normalizedRateManagerAddress ? {
5659
+ id: {
5660
+ _ilike: buildRateManagerAddressScopedIdPattern(
5661
+ normalizedId,
5662
+ normalizedRateManagerAddress
5663
+ )
5664
+ }
5665
+ } : {}
5666
+ },
5667
+ statsWhere: {
5668
+ rateManagerId: { _eq: normalizedId },
5669
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5670
+ },
5671
+ delegationWhere: {
5672
+ rateManagerId: { _eq: normalizedId },
5673
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5674
+ },
5675
+ statsLimit: options?.statsLimit ?? 20
5676
+ };
5677
+ const legacyVariables = {
5678
+ ...baseVariables,
5679
+ floorWhere: {
5680
+ rateManagerId: { _eq: normalizedId },
5681
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5682
+ }
5683
+ };
5684
+ let managerRaw;
5685
+ let scopedRates = [];
5686
+ let scopedRecentStats = [];
5687
+ let scopedDelegations = [];
5688
+ let aggregate = null;
5689
+ try {
5690
+ const result = await this.client.query({
5691
+ query: RATE_MANAGER_DETAIL_QUERY,
5692
+ variables: baseVariables
5693
+ });
5694
+ managerRaw = result.RateManager?.[0];
5695
+ if (!managerRaw) return null;
5696
+ const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
5697
+ scopedRates = (result.RateManagerRate ?? []).filter(
5698
+ (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
5699
+ );
5700
+ scopedRecentStats = (result.ManagerStats ?? []).filter((stats) => {
5701
+ const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
5702
+ return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
5703
+ });
5704
+ scopedDelegations = (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation)).filter(
5705
+ (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
5706
+ );
5707
+ aggregate = (result.ManagerAggregateStats ?? []).find(
5708
+ (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
5709
+ ) ?? result.ManagerAggregateStats?.[0] ?? null;
5710
+ } catch (error) {
5711
+ if (!isSchemaCompatibilityError(error)) {
5712
+ throw error;
5713
+ }
5714
+ const legacyResult = await this.client.query({
5715
+ query: LEGACY_RATE_MANAGER_DETAIL_QUERY,
5716
+ variables: legacyVariables
5717
+ });
5718
+ managerRaw = legacyResult.RateManager?.[0];
5719
+ if (!managerRaw) return null;
5720
+ const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
5721
+ scopedRates = (legacyResult.RateManagerRate ?? []).filter(
5722
+ (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
5723
+ );
5724
+ scopedRecentStats = (legacyResult.ManagerStats ?? []).filter((stats) => {
5725
+ const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
5726
+ return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
5727
+ });
5728
+ scopedDelegations = (legacyResult.RateManagerDelegation ?? []).filter(
5729
+ (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
5730
+ );
5731
+ aggregate = (legacyResult.ManagerAggregateStats ?? []).find(
5732
+ (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
5733
+ ) ?? legacyResult.ManagerAggregateStats?.[0] ?? null;
5734
+ }
5735
+ if (!managerRaw) return null;
5736
+ const manager = normalizeRateManagerEntity(managerRaw);
5465
5737
  return {
5466
- ...data,
5467
- responseObject: { isValid: data.responseObject }
5738
+ manager,
5739
+ rates: scopedRates,
5740
+ aggregate,
5741
+ recentStats: scopedRecentStats,
5742
+ delegations: scopedDelegations
5468
5743
  };
5469
5744
  }
5470
- return data;
5471
- }
5472
- async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs) {
5473
- const escrowAddress = requireEscrowAddress(
5474
- req.escrowAddress,
5475
- "apiGetOwnerDeposits requires escrowAddress"
5476
- );
5477
- const indexerEndpoint = defaultIndexerEndpoint(inferIndexerEnvFromBaseApiUrl(baseApiUrl));
5478
- const indexerClient = new IndexerClient(indexerEndpoint, {
5479
- apiKey,
5480
- authorizationToken: authToken
5481
- });
5482
- const service = new IndexerDepositService(indexerClient);
5483
- const deposits = await withOptionalTimeout(
5484
- service.fetchDepositsWithRelations(
5485
- {
5486
- depositor: req.ownerAddress,
5487
- escrowAddress,
5488
- escrowAddresses: req.escrowAddresses?.length ? req.escrowAddresses : void 0,
5489
- status: normalizeOwnerDepositsStatus(req.status)
5745
+ async fetchRateManagerDelegations(rateManagerId, pagination) {
5746
+ if (!rateManagerId) return [];
5747
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5748
+ const normalizedRateManagerAddress = normalizeAddress3(pagination?.rateManagerAddress);
5749
+ const variables = {
5750
+ where: {
5751
+ rateManagerId: { _eq: normalizedId },
5752
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
5490
5753
  },
5491
- void 0,
5492
- { includeIntents: false }
5493
- ),
5494
- timeoutMs,
5495
- indexerEndpoint
5496
- );
5497
- return {
5498
- success: true,
5499
- message: "ok",
5500
- responseObject: deposits.map(convertIndexerDepositToLegacyApiDeposit),
5501
- statusCode: 200
5502
- };
5503
- }
5504
- async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
5505
- const normalizedOwner = req.owner.toLowerCase();
5506
- const query = new URLSearchParams({
5507
- owner: normalizedOwner,
5508
- chainId: String(req.chainId)
5509
- });
5510
- const endpoint = `/v2/taker/tier?${query.toString()}`;
5511
- return apiFetch({
5512
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
5513
- method: "GET",
5514
- timeoutMs
5515
- });
5516
- }
5517
- async function apiGetReferralDashboard(opts) {
5518
- const endpoint = "/v2/referral";
5519
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
5520
- const response = await apiFetch({
5521
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
5522
- method: "GET",
5523
- authorizationToken,
5524
- timeoutMs: opts.timeoutMs
5525
- });
5526
- return unwrapResponseObject(response);
5527
- }
5528
- async function apiGetReferralEarnings(opts) {
5529
- const endpoint = "/v2/referral/earnings";
5530
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
5531
- const response = await apiFetch({
5532
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
5533
- method: "GET",
5534
- authorizationToken,
5535
- timeoutMs: opts.timeoutMs
5536
- });
5537
- return unwrapResponseObject(response);
5538
- }
5539
- async function apiRedeemReferralCode(req, opts) {
5540
- const endpoint = "/v2/referral/redeem";
5541
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
5542
- const response = await apiFetch({
5543
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
5544
- method: "POST",
5545
- body: { code: normalizeReferralCode(req.code) },
5546
- authorizationToken,
5547
- timeoutMs: opts.timeoutMs
5548
- });
5549
- return unwrapResponseObject(response);
5550
- }
5551
- async function apiUpdateReferralCode(req, opts) {
5552
- const endpoint = "/v2/referral/code";
5553
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
5554
- const response = await apiFetch({
5555
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
5556
- method: "PATCH",
5557
- body: { code: normalizeReferralCode(req.code) },
5558
- authorizationToken,
5559
- timeoutMs: opts.timeoutMs
5560
- });
5561
- return unwrapResponseObject(response);
5562
- }
5563
- async function apiUploadSellerCredential(processorName, payeeDetails, bundle, baseApiUrl, timeoutMs) {
5564
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
5565
- payeeDetails
5566
- )}/seller-credential`;
5567
- return apiFetch({
5568
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
5569
- method: "POST",
5570
- body: bundle,
5571
- timeoutMs
5572
- });
5573
- }
5574
- async function apiUploadGoogleOAuthSellerCredential(processorName, payeeDetails, body, baseApiUrl, opts) {
5575
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
5576
- payeeDetails
5577
- )}/seller-credential/google-oauth`;
5578
- return apiFetch({
5579
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
5580
- method: "POST",
5581
- body,
5582
- timeoutMs: opts?.timeoutMs
5583
- });
5584
- }
5585
- async function apiGetSellerCredentialStatus(processorName, payeeDetails, baseApiUrl, timeoutMs) {
5586
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
5587
- payeeDetails
5588
- )}/seller-credential/status`;
5589
- return apiFetch({
5590
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
5591
- method: "GET",
5592
- timeoutMs
5593
- });
5594
- }
5595
- async function apiVerifySellerPayment(platform, req, baseApiUrl, timeoutMs, apiKey) {
5596
- const body = {
5597
- txId: req.txId,
5598
- chainId: req.chainId,
5599
- intent: req.intent,
5600
- ...req.metadata !== void 0 ? { metadata: req.metadata } : {}
5601
- };
5602
- return apiFetch({
5603
- url: `${withApiBase(baseApiUrl)}/v2/verify/seller/${encodeURIComponent(platform)}`,
5604
- method: "POST",
5605
- body,
5606
- apiKey,
5607
- timeoutMs
5608
- });
5609
- }
5610
- async function apiGetOrderbook(params, optsOrBaseApiUrl, timeoutMs) {
5611
- const opts = typeof optsOrBaseApiUrl === "string" ? {
5612
- baseApiUrl: optsOrBaseApiUrl,
5613
- timeoutMs
5614
- } : optsOrBaseApiUrl;
5615
- const query = new URLSearchParams();
5616
- Object.entries(params).forEach(([key, value]) => {
5617
- if (value === void 0 || value === null) return;
5618
- query.set(key, String(value));
5619
- });
5620
- const response = await apiFetch({
5621
- url: `${withApiBase(opts.baseApiUrl)}/v2/orderbook?${query.toString()}`,
5622
- method: "GET",
5623
- timeoutMs: opts.timeoutMs
5624
- });
5625
- return response.responseObject;
5626
- }
5627
- async function apiGetDepositBundle(params, optsOrBaseApiUrl, timeoutMs) {
5628
- const opts = typeof optsOrBaseApiUrl === "string" ? {
5629
- baseApiUrl: optsOrBaseApiUrl,
5630
- timeoutMs
5631
- } : optsOrBaseApiUrl;
5632
- const escrowAddress = requireEscrowAddress(
5633
- params.escrowAddress,
5634
- "apiGetDepositBundle requires escrowAddress"
5635
- );
5636
- const query = new URLSearchParams({ escrowAddress });
5637
- if (params.dailySnapshotLimit !== void 0) {
5638
- query.set("dailySnapshotLimit", String(params.dailySnapshotLimit));
5754
+ order_by: this.buildDelegationOrderBy(pagination),
5755
+ limit: pagination?.limit ?? DEFAULT_LIMIT2,
5756
+ offset: pagination?.offset ?? 0
5757
+ };
5758
+ try {
5759
+ const result = await this.client.query({
5760
+ query: RATE_MANAGER_DELEGATIONS_QUERY,
5761
+ variables
5762
+ });
5763
+ return (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation));
5764
+ } catch (error) {
5765
+ if (!isSchemaCompatibilityError(error)) {
5766
+ throw error;
5767
+ }
5768
+ const legacyResult = await this.client.query({
5769
+ query: LEGACY_RATE_MANAGER_DELEGATIONS_QUERY,
5770
+ variables: {
5771
+ ...variables,
5772
+ order_by: this.buildLegacyDelegationOrderBy(pagination)
5773
+ }
5774
+ });
5775
+ return legacyResult.RateManagerDelegation ?? [];
5776
+ }
5777
+ }
5778
+ async fetchManagerDailySnapshots(rateManagerId, options) {
5779
+ if (!rateManagerId) return [];
5780
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5781
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
5782
+ try {
5783
+ const result = await this.client.query({
5784
+ query: MANAGER_DAILY_SNAPSHOTS_QUERY,
5785
+ variables: {
5786
+ where: {
5787
+ rateManagerId: { _eq: normalizedId },
5788
+ ...normalizedRateManagerAddress ? {
5789
+ id: {
5790
+ _ilike: buildRateManagerScopedIdPattern(
5791
+ normalizedId,
5792
+ normalizedRateManagerAddress
5793
+ )
5794
+ }
5795
+ } : {}
5796
+ },
5797
+ order_by: [{ dayTimestamp: "asc" }],
5798
+ limit: options?.limit ?? 365
5799
+ }
5800
+ });
5801
+ return result.ManagerDailySnapshot ?? [];
5802
+ } catch (error) {
5803
+ if (!isSchemaCompatibilityError(error)) {
5804
+ throw error;
5805
+ }
5806
+ return [];
5807
+ }
5639
5808
  }
5640
- const response = await apiFetch({
5641
- url: `${withApiBase(opts.baseApiUrl)}/v2/deposits/${params.depositId}/bundle?${query.toString()}`,
5642
- method: "GET",
5643
- timeoutMs: opts.timeoutMs
5809
+ async fetchDelegationForDeposit(depositId, options) {
5810
+ if (!depositId) return null;
5811
+ const normalizedDepositId = normalizeCompositeDepositId(depositId, options?.escrowAddress);
5812
+ try {
5813
+ const result = await this.client.query({
5814
+ query: DEPOSIT_DELEGATION_QUERY,
5815
+ variables: {
5816
+ depositId: normalizedDepositId
5817
+ }
5818
+ });
5819
+ const delegationDeposit = result.Deposit?.[0];
5820
+ if (!delegationDeposit) {
5821
+ return null;
5822
+ }
5823
+ return toDelegationEntityFromDeposit(delegationDeposit) ?? null;
5824
+ } catch (error) {
5825
+ if (!isSchemaCompatibilityError(error)) {
5826
+ throw error;
5827
+ }
5828
+ const legacyResult = await this.client.query({
5829
+ query: LEGACY_DEPOSIT_DELEGATION_QUERY,
5830
+ variables: {
5831
+ depositId: normalizedDepositId
5832
+ }
5833
+ });
5834
+ return legacyResult.RateManagerDelegation?.[0] ?? null;
5835
+ }
5836
+ }
5837
+ async fetchManualRateUpdates(rateManagerId, options) {
5838
+ if (!rateManagerId) return [];
5839
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5840
+ try {
5841
+ const result = await this.client.query({
5842
+ query: MANUAL_RATE_UPDATES_QUERY,
5843
+ variables: {
5844
+ where: {
5845
+ rateManagerId: { _eq: normalizedId }
5846
+ },
5847
+ order_by: [{ id: "desc" }],
5848
+ limit: options?.limit ?? 100
5849
+ }
5850
+ });
5851
+ return (result.RateManagerV1_RateManagerRateUpdated ?? []).map((e) => ({
5852
+ ...e,
5853
+ currency: e.currency ?? e.currencyCode ?? "",
5854
+ minRate: e.minRate ?? e.rate ?? "0"
5855
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5856
+ } catch (error) {
5857
+ if (!isSchemaCompatibilityError(error)) {
5858
+ throw error;
5859
+ }
5860
+ return [];
5861
+ }
5862
+ }
5863
+ async fetchOracleConfigUpdates(rateManagerId, options) {
5864
+ if (!rateManagerId) return [];
5865
+ const normalizedId = normalizeRateManagerId2(rateManagerId);
5866
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
5867
+ const limit = options?.limit ?? 100;
5868
+ try {
5869
+ const depositScopes = await this.fetchHistoricalRateManagerDepositScopes(
5870
+ normalizedId,
5871
+ normalizedRateManagerAddress || void 0
5872
+ );
5873
+ if (!depositScopes.length) {
5874
+ return [];
5875
+ }
5876
+ const scopedKeys = new Set(depositScopes.map((scope) => buildDepositScopeKey(scope)));
5877
+ const result = await this.client.query({
5878
+ query: ORACLE_CONFIG_UPDATES_QUERY,
5879
+ variables: {
5880
+ where: {
5881
+ _or: depositScopes.map((scope) => ({
5882
+ _and: [
5883
+ { depositId: { _eq: scope.depositIdOnContract } },
5884
+ { escrow: { _eq: scope.escrow } }
5885
+ ]
5886
+ }))
5887
+ },
5888
+ order_by: [{ id: "desc" }],
5889
+ limit
5890
+ }
5891
+ });
5892
+ return (result.EscrowV2_DepositOracleRateConfigSet ?? []).filter((event) => {
5893
+ const escrow = normalizeAddress3(event.escrow);
5894
+ const depositIdOnContract = event.depositIdOnContract ?? event.depositId?.toString?.() ?? "";
5895
+ if (!escrow || !depositIdOnContract) return false;
5896
+ return scopedKeys.has(
5897
+ buildDepositScopeKey({
5898
+ escrow,
5899
+ depositIdOnContract
5900
+ })
5901
+ );
5902
+ }).map((e) => ({
5903
+ ...e,
5904
+ rateManagerId: normalizedId,
5905
+ escrow: normalizeAddress3(e.escrow) || void 0,
5906
+ currency: e.currency ?? e.currencyCode ?? "",
5907
+ depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
5908
+ adapter: e.adapter ?? "",
5909
+ spreadBps: e.spreadBps ?? 0
5910
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5911
+ } catch (error) {
5912
+ if (isSchemaCompatibilityError(error)) ; else {
5913
+ throw error;
5914
+ }
5915
+ const legacyResult = await this.client.query({
5916
+ query: LEGACY_ORACLE_CONFIG_UPDATES_QUERY,
5917
+ variables: {
5918
+ where: {
5919
+ rateManagerId: { _eq: normalizedId }
5920
+ },
5921
+ order_by: [{ id: "desc" }],
5922
+ limit
5923
+ }
5924
+ });
5925
+ return (legacyResult.RateManagerV1_DepositorFloorSet ?? []).map((e) => ({
5926
+ ...e,
5927
+ currency: e.currency ?? e.currencyCode ?? "",
5928
+ depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
5929
+ adapter: e.adapter ?? e.oracleAdapter ?? "",
5930
+ spreadBps: e.spreadBps ?? e.floorSpreadBps ?? 0
5931
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
5932
+ }
5933
+ }
5934
+ };
5935
+
5936
+ // src/indexer/intentVerification.ts
5937
+ async function fetchFulfillmentAndPayment(client, intentHash) {
5938
+ return client.query({
5939
+ query: FULFILLMENT_AND_PAYMENT_QUERY,
5940
+ variables: { intentHash }
5644
5941
  });
5645
- return response.responseObject;
5646
5942
  }
5647
5943
 
5648
5944
  // src/sellerCredentials.ts
@@ -5847,9 +6143,7 @@ function isObjectRecord(value) {
5847
6143
  return true;
5848
6144
  }
5849
6145
  function normalizeTelegramUsername(value) {
5850
- if (typeof value !== "string") {
5851
- return value === null ? null : null;
5852
- }
6146
+ if (typeof value !== "string") return null;
5853
6147
  const normalized = value.trim();
5854
6148
  return normalized.length > 0 ? normalized : null;
5855
6149
  }
@@ -6143,7 +6437,7 @@ var Zkp2pClient = class {
6143
6437
  () => ({
6144
6438
  address: this.rateManagerControllerAddress,
6145
6439
  abi: this.rateManagerControllerAbi,
6146
- label: "Rate manager controller (staging only)"
6440
+ label: "Rate manager controller"
6147
6441
  }),
6148
6442
  "setDepositRateManager",
6149
6443
  (params) => {
@@ -6157,7 +6451,7 @@ var Zkp2pClient = class {
6157
6451
  () => ({
6158
6452
  address: this.rateManagerControllerAddress,
6159
6453
  abi: this.rateManagerControllerAbi,
6160
- label: "Rate manager controller (staging only)"
6454
+ label: "Rate manager controller"
6161
6455
  }),
6162
6456
  "clearDepositRateManager",
6163
6457
  (params) => {
@@ -6243,7 +6537,7 @@ var Zkp2pClient = class {
6243
6537
  () => ({
6244
6538
  address: this.rateManagerRegistryAddress,
6245
6539
  abi: this.rateManagerRegistryAbi,
6246
- label: "Rate manager registry (staging only)"
6540
+ label: "Rate manager registry"
6247
6541
  }),
6248
6542
  "setFee",
6249
6543
  (params) => {
@@ -6728,6 +7022,10 @@ var Zkp2pClient = class {
6728
7022
  const prepared = await this.prepareFulfillIntent(params);
6729
7023
  const txHash = await this.executePreparedTransaction(prepared, params.txOverrides);
6730
7024
  params?.callbacks?.onTxSent?.(txHash);
7025
+ if (params?.callbacks?.onTxMined) {
7026
+ await this.publicClient.waitForTransactionReceipt({ hash: txHash });
7027
+ params.callbacks.onTxMined(txHash);
7028
+ }
6731
7029
  return txHash;
6732
7030
  },
6733
7031
  {
@@ -6746,7 +7044,7 @@ var Zkp2pClient = class {
6746
7044
  this.walletClient = opts.walletClient;
6747
7045
  this.chainId = opts.chainId;
6748
7046
  this.runtimeEnv = opts.runtimeEnv ?? "production";
6749
- const inferredRpc = this.walletClient?.chain?.rpcUrls?.default?.http?.[0];
7047
+ const inferredRpc = this.walletClient.chain?.rpcUrls?.default?.http?.[0];
6750
7048
  const defaultRpcUrls = {
6751
7049
  [base.id]: "https://mainnet.base.org",
6752
7050
  [hardhat.id]: "http://127.0.0.1:8545"
@@ -6759,7 +7057,7 @@ var Zkp2pClient = class {
6759
7057
  const selectedChain = chainMap[this.chainId];
6760
7058
  this.publicClient = createPublicClient({
6761
7059
  chain: selectedChain,
6762
- transport: http(rpc, { batch: false })
7060
+ transport: opts.rpcTransport ?? http(rpc, { batch: false })
6763
7061
  });
6764
7062
  const { addresses, abis } = getContracts(this.chainId, this.runtimeEnv);
6765
7063
  const toAddress = (value) => this.isValidHexAddress(value) ? value : void 0;
@@ -6777,12 +7075,10 @@ var Zkp2pClient = class {
6777
7075
  };
6778
7076
  this.escrowV2Address = toAddress(addresses.escrowV2 ?? addresses.escrow);
6779
7077
  this.escrowV2Abi = abis.escrowV2 ?? abis.escrow;
6780
- this.orchestratorV2Address = toAddress(
6781
- addresses.orchestratorV2 ?? addresses.orchestrator
6782
- );
7078
+ this.orchestratorV2Address = toAddress(addresses.orchestratorV2 ?? addresses.orchestrator);
6783
7079
  this.orchestratorV2Abi = abis.orchestratorV2 ?? abis.orchestrator;
6784
- const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter(Boolean);
6785
- const configuredOrchestratorAddresses = (addresses.orchestratorAddresses ?? []).map((value) => toAddress(value)).filter(Boolean);
7080
+ const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
7081
+ const configuredOrchestratorAddresses = (addresses.orchestratorAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
6786
7082
  this.escrowAddresses = uniqAddresses([
6787
7083
  this.escrowV2Address ?? toAddress(addresses.escrow),
6788
7084
  ...configuredEscrowAddresses
@@ -6848,8 +7144,7 @@ var Zkp2pClient = class {
6848
7144
  orchestratorV2Abi: this.orchestratorV2Abi,
6849
7145
  orchestratorAddresses: this.orchestratorAddresses
6850
7146
  });
6851
- const maybeUsdc = addresses.usdc;
6852
- if (maybeUsdc) this._usdcAddress = maybeUsdc;
7147
+ if (addresses.usdc) this._usdcAddress = addresses.usdc;
6853
7148
  const runtimeToIndexerEnv = {
6854
7149
  production: "PRODUCTION",
6855
7150
  preproduction: "PREPRODUCTION",
@@ -6925,6 +7220,15 @@ var Zkp2pClient = class {
6925
7220
  getPvIntent: (intentHash) => this.getPvIntent(intentHash)
6926
7221
  }
6927
7222
  });
7223
+ this._referralOps = new ReferralAccountOperations({
7224
+ getWalletClient: () => this.walletClient,
7225
+ getChainId: () => this.chainId,
7226
+ getRuntimeEnv: () => this.runtimeEnv,
7227
+ getBaseApiUrl: () => this.baseApiUrl,
7228
+ getApiTimeoutMs: () => this.apiTimeoutMs,
7229
+ getAuthorizationToken: () => this.authorizationToken,
7230
+ getAuthorizationTokenProvider: () => this.getAuthorizationToken
7231
+ });
6928
7232
  }
6929
7233
  isValidHexAddress(addr) {
6930
7234
  return isValidHexAddress(addr);
@@ -6962,22 +7266,6 @@ var Zkp2pClient = class {
6962
7266
  `attestationServiceUrl is required when baseApiUrl is not a supported zkp2p API host: ${baseApiUrl}`
6963
7267
  );
6964
7268
  }
6965
- async resolveAuthorizationToken(opts) {
6966
- if (opts?.authorizationToken !== void 0) {
6967
- return opts.authorizationToken;
6968
- }
6969
- const provider = opts?.getAuthorizationToken ?? this.getAuthorizationToken;
6970
- if (provider) {
6971
- return await provider() ?? void 0;
6972
- }
6973
- return this.authorizationToken;
6974
- }
6975
- normalizeOracleRateConfig(config) {
6976
- return normalizeOracleRateConfig(config);
6977
- }
6978
- escrowCurrencyHasOracleConfig(abi) {
6979
- return escrowCurrencyHasOracleConfig(abi);
6980
- }
6981
7269
  /**
6982
7270
  * Normalizes currency tuples by appending an empty `oracleRateConfig` when the ABI
6983
7271
  * requires it and the caller hasn't provided one.
@@ -6990,21 +7278,9 @@ var Zkp2pClient = class {
6990
7278
  escrowAddress: params?.escrowAddress
6991
7279
  });
6992
7280
  }
6993
- parseManagerFeeFromRead(result) {
6994
- return parseManagerFeeFromRead(result);
6995
- }
6996
- getAbiFunction(abi, ...names) {
6997
- return getAbiFunction(abi, ...names);
6998
- }
6999
7281
  resolveAbiFunctionName(abi, names) {
7000
7282
  return resolveAbiFunctionName(abi, names);
7001
7283
  }
7002
- abiTupleHasComponent(abi, functionName, componentName) {
7003
- return abiTupleHasComponent(abi, functionName, componentName);
7004
- }
7005
- abiFunctionHasInput(abi, functionName, inputName) {
7006
- return abiFunctionHasInput(abi, functionName, inputName);
7007
- }
7008
7284
  resolveEscrowAddressOrThrow(escrowAddress, depositId, _methodName) {
7009
7285
  const resolved = escrowAddress ?? this.parseEscrowAddressFromCompositeDepositId(depositId);
7010
7286
  if (resolved) return resolved;
@@ -7130,7 +7406,7 @@ var Zkp2pClient = class {
7130
7406
  async lookupIntentEscrowOnchain(intentHash) {
7131
7407
  try {
7132
7408
  const view = await this.getPvIntent(intentHash);
7133
- return this.normalizeAddress(view?.intent?.escrow);
7409
+ return this.normalizeAddress(view.intent.escrow);
7134
7410
  } catch {
7135
7411
  return void 0;
7136
7412
  }
@@ -7195,6 +7471,15 @@ var Zkp2pClient = class {
7195
7471
  if (fallback) return fallback;
7196
7472
  throw new Error("Orchestrator not available");
7197
7473
  }
7474
+ /**
7475
+ * Spread helper for viem requests.
7476
+ * justified: TxOverrides mixes legacy gasPrice with EIP-1559 fee fields, which
7477
+ * viem's discriminated request unions reject; keep the suppression in one place.
7478
+ */
7479
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7480
+ applyTxOverrides(overrides) {
7481
+ return overrides;
7482
+ }
7198
7483
  /**
7199
7484
  * Simulate a contract call (validation only) and send with ERC-8021 attribution.
7200
7485
  * Referrer codes are stripped from overrides for simulation and appended to calldata.
@@ -7207,7 +7492,7 @@ var Zkp2pClient = class {
7207
7492
  functionName: opts.functionName,
7208
7493
  args: opts.args ?? [],
7209
7494
  account: this.walletClient.account,
7210
- ...txOverrides
7495
+ ...this.applyTxOverrides(txOverrides)
7211
7496
  });
7212
7497
  return sendTransactionWithAttribution(
7213
7498
  this.walletClient,
@@ -7234,7 +7519,7 @@ var Zkp2pClient = class {
7234
7519
  functionName: prepared.functionName,
7235
7520
  args: prepared.args,
7236
7521
  account: this.walletClient.account,
7237
- ...overrides
7522
+ ...this.applyTxOverrides(overrides)
7238
7523
  });
7239
7524
  return this.walletClient.sendTransaction({
7240
7525
  to: prepared.to,
@@ -7242,7 +7527,7 @@ var Zkp2pClient = class {
7242
7527
  value: prepared.value,
7243
7528
  account: this.walletClient.account,
7244
7529
  chain: this.walletClient.chain,
7245
- ...overrides
7530
+ ...this.applyTxOverrides(overrides)
7246
7531
  });
7247
7532
  }
7248
7533
  prepareEscrowTransaction(opts) {
@@ -7848,20 +8133,18 @@ var Zkp2pClient = class {
7848
8133
  if (params.processorNames.length !== payeeData.length) {
7849
8134
  throw new Error("processorNames and payeeData length mismatch");
7850
8135
  }
7851
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
8136
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
7852
8137
  const depositDetails = params.processorNames.map(
7853
8138
  (processorName, index) => toPostDepositDetailsRequest(processorName, payeeData[index], index)
7854
8139
  );
7855
8140
  const apiResponses = await Promise.all(
7856
8141
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
7857
8142
  );
7858
- if (!apiResponses.every((r) => r?.success)) {
7859
- const failed = apiResponses.find((r) => !r?.success);
8143
+ if (!apiResponses.every((r) => r.success)) {
8144
+ const failed = apiResponses.find((r) => !r.success);
7860
8145
  throw new Error(failed?.message || "Failed to register payee details");
7861
8146
  }
7862
- const hashedOnchainIds = apiResponses.map(
7863
- (r) => r.responseObject?.hashedOnchainId
7864
- );
8147
+ const hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
7865
8148
  return { depositDetails, hashedOnchainIds };
7866
8149
  }
7867
8150
  /**
@@ -7985,17 +8268,15 @@ var Zkp2pClient = class {
7985
8268
  }
7986
8269
  hashedOnchainIds = payeeDetailsHashes;
7987
8270
  } else {
7988
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
8271
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
7989
8272
  const apiResponses = await Promise.all(
7990
8273
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
7991
8274
  );
7992
- if (!apiResponses.every((r) => r?.success)) {
7993
- const failed = apiResponses.find((r) => !r?.success);
8275
+ if (!apiResponses.every((r) => r.success)) {
8276
+ const failed = apiResponses.find((r) => !r.success);
7994
8277
  throw new Error(failed?.message || "Failed to create deposit details");
7995
8278
  }
7996
- hashedOnchainIds = apiResponses.map(
7997
- (r) => r.responseObject?.hashedOnchainId
7998
- );
8279
+ hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
7999
8280
  }
8000
8281
  paymentMethodData = hashedOnchainIds.map((hid) => ({
8001
8282
  intentGatingService,
@@ -8017,10 +8298,10 @@ var Zkp2pClient = class {
8017
8298
  }
8018
8299
  });
8019
8300
  const { mapConversionRatesToOnchainMinRate: mapConversionRatesToOnchainMinRate2 } = await import('./currency-MARF3D2J.mjs');
8020
- const normalized = params.conversionRates.map(
8021
- (group) => group.map((r) => ({ currency: r.currency, conversionRate: r.conversionRate }))
8301
+ currencies = mapConversionRatesToOnchainMinRate2(
8302
+ params.conversionRates,
8303
+ paymentMethods.length
8022
8304
  );
8023
- currencies = mapConversionRatesToOnchainMinRate2(normalized, paymentMethods.length);
8024
8305
  }
8025
8306
  const escrowContext = this.resolveEscrowContext({
8026
8307
  escrowAddress: params.escrowAddress
@@ -8112,9 +8393,6 @@ var Zkp2pClient = class {
8112
8393
  async prepareFulfillIntent(params) {
8113
8394
  return this._intentOps.prepareFulfillIntent(params);
8114
8395
  }
8115
- defaultAttestationService() {
8116
- return this._intentOps.defaultAttestationService();
8117
- }
8118
8396
  // ───────────────────────────────────────────────────────────────────────────
8119
8397
  // SUPPORTING: QUOTES API
8120
8398
  // (Used by frontends to find available liquidity)
@@ -8162,7 +8440,7 @@ var Zkp2pClient = class {
8162
8440
  */
8163
8441
  async getQuote(req, opts) {
8164
8442
  const referrerFeeConfig = assertValidReferrerFeeConfig(req.referrerFeeConfig, "getQuote");
8165
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
8443
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
8166
8444
  /\/$/,
8167
8445
  ""
8168
8446
  );
@@ -8177,9 +8455,8 @@ var Zkp2pClient = class {
8177
8455
  const quote = await apiGetQuote(reqWithEscrow, baseApiUrl, timeoutMs, this.apiKey);
8178
8456
  const quotes = quote?.responseObject?.quotes ?? [];
8179
8457
  for (const q of quotes) {
8180
- const maker = q?.maker;
8181
- const payeeData = normalizeQuotePayeeData(maker);
8182
- if (payeeData && typeof q === "object") {
8458
+ const payeeData = normalizeQuotePayeeData(q.maker);
8459
+ if (payeeData) {
8183
8460
  q.payeeData = payeeData;
8184
8461
  }
8185
8462
  }
@@ -8200,7 +8477,7 @@ var Zkp2pClient = class {
8200
8477
  req.referrerFeeConfig,
8201
8478
  "getQuotesBestByPlatform"
8202
8479
  );
8203
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
8480
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
8204
8481
  /\/$/,
8205
8482
  ""
8206
8483
  );
@@ -8249,7 +8526,7 @@ var Zkp2pClient = class {
8249
8526
  * @returns Taker tier response
8250
8527
  */
8251
8528
  async getTakerTier(req, opts) {
8252
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
8529
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
8253
8530
  /\/$/,
8254
8531
  ""
8255
8532
  );
@@ -8257,49 +8534,62 @@ var Zkp2pClient = class {
8257
8534
  return apiGetTakerTier(req, baseApiUrl, timeoutMs);
8258
8535
  }
8259
8536
  /**
8260
- * Fetch the authenticated user's referral dashboard, including their generated
8261
- * code, reward rates, referee counts, and lifetime referral fees.
8537
+ * Fetch a referral dashboard. Pass `address` for a public wallet-keyed read;
8538
+ * omit it to use the authenticated caller mode.
8262
8539
  */
8263
8540
  async getReferralDashboard(opts) {
8264
- const baseApiUrl = this.stripTrailingSlash(
8265
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
8266
- );
8267
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8268
- const authorizationToken = await this.resolveAuthorizationToken(opts);
8269
- return apiGetReferralDashboard({ baseApiUrl, timeoutMs, authorizationToken });
8541
+ return this._referralOps.getReferralDashboard(opts);
8270
8542
  }
8271
8543
  /**
8272
- * Fetch the authenticated user's referral earnings totals.
8544
+ * Fetch referral earnings. Pass `address` for a public wallet-keyed read;
8545
+ * omit it to use the authenticated caller mode.
8273
8546
  */
8274
8547
  async getReferralEarnings(opts) {
8275
- const baseApiUrl = this.stripTrailingSlash(
8276
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
8277
- );
8278
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8279
- const authorizationToken = await this.resolveAuthorizationToken(opts);
8280
- return apiGetReferralEarnings({ baseApiUrl, timeoutMs, authorizationToken });
8548
+ return this._referralOps.getReferralEarnings(opts);
8549
+ }
8550
+ /**
8551
+ * Publicly look up a referral code's owner wallet and active status.
8552
+ */
8553
+ async lookupReferralCode(code, opts) {
8554
+ return this._referralOps.lookupReferralCode(code, opts);
8281
8555
  }
8282
8556
  /**
8283
- * Apply another user's referral code to the authenticated account.
8557
+ * Create or fetch the authenticated caller's referral code with bearer auth.
8558
+ */
8559
+ async createReferralCode(opts) {
8560
+ return this._referralOps.createReferralCode(opts);
8561
+ }
8562
+ /**
8563
+ * Create or fetch the wallet's referral code with EIP-712 signature auth.
8564
+ */
8565
+ async createReferralCodeWithSignature(opts) {
8566
+ return this._referralOps.createReferralCodeWithSignature(opts);
8567
+ }
8568
+ /**
8569
+ * Apply another user's referral code with bearer auth.
8284
8570
  */
8285
8571
  async redeemReferralCode(code, opts) {
8286
- const baseApiUrl = this.stripTrailingSlash(
8287
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
8288
- );
8289
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8290
- const authorizationToken = await this.resolveAuthorizationToken(opts);
8291
- return apiRedeemReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
8572
+ return this._referralOps.redeemReferralCode(code, opts);
8292
8573
  }
8293
8574
  /**
8294
- * Customize the authenticated user's own referral code.
8575
+ * Apply another user's referral code with EIP-712 signature auth. If
8576
+ * `referrerWalletAddress` is omitted, the SDK looks up the code first and signs
8577
+ * the current owner wallet into the redeem payload.
8578
+ */
8579
+ async redeemReferralCodeWithSignature(code, opts) {
8580
+ return this._referralOps.redeemReferralCodeWithSignature(code, opts);
8581
+ }
8582
+ /**
8583
+ * Customize the authenticated caller's referral code with bearer auth.
8295
8584
  */
8296
8585
  async updateReferralCode(code, opts) {
8297
- const baseApiUrl = this.stripTrailingSlash(
8298
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
8299
- );
8300
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
8301
- const authorizationToken = await this.resolveAuthorizationToken(opts);
8302
- return apiUpdateReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
8586
+ return this._referralOps.updateReferralCode(code, opts);
8587
+ }
8588
+ /**
8589
+ * Customize the wallet's referral code with EIP-712 signature auth.
8590
+ */
8591
+ async updateReferralCodeWithSignature(code, opts) {
8592
+ return this._referralOps.updateReferralCodeWithSignature(code, opts);
8303
8593
  }
8304
8594
  /**
8305
8595
  * The signed `credentialValidatedAt` field is an upload-time freshness witness minted by
@@ -8321,44 +8611,14 @@ var Zkp2pClient = class {
8321
8611
  const attestationServiceUrl = this.stripTrailingSlash(
8322
8612
  opts?.attestationServiceUrl ?? this.defaultAttestationServiceForBaseApiUrl(baseApiUrl)
8323
8613
  );
8324
- const createBundle = (uploadPayload) => {
8325
- const requestOptions = opts?.attestationServiceFallbackUrls ? { fallbackUrls: opts.attestationServiceFallbackUrls } : void 0;
8326
- if (opts?.attestationRuntime && requestOptions) {
8327
- return apiCreateSellerCredentialBundle(
8328
- uploadPayload,
8329
- attestationServiceUrl,
8330
- params.platform,
8331
- timeoutMs,
8332
- opts.attestationRuntime,
8333
- requestOptions
8334
- );
8335
- }
8336
- if (opts?.attestationRuntime) {
8337
- return apiCreateSellerCredentialBundle(
8338
- uploadPayload,
8339
- attestationServiceUrl,
8340
- params.platform,
8341
- timeoutMs,
8342
- opts.attestationRuntime
8343
- );
8344
- }
8345
- if (requestOptions) {
8346
- return apiCreateSellerCredentialBundle(
8347
- uploadPayload,
8348
- attestationServiceUrl,
8349
- params.platform,
8350
- timeoutMs,
8351
- void 0,
8352
- requestOptions
8353
- );
8354
- }
8355
- return apiCreateSellerCredentialBundle(
8356
- uploadPayload,
8357
- attestationServiceUrl,
8358
- params.platform,
8359
- timeoutMs
8360
- );
8361
- };
8614
+ const createBundle = (uploadPayload) => apiCreateSellerCredentialBundle(
8615
+ uploadPayload,
8616
+ attestationServiceUrl,
8617
+ params.platform,
8618
+ timeoutMs,
8619
+ opts?.attestationRuntime,
8620
+ opts?.attestationServiceFallbackUrls ? { fallbackUrls: opts.attestationServiceFallbackUrls } : void 0
8621
+ );
8362
8622
  if (params.platform === "wise") {
8363
8623
  const bundleResponse2 = await createBundle({
8364
8624
  sessionMaterial: params.sessionMaterial
@@ -8504,19 +8764,6 @@ var Zkp2pClient = class {
8504
8764
  protocolViewerFunctionInputCount(functionName) {
8505
8765
  return this._pvReader.protocolViewerFunctionInputCount(functionName);
8506
8766
  }
8507
- /**
8508
- * Returns the input count for a function on a specific PV entry's ABI.
8509
- * Used to branch between 1-input (V1) and 2-input (V2) PV call signatures.
8510
- */
8511
- pvEntryFunctionInputCount(entry, functionName) {
8512
- return this._pvReader.pvEntryFunctionInputCount(entry, functionName);
8513
- }
8514
- isZeroAddressValue(value) {
8515
- return this._pvReader.isZeroAddressValue(value);
8516
- }
8517
- toBigIntOrZero(value, fieldName = "numeric field") {
8518
- return this._pvReader.toBigIntOrZero(value, fieldName);
8519
- }
8520
8767
  buildProtocolViewerContexts(options) {
8521
8768
  return this._pvReader.buildProtocolViewerContexts(options);
8522
8769
  }
@@ -8529,9 +8776,6 @@ var Zkp2pClient = class {
8529
8776
  buildDepositViewFromEscrowDeposit(rawDeposit, depositId) {
8530
8777
  return this._pvReader.buildDepositViewFromEscrowDeposit(rawDeposit, depositId);
8531
8778
  }
8532
- convertIndexerDepositToPvView(deposit) {
8533
- return this._pvReader.convertIndexerDepositToPvView(deposit);
8534
- }
8535
8779
  async getPvAccountDepositsFromIndexer(owner) {
8536
8780
  return this._pvReader.getPvAccountDepositsFromIndexer(owner);
8537
8781
  }
@@ -8687,6 +8931,6 @@ var createPeerExtensionSdk = (options = {}) => ({
8687
8931
  });
8688
8932
  var peerExtensionSdk = createPeerExtensionSdk();
8689
8933
 
8690
- export { BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, Zkp2pClient as OfframpClient, PAYMENT_PLATFORMS, PEER_EXTENSION_CHROME_URL, PLATFORM_METADATA, PYTH_CONTRACT_BASE, PYTH_ORACLE_ADAPTER, PYTH_ORACLE_FEEDS, SPREAD_ORACLE_FEEDS, SUPPORTED_CHAIN_IDS, TOKEN_METADATA, ZKP2P_ANDROID_REFERRER, ZKP2P_IOS_REFERRER, Zkp2pClient, apiCreateSellerCredentialBundle, apiGetDepositBundle, apiGetOrderbook, apiGetOwnerDeposits, apiGetPayeeDetails, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiGetTakerTier, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, compareEventCursorIdsByRecency, convertDepositsForLiquidity, convertIndexerDepositToEscrowView, convertIndexerIntentsToEscrowViews, createCompositeDepositId, createEncryptedBuyerTeeSessionMaterial, createPeerExtensionSdk, defaultIndexerEndpoint, encodePythAdapterConfig, encodeSpreadOracleAdapterConfig, encodeWithAttribution, fetchFulfillmentAndPayment as fetchIndexerFulfillmentAndPayment, getAttributionDataSuffix, getPeerExtensionState, getSpreadOracleConfig, isPeerExtensionAvailable, isValidReferralCode, isValidReferrerFeeBps, isValidReferrerFeeRecipient, logger, normalizeReferralCode, openPeerExtensionInstallPage, parseReferrerFeeConfig, peerExtensionSdk, referrerFeeConfigToPreciseUnits, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
8934
+ export { BASE_BUILDER_CODE, CHAINLINK_ORACLE_ADAPTER, CHAINLINK_ORACLE_FEEDS, ContractRouter, DEFAULT_ORACLE_MAX_STALENESS_SECONDS, IndexerClient, IndexerDepositService, IndexerRateManagerService, Zkp2pClient as OfframpClient, PAYMENT_PLATFORMS, PEER_EXTENSION_CHROME_URL, PLATFORM_METADATA, PYTH_CONTRACT_BASE, PYTH_ORACLE_ADAPTER, PYTH_ORACLE_FEEDS, REFERRAL_SIGNATURE_DOMAIN, REFERRAL_SIGNATURE_TYPES, SPREAD_ORACLE_FEEDS, SUPPORTED_CHAIN_IDS, TOKEN_METADATA, ZKP2P_ANDROID_REFERRER, ZKP2P_IOS_REFERRER, Zkp2pClient, apiCreateReferralCode, apiCreateSellerCredentialBundle, apiGetDepositBundle, apiGetOrderbook, apiGetOwnerDeposits, apiGetPayeeDetails, apiGetQuotesBestByPlatform, apiGetReferralDashboard, apiGetReferralEarnings, apiGetTakerTier, apiLookupReferralCode, apiPostDepositDetails, apiRedeemReferralCode, apiRequestIdentityAttestation, apiUpdateReferralCode, apiUploadGoogleOAuthSellerCredential, apiUploadSellerCredentialBundle, apiValidatePayeeDetails, apiVerifyBuyerTeePayment, appendAttributionToCalldata, assertValidReferrerFeeConfig, compareEventCursorIdsByRecency, convertDepositsForLiquidity, convertIndexerDepositToEscrowView, convertIndexerIntentsToEscrowViews, createCompositeDepositId, createEncryptedBuyerTeeSessionMaterial, createPeerExtensionSdk, defaultIndexerEndpoint, encodePythAdapterConfig, encodeSpreadOracleAdapterConfig, encodeWithAttribution, fetchFulfillmentAndPayment as fetchIndexerFulfillmentAndPayment, getAttributionDataSuffix, getPeerExtensionState, getSpreadOracleConfig, isPeerExtensionAvailable, isValidReferralCode, isValidReferrerFeeBps, isValidReferrerFeeRecipient, logger, normalizeReferralCode, openPeerExtensionInstallPage, parseReferrerFeeConfig, peerExtensionSdk, referrerFeeConfigToPreciseUnits, sendTransactionWithAttribution, setLogLevel, validateOracleFeedsOnChain };
8691
8935
  //# sourceMappingURL=index.mjs.map
8692
8936
  //# sourceMappingURL=index.mjs.map