@zkp2p/sdk 0.6.3 → 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.cjs CHANGED
@@ -43081,6 +43081,44 @@ function resolvePlatformAttestationConfig(platformName) {
43081
43081
  return config;
43082
43082
  }
43083
43083
 
43084
+ // src/utils/logger.ts
43085
+ var currentLevel = "info";
43086
+ function setLogLevel(level) {
43087
+ currentLevel = level;
43088
+ }
43089
+ function shouldLog(level) {
43090
+ switch (currentLevel) {
43091
+ case "debug":
43092
+ return true;
43093
+ case "info":
43094
+ return level !== "debug";
43095
+ case "error":
43096
+ return level === "error";
43097
+ default:
43098
+ return true;
43099
+ }
43100
+ }
43101
+ var logger = {
43102
+ debug: (...args) => {
43103
+ if (shouldLog("debug")) {
43104
+ console.log("[DEBUG]", ...args);
43105
+ }
43106
+ },
43107
+ info: (...args) => {
43108
+ if (shouldLog("info")) {
43109
+ console.log("[INFO]", ...args);
43110
+ }
43111
+ },
43112
+ warn: (...args) => {
43113
+ if (shouldLog("info")) {
43114
+ console.warn("[WARN]", ...args);
43115
+ }
43116
+ },
43117
+ error: (...args) => {
43118
+ console.error("[ERROR]", ...args);
43119
+ }
43120
+ };
43121
+
43084
43122
  // src/client/IntentOperations.ts
43085
43123
  var INTENT_MIN_AT_SIGNAL_ABI = [
43086
43124
  {
@@ -43594,16 +43632,24 @@ var IntentOperations = class {
43594
43632
  async readIntentMinAtSignal(intentHash, orchestratorAddress) {
43595
43633
  const address = orchestratorAddress ?? this.config.getOrchestratorV2Address();
43596
43634
  if (!address) return void 0;
43635
+ const read = async () => this.config.getPublicClient().readContract({
43636
+ address,
43637
+ abi: INTENT_MIN_AT_SIGNAL_ABI,
43638
+ functionName: "getIntentMinAtSignal",
43639
+ args: [intentHash]
43640
+ });
43597
43641
  try {
43598
- const value = await this.config.getPublicClient().readContract({
43599
- address,
43600
- abi: INTENT_MIN_AT_SIGNAL_ABI,
43601
- functionName: "getIntentMinAtSignal",
43602
- args: [intentHash]
43603
- });
43604
- return value.toString();
43605
- } catch {
43606
- return void 0;
43642
+ return (await read()).toString();
43643
+ } catch (error) {
43644
+ logger.warn(
43645
+ `[sdk] getIntentMinAtSignal read failed for ${intentHash}; retrying once`,
43646
+ error instanceof Error ? error.message : error
43647
+ );
43648
+ try {
43649
+ return (await read()).toString();
43650
+ } catch {
43651
+ return void 0;
43652
+ }
43607
43653
  }
43608
43654
  }
43609
43655
  };
@@ -44307,478 +44353,165 @@ var ProtocolViewerReader = class {
44307
44353
  }
44308
44354
  };
44309
44355
 
44310
- // src/client/VaultOperations.ts
44311
- var VaultOperations = class {
44312
- constructor(config) {
44313
- this.config = config;
44356
+ // src/adapters/api.ts
44357
+ init_errors();
44358
+
44359
+ // src/indexer/client.ts
44360
+ var IndexerHttpError = class extends Error {
44361
+ constructor(status, statusText, options) {
44362
+ super(`Indexer request failed: ${status} ${statusText}`);
44363
+ this.name = "IndexerHttpError";
44364
+ this.status = status;
44365
+ this.retryAfterSeconds = options?.retryAfterSeconds;
44314
44366
  }
44315
- supportsInlineOracleRateConfig(params) {
44316
- const escrowContext = this.config.host.resolveEscrowContext({
44317
- escrowAddress: params?.escrowAddress
44318
- });
44319
- return escrowCurrencyHasOracleConfig(escrowContext.abi);
44367
+ };
44368
+ function parseRetryAfterSeconds(rawHeader) {
44369
+ if (!rawHeader) return void 0;
44370
+ const parsedSeconds = Number(rawHeader);
44371
+ if (Number.isFinite(parsedSeconds) && parsedSeconds >= 0) {
44372
+ return Math.ceil(parsedSeconds);
44320
44373
  }
44321
- resolveRateManagerRegistryContract(registryAddress) {
44322
- const abi = this.config.getRateManagerRegistryAbi();
44323
- if (!abi) {
44324
- throw this.buildRateManagerUnavailableError("Rate manager registry not available");
44325
- }
44326
- if (registryAddress) {
44327
- return {
44328
- address: registryAddress,
44329
- abi
44330
- };
44331
- }
44332
- const address = this.config.getRateManagerRegistryAddress();
44333
- if (!address) {
44334
- throw this.buildRateManagerUnavailableError("Rate manager registry not available");
44374
+ const parsedDateMs = Date.parse(rawHeader);
44375
+ if (!Number.isFinite(parsedDateMs)) return void 0;
44376
+ const secondsUntilRetry = Math.ceil((parsedDateMs - Date.now()) / 1e3);
44377
+ return Math.max(0, secondsUntilRetry);
44378
+ }
44379
+ function createAbortError() {
44380
+ const error = new Error("The operation was aborted");
44381
+ error.name = "AbortError";
44382
+ return error;
44383
+ }
44384
+ function delay(ms, signal) {
44385
+ if (ms <= 0) {
44386
+ return Promise.resolve();
44387
+ }
44388
+ return new Promise((resolve, reject) => {
44389
+ if (signal?.aborted) {
44390
+ reject(createAbortError());
44391
+ return;
44335
44392
  }
44336
- return {
44337
- address,
44338
- abi
44393
+ const timer = setTimeout(() => {
44394
+ signal?.removeEventListener("abort", onAbort);
44395
+ resolve();
44396
+ }, ms);
44397
+ const onAbort = () => {
44398
+ clearTimeout(timer);
44399
+ signal?.removeEventListener("abort", onAbort);
44400
+ reject(createAbortError());
44339
44401
  };
44402
+ signal?.addEventListener("abort", onAbort);
44403
+ });
44404
+ }
44405
+ var IndexerClient = class {
44406
+ constructor(endpoint, options = {}) {
44407
+ this.endpoint = endpoint;
44408
+ this.options = options;
44409
+ this.hasLoggedTokenProviderError = false;
44340
44410
  }
44341
- buildRateManagerUnavailableError(reason) {
44342
- const initError = this.config.getRateManagerInitError();
44343
- if (!initError) {
44344
- return new Error(reason);
44411
+ async resolveAuthorizationToken() {
44412
+ if (this.options.getAuthorizationToken) {
44413
+ try {
44414
+ const token = await this.options.getAuthorizationToken();
44415
+ return token ?? void 0;
44416
+ } catch (error) {
44417
+ if (this.options.onAuthorizationTokenError) {
44418
+ this.options.onAuthorizationTokenError(error);
44419
+ } else if (!this.hasLoggedTokenProviderError) {
44420
+ this.hasLoggedTokenProviderError = true;
44421
+ console.warn(
44422
+ "[IndexerClient] getAuthorizationToken failed; continuing without Authorization header",
44423
+ error
44424
+ );
44425
+ }
44426
+ return void 0;
44427
+ }
44345
44428
  }
44346
- return new Error(
44347
- `${reason}. Rate manager contracts failed to initialize: ${initError.message}`
44348
- );
44429
+ return this.options.authorizationToken;
44349
44430
  }
44350
- buildCreateRateManagerConfig(config) {
44351
- const registryAbi = this.config.getRateManagerRegistryAbi();
44352
- const includeDepositHook = abiTupleHasComponent(
44353
- registryAbi,
44354
- "createRateManager",
44355
- "depositHook"
44356
- );
44357
- const includeMinLiquidity = abiTupleHasComponent(
44358
- registryAbi,
44359
- "createRateManager",
44360
- "minLiquidity"
44361
- );
44362
- const result = {
44363
- manager: config.manager,
44364
- feeRecipient: config.feeRecipient,
44365
- maxFee: config.maxFee,
44366
- fee: config.fee
44367
- };
44368
- if (includeDepositHook) {
44369
- result.depositHook = config.depositHook ?? ZERO_ADDRESS;
44431
+ async _post(request, init) {
44432
+ const token = await this.resolveAuthorizationToken();
44433
+ const headers2 = new Headers(init?.headers);
44434
+ if (!headers2.has("Content-Type")) {
44435
+ headers2.set("Content-Type", "application/json");
44370
44436
  }
44371
- if (includeMinLiquidity) {
44372
- result.minLiquidity = config.minLiquidity ?? 0n;
44437
+ if (token && !headers2.has("Authorization")) {
44438
+ headers2.set("Authorization", token.startsWith("Bearer ") ? token : `Bearer ${token}`);
44373
44439
  }
44374
- result.name = config.name;
44375
- result.uri = config.uri;
44376
- return result;
44377
- }
44378
- buildSetRateManagerConfigArgs(params) {
44379
- const registryAbi = this.config.getRateManagerRegistryAbi();
44380
- const includeHook = abiFunctionHasInput(registryAbi, "setRateManagerConfig", "_newHook") || abiFunctionHasInput(registryAbi, "setRateManagerConfig", "newHook");
44381
- if (includeHook) {
44382
- return [
44383
- params.rateManagerId,
44384
- params.newManager,
44385
- params.newFeeRecipient,
44386
- params.newHook ?? ZERO_ADDRESS,
44387
- params.newName,
44388
- params.newUri
44389
- ];
44440
+ if (this.options.apiKey && !headers2.has("x-api-key")) {
44441
+ headers2.set("x-api-key", this.options.apiKey);
44390
44442
  }
44391
- return [
44392
- params.rateManagerId,
44393
- params.newManager,
44394
- params.newFeeRecipient,
44395
- params.newName,
44396
- params.newUri
44397
- ];
44398
- }
44399
- prepareRateManagerRegistryTransaction(opts) {
44400
- const contract = this.resolveRateManagerRegistryContract(opts.registry);
44401
- const functionName = resolveAbiFunctionName(contract.abi, opts.functionNames);
44402
- return this.config.host.prepareContractTransaction({
44403
- address: contract.address,
44404
- abi: contract.abi,
44405
- functionName,
44406
- args: opts.args,
44407
- txOverrides: opts.txOverrides
44408
- });
44409
- }
44410
- prepareCreateRateManagerTransaction(params) {
44411
- return this.prepareRateManagerRegistryTransaction({
44412
- functionNames: ["createRateManager"],
44413
- args: [this.buildCreateRateManagerConfig(params.config)],
44414
- txOverrides: params.txOverrides
44415
- });
44416
- }
44417
- prepareSetVaultRateTransaction(params) {
44418
- return this.prepareRateManagerRegistryTransaction({
44419
- functionNames: ["setRate", "setMinRate"],
44420
- args: [params.rateManagerId, params.paymentMethodHash, params.currencyHash, params.rate],
44421
- txOverrides: params.txOverrides
44422
- });
44423
- }
44424
- prepareSetVaultRatesBatchTransaction(params) {
44425
- return this.prepareRateManagerRegistryTransaction({
44426
- functionNames: ["setRateBatch", "setMinRatesBatch"],
44427
- args: [params.rateManagerId, params.paymentMethods, params.currencies, params.rates],
44428
- txOverrides: params.txOverrides
44429
- });
44430
- }
44431
- prepareSetOracleRateConfigTransaction(params) {
44432
- const escrowContext = this.config.host.resolveEscrowContext({
44433
- escrowAddress: params.escrowAddress,
44434
- depositId: params.depositId
44443
+ const res = await fetch(this.endpoint, {
44444
+ method: "POST",
44445
+ headers: headers2,
44446
+ body: JSON.stringify(request),
44447
+ cache: "no-store",
44448
+ ...init
44435
44449
  });
44436
- if (escrowContext.version !== "v2") {
44437
- throw new Error("setOracleRateConfig requires EscrowV2");
44450
+ if (!res.ok) {
44451
+ throw new IndexerHttpError(res.status, res.statusText, {
44452
+ retryAfterSeconds: parseRetryAfterSeconds(res.headers.get("Retry-After"))
44453
+ });
44438
44454
  }
44439
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfig"]);
44440
- return this.config.host.prepareEscrowTransaction({
44441
- functionName,
44442
- args: [
44443
- parseRawDepositId(params.depositId),
44444
- params.paymentMethodHash,
44445
- params.currencyHash,
44446
- normalizeOracleRateConfig(params.config)
44447
- ],
44448
- txOverrides: params.txOverrides,
44449
- escrowAddress: escrowContext.address,
44450
- escrowAbi: escrowContext.abi
44451
- });
44452
- }
44453
- prepareRemoveOracleRateConfigTransaction(params) {
44454
- const escrowContext = this.config.host.resolveEscrowContext({
44455
- escrowAddress: params.escrowAddress,
44456
- depositId: params.depositId
44457
- });
44458
- if (escrowContext.version !== "v2") {
44459
- throw new Error("removeOracleRateConfig requires EscrowV2");
44460
- }
44461
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["removeOracleRateConfig"]);
44462
- return this.config.host.prepareEscrowTransaction({
44463
- functionName,
44464
- args: [parseRawDepositId(params.depositId), params.paymentMethodHash, params.currencyHash],
44465
- txOverrides: params.txOverrides,
44466
- escrowAddress: escrowContext.address,
44467
- escrowAbi: escrowContext.abi
44468
- });
44469
- }
44470
- prepareSetOracleRateConfigBatchTransaction(params) {
44471
- const escrowContext = this.config.host.resolveEscrowContext({
44472
- escrowAddress: params.escrowAddress,
44473
- depositId: params.depositId
44474
- });
44475
- if (escrowContext.version !== "v2") {
44476
- throw new Error("setOracleRateConfigBatch requires EscrowV2");
44477
- }
44478
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfigBatch"]);
44479
- return this.config.host.prepareEscrowTransaction({
44480
- functionName,
44481
- args: [
44482
- parseRawDepositId(params.depositId),
44483
- params.paymentMethods,
44484
- params.currencies,
44485
- params.configs.map((group) => group.map((config) => normalizeOracleRateConfig(config)))
44486
- ],
44487
- txOverrides: params.txOverrides,
44488
- escrowAddress: escrowContext.address,
44489
- escrowAbi: escrowContext.abi
44490
- });
44491
- }
44492
- prepareUpdateCurrencyConfigBatchTransaction(params) {
44493
- const escrowContext = this.config.host.resolveEscrowContext({
44494
- escrowAddress: params.escrowAddress,
44495
- depositId: params.depositId
44496
- });
44497
- if (escrowContext.version !== "v2") {
44498
- throw new Error("updateCurrencyConfigBatch requires EscrowV2");
44499
- }
44500
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["updateCurrencyConfigBatch"]);
44501
- return this.config.host.prepareEscrowTransaction({
44502
- functionName,
44503
- args: [
44504
- parseRawDepositId(params.depositId),
44505
- params.paymentMethods,
44506
- params.updates.map(
44507
- (group) => group.map((update) => ({
44508
- code: update.code,
44509
- minConversionRate: typeof update.minConversionRate === "bigint" ? update.minConversionRate : BigInt(update.minConversionRate),
44510
- updateOracle: update.updateOracle,
44511
- oracleRateConfig: normalizeOracleRateConfig(update.oracleRateConfig)
44512
- }))
44513
- )
44514
- ],
44515
- txOverrides: params.txOverrides,
44516
- escrowAddress: escrowContext.address,
44517
- escrowAbi: escrowContext.abi
44518
- });
44519
- }
44520
- prepareDeactivateCurrenciesBatchTransaction(params) {
44521
- const escrowContext = this.config.host.resolveEscrowContext({
44522
- escrowAddress: params.escrowAddress,
44523
- depositId: params.depositId
44524
- });
44525
- if (escrowContext.version !== "v2") {
44526
- throw new Error("deactivateCurrenciesBatch requires EscrowV2");
44455
+ const json = await res.json();
44456
+ if (json.errors?.length) {
44457
+ const msg = json.errors.map((e) => e.message).join(", ");
44458
+ throw new Error(`GraphQL errors: ${msg}`);
44527
44459
  }
44528
- const functionName = resolveAbiFunctionName(escrowContext.abi, ["deactivateCurrenciesBatch"]);
44529
- return this.config.host.prepareEscrowTransaction({
44530
- functionName,
44531
- args: [parseRawDepositId(params.depositId), params.paymentMethods, params.currencyCodes],
44532
- txOverrides: params.txOverrides,
44533
- escrowAddress: escrowContext.address,
44534
- escrowAbi: escrowContext.abi
44535
- });
44536
- }
44537
- prepareSetVaultConfigTransaction(params) {
44538
- return this.prepareRateManagerRegistryTransaction({
44539
- functionNames: ["setRateManagerConfig"],
44540
- args: this.buildSetRateManagerConfigArgs(params),
44541
- txOverrides: params.txOverrides
44542
- });
44460
+ if (!json.data) throw new Error("No data returned from indexer");
44461
+ return json.data;
44543
44462
  }
44544
- async getDepositRateManager(escrow, depositId) {
44545
- const id = parseRawDepositId(depositId);
44546
- const escrowContext = this.config.host.resolveEscrowContext({
44547
- escrowAddress: escrow,
44548
- depositId
44549
- });
44550
- if (getRateManagerReadFunction(escrowContext.abi, "getDepositRateManager")) {
44551
- const result = await this.config.getPublicClient().readContract({
44552
- address: escrowContext.address,
44553
- abi: escrowContext.abi,
44554
- functionName: "getDepositRateManager",
44555
- args: [id]
44556
- });
44557
- if (result && result.length >= 2) {
44558
- return {
44559
- registry: result[0],
44560
- rateManagerId: result[1]
44561
- };
44463
+ async query(request, init) {
44464
+ const retries = Math.max(0, init?.retries ?? 1);
44465
+ const rateLimitRetries = Math.max(0, init?.rateLimitRetries ?? 2);
44466
+ const maxAttempts = 1 + Math.max(retries, rateLimitRetries);
44467
+ const {
44468
+ retries: _unusedRetries,
44469
+ rateLimitRetries: _unusedRateLimitRetries,
44470
+ ...requestInit
44471
+ } = init ?? {};
44472
+ let attempts = 0;
44473
+ let rateLimitAttempt = 0;
44474
+ let standardRetryAttempt = 0;
44475
+ let lastErr;
44476
+ while (attempts < maxAttempts) {
44477
+ try {
44478
+ return await this._post(request, requestInit);
44479
+ } catch (e) {
44480
+ lastErr = e;
44481
+ attempts += 1;
44482
+ if (requestInit.signal?.aborted) {
44483
+ throw e;
44484
+ }
44485
+ const hasAttemptsRemaining = attempts < maxAttempts;
44486
+ if (e instanceof IndexerHttpError && e.status === 429 && rateLimitAttempt < rateLimitRetries && hasAttemptsRemaining) {
44487
+ rateLimitAttempt += 1;
44488
+ const waitSeconds = e.retryAfterSeconds !== void 0 ? Math.max(0, e.retryAfterSeconds) : 1;
44489
+ await delay(waitSeconds * 1e3, requestInit.signal ?? void 0);
44490
+ continue;
44491
+ }
44492
+ if (!hasAttemptsRemaining || standardRetryAttempt >= retries) {
44493
+ break;
44494
+ }
44495
+ standardRetryAttempt += 1;
44496
+ await delay(200 * standardRetryAttempt, requestInit.signal ?? void 0);
44562
44497
  }
44563
44498
  }
44564
- const controllerAddress = this.config.getRateManagerControllerAddress();
44565
- const controllerAbi = this.config.getRateManagerControllerAbi();
44566
- if (!controllerAddress || !controllerAbi) {
44567
- throw this.buildRateManagerUnavailableError("Rate manager controller not available");
44568
- }
44569
- const legacyResult = await this.config.getPublicClient().readContract({
44570
- address: controllerAddress,
44571
- abi: controllerAbi,
44572
- functionName: "getDepositRateManager",
44573
- args: [escrow, id]
44574
- });
44575
- return {
44576
- registry: legacyResult[0],
44577
- rateManagerId: legacyResult[1]
44578
- };
44579
- }
44580
- async getManagerFee(escrow, depositId) {
44581
- const id = parseRawDepositId(depositId);
44582
- const escrowContext = this.config.host.resolveEscrowContext({
44583
- escrowAddress: escrow,
44584
- depositId
44585
- });
44586
- if (getRateManagerReadFunction(escrowContext.abi, "getManagerFee")) {
44587
- const result2 = await this.config.getPublicClient().readContract({
44588
- address: escrowContext.address,
44589
- abi: escrowContext.abi,
44590
- functionName: "getManagerFee",
44591
- args: [id]
44592
- });
44593
- return parseManagerFeeFromRead(result2);
44594
- }
44595
- const controllerAddress = this.config.getRateManagerControllerAddress();
44596
- const controllerAbi = this.config.getRateManagerControllerAbi();
44597
- if (!controllerAddress || !controllerAbi) {
44598
- throw this.buildRateManagerUnavailableError("Rate manager controller not available");
44599
- }
44600
- const result = await this.config.getPublicClient().readContract({
44601
- address: controllerAddress,
44602
- abi: controllerAbi,
44603
- functionName: "getManagerFee",
44604
- args: [escrow, id]
44605
- });
44606
- return parseManagerFeeFromRead(result);
44607
- }
44608
- async getEffectiveRate(params) {
44609
- const escrowContext = this.config.host.resolveEscrowContext({
44610
- escrowAddress: params.escrow,
44611
- depositId: params.depositId
44612
- });
44613
- const id = parseRawDepositId(params.depositId);
44614
- return await this.config.getPublicClient().readContract({
44615
- address: escrowContext.address,
44616
- abi: escrowContext.abi,
44617
- functionName: "getEffectiveRate",
44618
- args: [id, params.paymentMethod, params.fiatCurrency]
44619
- });
44620
- }
44621
- };
44622
- var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && abi.some(
44623
- (item) => item.type === "function" && item.name === functionName
44624
- );
44625
-
44626
- // src/indexer/client.ts
44627
- var IndexerHttpError = class extends Error {
44628
- constructor(status, statusText, options) {
44629
- super(`Indexer request failed: ${status} ${statusText}`);
44630
- this.name = "IndexerHttpError";
44631
- this.status = status;
44632
- this.retryAfterSeconds = options?.retryAfterSeconds;
44499
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
44633
44500
  }
44634
44501
  };
44635
- function parseRetryAfterSeconds(rawHeader) {
44636
- if (!rawHeader) return void 0;
44637
- const parsedSeconds = Number(rawHeader);
44638
- if (Number.isFinite(parsedSeconds) && parsedSeconds >= 0) {
44639
- return Math.ceil(parsedSeconds);
44640
- }
44641
- const parsedDateMs = Date.parse(rawHeader);
44642
- if (!Number.isFinite(parsedDateMs)) return void 0;
44643
- const secondsUntilRetry = Math.ceil((parsedDateMs - Date.now()) / 1e3);
44644
- return Math.max(0, secondsUntilRetry);
44645
- }
44646
- function createAbortError() {
44647
- const error = new Error("The operation was aborted");
44648
- error.name = "AbortError";
44649
- return error;
44650
- }
44651
- function delay(ms, signal) {
44652
- if (ms <= 0) {
44653
- return Promise.resolve();
44654
- }
44655
- return new Promise((resolve, reject) => {
44656
- if (signal?.aborted) {
44657
- reject(createAbortError());
44658
- return;
44659
- }
44660
- const timer = setTimeout(() => {
44661
- signal?.removeEventListener("abort", onAbort);
44662
- resolve();
44663
- }, ms);
44664
- const onAbort = () => {
44665
- clearTimeout(timer);
44666
- signal?.removeEventListener("abort", onAbort);
44667
- reject(createAbortError());
44668
- };
44669
- signal?.addEventListener("abort", onAbort);
44670
- });
44671
- }
44672
- var IndexerClient = class {
44673
- constructor(endpoint, options = {}) {
44674
- this.endpoint = endpoint;
44675
- this.options = options;
44676
- this.hasLoggedTokenProviderError = false;
44677
- }
44678
- async resolveAuthorizationToken() {
44679
- if (this.options.getAuthorizationToken) {
44680
- try {
44681
- const token = await this.options.getAuthorizationToken();
44682
- return token ?? void 0;
44683
- } catch (error) {
44684
- if (this.options.onAuthorizationTokenError) {
44685
- this.options.onAuthorizationTokenError(error);
44686
- } else if (!this.hasLoggedTokenProviderError) {
44687
- this.hasLoggedTokenProviderError = true;
44688
- console.warn(
44689
- "[IndexerClient] getAuthorizationToken failed; continuing without Authorization header",
44690
- error
44691
- );
44692
- }
44693
- return void 0;
44694
- }
44695
- }
44696
- return this.options.authorizationToken;
44697
- }
44698
- async _post(request, init) {
44699
- const token = await this.resolveAuthorizationToken();
44700
- const headers2 = new Headers(init?.headers);
44701
- if (!headers2.has("Content-Type")) {
44702
- headers2.set("Content-Type", "application/json");
44703
- }
44704
- if (token && !headers2.has("Authorization")) {
44705
- headers2.set("Authorization", token.startsWith("Bearer ") ? token : `Bearer ${token}`);
44706
- }
44707
- if (this.options.apiKey && !headers2.has("x-api-key")) {
44708
- headers2.set("x-api-key", this.options.apiKey);
44709
- }
44710
- const res = await fetch(this.endpoint, {
44711
- method: "POST",
44712
- headers: headers2,
44713
- body: JSON.stringify(request),
44714
- cache: "no-store",
44715
- ...init
44716
- });
44717
- if (!res.ok) {
44718
- throw new IndexerHttpError(res.status, res.statusText, {
44719
- retryAfterSeconds: parseRetryAfterSeconds(res.headers.get("Retry-After"))
44720
- });
44721
- }
44722
- const json = await res.json();
44723
- if (json.errors?.length) {
44724
- const msg = json.errors.map((e) => e.message).join(", ");
44725
- throw new Error(`GraphQL errors: ${msg}`);
44726
- }
44727
- if (!json.data) throw new Error("No data returned from indexer");
44728
- return json.data;
44729
- }
44730
- async query(request, init) {
44731
- const retries = Math.max(0, init?.retries ?? 1);
44732
- const rateLimitRetries = Math.max(0, init?.rateLimitRetries ?? 2);
44733
- const maxAttempts = 1 + Math.max(retries, rateLimitRetries);
44734
- const {
44735
- retries: _unusedRetries,
44736
- rateLimitRetries: _unusedRateLimitRetries,
44737
- ...requestInit
44738
- } = init ?? {};
44739
- let attempts = 0;
44740
- let rateLimitAttempt = 0;
44741
- let standardRetryAttempt = 0;
44742
- let lastErr;
44743
- while (attempts < maxAttempts) {
44744
- try {
44745
- return await this._post(request, requestInit);
44746
- } catch (e) {
44747
- lastErr = e;
44748
- attempts += 1;
44749
- if (requestInit.signal?.aborted) {
44750
- throw e;
44751
- }
44752
- const hasAttemptsRemaining = attempts < maxAttempts;
44753
- if (e instanceof IndexerHttpError && e.status === 429 && rateLimitAttempt < rateLimitRetries && hasAttemptsRemaining) {
44754
- rateLimitAttempt += 1;
44755
- const waitSeconds = e.retryAfterSeconds !== void 0 ? Math.max(0, e.retryAfterSeconds) : 1;
44756
- await delay(waitSeconds * 1e3, requestInit.signal ?? void 0);
44757
- continue;
44758
- }
44759
- if (!hasAttemptsRemaining || standardRetryAttempt >= retries) {
44760
- break;
44761
- }
44762
- standardRetryAttempt += 1;
44763
- await delay(200 * standardRetryAttempt, requestInit.signal ?? void 0);
44764
- }
44765
- }
44766
- throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
44767
- }
44768
- };
44769
- function defaultIndexerEndpoint(env = "PRODUCTION") {
44770
- switch (env) {
44771
- case "PRODUCTION":
44772
- return "https://indexer.zkp2p.xyz/v1/graphql";
44773
- case "PREPRODUCTION":
44774
- return "https://indexer-preprod.zkp2p.xyz/v1/graphql";
44775
- case "STAGING":
44776
- return "https://indexer-staging.zkp2p.xyz/v1/graphql";
44777
- case "DEV":
44778
- case "LOCAL":
44779
- return "https://indexer-staging.zkp2p.xyz/v1/graphql";
44780
- default:
44781
- return "https://indexer.zkp2p.xyz/v1/graphql";
44502
+ function defaultIndexerEndpoint(env = "PRODUCTION") {
44503
+ switch (env) {
44504
+ case "PRODUCTION":
44505
+ return "https://indexer.zkp2p.xyz/v1/graphql";
44506
+ case "PREPRODUCTION":
44507
+ return "https://indexer-preprod.zkp2p.xyz/v1/graphql";
44508
+ case "STAGING":
44509
+ return "https://indexer-staging.zkp2p.xyz/v1/graphql";
44510
+ case "DEV":
44511
+ case "LOCAL":
44512
+ return "https://indexer-staging.zkp2p.xyz/v1/graphql";
44513
+ default:
44514
+ return "https://indexer.zkp2p.xyz/v1/graphql";
44782
44515
  }
44783
44516
  }
44784
44517
 
@@ -46223,7 +45956,11 @@ var IndexerDepositService = class {
46223
45956
  (pm) => (pm.paymentMethodHash ?? "").toLowerCase() === target
46224
45957
  );
46225
45958
  return match?.payeeDetailsHash ?? null;
46226
- } catch {
45959
+ } catch (error) {
45960
+ logger.warn(
45961
+ "[sdk] resolvePayeeHash lookup failed; returning null",
45962
+ error instanceof Error ? error.message : error
45963
+ );
46227
45964
  return null;
46228
45965
  }
46229
45966
  }
@@ -46385,1165 +46122,1791 @@ var IndexerDepositService = class {
46385
46122
  }
46386
46123
  };
46387
46124
 
46388
- // src/indexer/rateManagerService.ts
46389
- init_bigint();
46390
- var DEFAULT_LIMIT2 = 50;
46391
- var RATE_MANAGER_HISTORY_PAGE_SIZE = 250;
46392
- var EVM_ADDRESS_REGEX = /^0x[a-f0-9]{40}$/;
46393
- function normalizeRateManagerId(value) {
46394
- if (!value) return "";
46395
- return value.toLowerCase();
46125
+ // src/referral.ts
46126
+ var normalizeReferralCode = (code) => code.trim().toUpperCase();
46127
+ var isValidReferralCode = (code) => /^[A-Z0-9]{6}$/.test(normalizeReferralCode(code));
46128
+ var REFERRAL_SIGNATURE_DOMAIN = { name: "ZKP2PReferral", version: "1" };
46129
+ var REFERRAL_SIGNATURE_TYPES = {
46130
+ CreateCode: [
46131
+ { name: "wallet", type: "address" },
46132
+ { name: "audience", type: "string" },
46133
+ { name: "issuedAt", type: "uint256" }
46134
+ ],
46135
+ RedeemCode: [
46136
+ { name: "wallet", type: "address" },
46137
+ { name: "code", type: "string" },
46138
+ { name: "referrer", type: "address" },
46139
+ { name: "audience", type: "string" },
46140
+ { name: "issuedAt", type: "uint256" }
46141
+ ],
46142
+ RenameCode: [
46143
+ { name: "wallet", type: "address" },
46144
+ { name: "oldCode", type: "string" },
46145
+ { name: "newCode", type: "string" },
46146
+ { name: "audience", type: "string" },
46147
+ { name: "issuedAt", type: "uint256" }
46148
+ ]
46149
+ };
46150
+
46151
+ // src/adapters/api.ts
46152
+ function createHeaders(apiKey, authorizationToken) {
46153
+ const headers2 = { "Content-Type": "application/json" };
46154
+ if (apiKey) headers2["x-api-key"] = apiKey;
46155
+ if (authorizationToken) {
46156
+ headers2.Authorization = authorizationToken.startsWith("Bearer ") ? authorizationToken : `Bearer ${authorizationToken}`;
46157
+ }
46158
+ return headers2;
46396
46159
  }
46397
- function normalizeAddress3(value) {
46398
- if (!value) return "";
46399
- return value.toLowerCase();
46160
+ function withApiBase(baseApiUrl) {
46161
+ const trimmed = (baseApiUrl || "").trim();
46162
+ let base2 = trimmed.replace(/\/+$/, "");
46163
+ base2 = base2.replace(/\/v1$/i, "");
46164
+ base2 = base2.replace(/\/v2$/i, "");
46165
+ return base2;
46400
46166
  }
46401
- function escapeLikePatternLiteral(value) {
46402
- return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
46167
+ async function apiFetch({
46168
+ url,
46169
+ method = "GET",
46170
+ body,
46171
+ apiKey,
46172
+ authorizationToken,
46173
+ timeoutMs,
46174
+ retryCount = 3,
46175
+ retryDelayMs = 1e3
46176
+ }) {
46177
+ const endpoint = url.replace(/^[^/]*\/\/[^/]*/, "");
46178
+ return withRetry(
46179
+ async () => {
46180
+ let res;
46181
+ try {
46182
+ const options = {
46183
+ method,
46184
+ headers: createHeaders(apiKey, authorizationToken)
46185
+ };
46186
+ if (body && method !== "GET") {
46187
+ options.body = JSON.stringify(body);
46188
+ }
46189
+ res = await fetch(url, options);
46190
+ } catch (error) {
46191
+ throw new exports.NetworkError("Failed to connect to API server", { endpoint, error });
46192
+ }
46193
+ if (!res.ok) {
46194
+ const errorText = await res.text();
46195
+ throw parseAPIError(res, errorText);
46196
+ }
46197
+ return res.json();
46198
+ },
46199
+ retryCount,
46200
+ retryDelayMs,
46201
+ timeoutMs
46202
+ );
46403
46203
  }
46404
- function parseScopedRateManagerFilterId(value) {
46405
- const trimmed = value.trim().toLowerCase();
46406
- if (!trimmed) return null;
46407
- const separatorIndex = trimmed.indexOf(":");
46408
- if (separatorIndex <= 0) return null;
46409
- const rateManagerAddress = normalizeAddress3(trimmed.slice(0, separatorIndex));
46410
- const rateManagerId = normalizeRateManagerId(trimmed.slice(separatorIndex + 1));
46411
- if (!EVM_ADDRESS_REGEX.test(rateManagerAddress) || !rateManagerId) {
46412
- return null;
46204
+ function unwrapResponseObject(payload) {
46205
+ if (payload && typeof payload === "object" && "responseObject" in payload) {
46206
+ return payload.responseObject;
46413
46207
  }
46414
- return { rateManagerAddress, rateManagerId };
46415
- }
46416
- function getManagerScopeKey(rateManagerId, rateManagerAddress) {
46417
- const normalizedId = normalizeRateManagerId(rateManagerId);
46418
- const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
46419
- return normalizedRateManagerAddress ? `${normalizedRateManagerAddress}:${normalizedId}` : normalizedId;
46208
+ return payload;
46420
46209
  }
46421
- function extractRateManagerAddressFromScopedId(id) {
46422
- if (!id) return null;
46423
- const parts = id.split("_");
46424
- if (parts.length < 3) return null;
46425
- const rateManagerAddress = parts[1] ?? "";
46426
- return rateManagerAddress.startsWith("0x") ? rateManagerAddress.toLowerCase() : null;
46210
+ function requireAuthorizationToken(authorizationToken, endpoint) {
46211
+ if (!authorizationToken) {
46212
+ throw new exports.ValidationError(
46213
+ `authorizationToken is required for ${endpoint}`,
46214
+ "authorizationToken"
46215
+ );
46216
+ }
46217
+ return authorizationToken;
46427
46218
  }
46428
- function buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress) {
46429
- const normalizedId = escapeLikePatternLiteral(normalizeRateManagerId(rateManagerId));
46430
- const normalizedRateManagerAddress = escapeLikePatternLiteral(
46431
- normalizeAddress3(rateManagerAddress)
46432
- );
46433
- return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
46219
+ function requireReferralWriteAuth(authorizationToken, signature, endpoint) {
46220
+ if (authorizationToken && signature) {
46221
+ throw new exports.ValidationError(
46222
+ `Use either authorizationToken or signature for ${endpoint}, not both`,
46223
+ "authorizationToken"
46224
+ );
46225
+ }
46226
+ if (!authorizationToken && !signature) {
46227
+ throw new exports.ValidationError(
46228
+ `authorizationToken or signature is required for ${endpoint}`,
46229
+ "authorizationToken"
46230
+ );
46231
+ }
46232
+ return authorizationToken;
46434
46233
  }
46435
- function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
46436
- return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
46234
+ function requireEscrowAddress(escrowAddress, endpoint) {
46235
+ if (!escrowAddress) {
46236
+ throw new exports.ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
46237
+ }
46238
+ return escrowAddress;
46437
46239
  }
46438
- function normalizeCompositeDepositId(depositId, escrowAddress) {
46439
- const normalizedDepositId = depositId.trim().toLowerCase();
46440
- if (!normalizedDepositId) return "";
46441
- if (normalizedDepositId.includes("_")) return normalizedDepositId;
46442
- const normalizedEscrow = normalizeAddress3(escrowAddress);
46443
- if (normalizedEscrow) {
46444
- return `${normalizedEscrow}_${normalizedDepositId}`;
46240
+ function normalizeReferralAddress(address, field) {
46241
+ const normalized = address.trim().toLowerCase();
46242
+ if (!isValidHexAddress(normalized)) {
46243
+ throw new exports.ValidationError(`${field} must be a valid Ethereum address`, field);
46445
46244
  }
46446
- return normalizedDepositId;
46245
+ return normalized;
46447
46246
  }
46448
- function extractDepositIdOnContract(compositeDepositId) {
46449
- if (!compositeDepositId) return null;
46450
- const parts = compositeDepositId.split("_");
46451
- const rawDepositId = parts[parts.length - 1];
46452
- return rawDepositId && /^\d+$/.test(rawDepositId) ? rawDepositId : null;
46453
- }
46454
- function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
46455
- if (!compositeDepositId) return null;
46456
- const [escrowAddress] = compositeDepositId.split("_");
46457
- return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
46458
- }
46459
- function parseRateManagerFilterIds(rateManagerIds) {
46460
- const bare = /* @__PURE__ */ new Set();
46461
- const scoped = /* @__PURE__ */ new Map();
46462
- for (const value of rateManagerIds) {
46463
- const scopedRateManager = parseScopedRateManagerFilterId(value);
46464
- if (scopedRateManager) {
46465
- scoped.set(
46466
- getManagerScopeKey(scopedRateManager.rateManagerId, scopedRateManager.rateManagerAddress),
46467
- scopedRateManager
46468
- );
46469
- continue;
46470
- }
46471
- if (value.includes(":")) {
46472
- continue;
46473
- }
46474
- const normalizedRateManagerId = normalizeRateManagerId(value);
46475
- if (normalizedRateManagerId) {
46476
- bare.add(normalizedRateManagerId);
46477
- }
46247
+ function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
46248
+ const normalized = withApiBase(baseApiUrl).toLowerCase();
46249
+ if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
46250
+ return "PREPRODUCTION";
46478
46251
  }
46479
- return { bare, scoped };
46480
- }
46481
- function buildDepositScopeKey(scope) {
46482
- return `${scope.escrow}:${scope.depositIdOnContract}`;
46252
+ if (normalized.includes("staging") || normalized.includes("/staging/") || normalized.includes("localhost") || normalized.includes("127.0.0.1")) {
46253
+ return "STAGING";
46254
+ }
46255
+ return "PRODUCTION";
46483
46256
  }
46484
- function toSafeBigInt(value) {
46485
- if (!value) return 0n;
46257
+ async function withOptionalTimeout(promise, timeoutMs, endpoint) {
46258
+ if (!timeoutMs || timeoutMs <= 0) return promise;
46259
+ let timer;
46486
46260
  try {
46487
- return parseBigIntLike(value);
46488
- } catch {
46489
- return 0n;
46261
+ return await Promise.race([
46262
+ promise,
46263
+ new Promise((_, reject) => {
46264
+ timer = setTimeout(() => {
46265
+ reject(new exports.NetworkError("Request timed out", { endpoint }));
46266
+ }, timeoutMs);
46267
+ })
46268
+ ]);
46269
+ } finally {
46270
+ if (timer) clearTimeout(timer);
46490
46271
  }
46491
46272
  }
46492
- function compareBigInt(a, b, direction) {
46493
- if (a === b) return 0;
46494
- if (direction === "asc") return a < b ? -1 : 1;
46495
- return a > b ? -1 : 1;
46273
+ function toDateFromUnixSeconds(value) {
46274
+ if (!value) return void 0;
46275
+ const numeric = Number(value);
46276
+ if (!Number.isFinite(numeric) || numeric <= 0) return void 0;
46277
+ return new Date(numeric * 1e3);
46496
46278
  }
46497
- function parseEventCursorId(id) {
46498
- if (!id) return null;
46499
- const [chainIdRaw, blockNumberRaw, logIndexRaw] = id.split("_");
46500
- if (!chainIdRaw || !blockNumberRaw || !logIndexRaw) return null;
46501
- if (!/^\d+$/.test(chainIdRaw) || !/^\d+$/.test(blockNumberRaw) || !/^\d+$/.test(logIndexRaw)) {
46502
- return null;
46503
- }
46279
+ function toBigIntSafe(value) {
46280
+ if (value === null || value === void 0) return 0n;
46504
46281
  try {
46505
- return {
46506
- chainId: BigInt(chainIdRaw),
46507
- blockNumber: BigInt(blockNumberRaw),
46508
- logIndex: BigInt(logIndexRaw)
46509
- };
46282
+ return BigInt(value);
46510
46283
  } catch {
46511
- return null;
46284
+ return 0n;
46512
46285
  }
46513
46286
  }
46514
- function compareEventCursorIdsByRecency(leftId, rightId) {
46515
- const left = parseEventCursorId(leftId);
46516
- const right = parseEventCursorId(rightId);
46517
- if (left && right) {
46518
- if (left.chainId !== right.chainId) {
46519
- return left.chainId > right.chainId ? -1 : 1;
46520
- }
46521
- if (left.blockNumber !== right.blockNumber) {
46522
- return left.blockNumber > right.blockNumber ? -1 : 1;
46523
- }
46524
- if (left.logIndex !== right.logIndex) {
46525
- return left.logIndex > right.logIndex ? -1 : 1;
46287
+ function normalizeOwnerDepositsStatus(status) {
46288
+ if (!status) return void 0;
46289
+ if (status === "WITHDRAWN") return "CLOSED";
46290
+ return status;
46291
+ }
46292
+ function buildLegacyVerifierCurrencies(deposit) {
46293
+ const currenciesByMethod = /* @__PURE__ */ new Map();
46294
+ for (const currency of deposit.currencies ?? []) {
46295
+ const methodHash = currency.paymentMethodHash;
46296
+ const resolvedConversionRate = currency.conversionRate ?? currency.minConversionRate;
46297
+ if (resolvedConversionRate === null || resolvedConversionRate === void 0) {
46298
+ logger.warn(
46299
+ `[sdk] Skipping currency with missing conversion rate (deposit ${deposit.depositId}, currency ${currency.currencyCode})`
46300
+ );
46301
+ continue;
46526
46302
  }
46527
- return 0;
46303
+ const bucket = currenciesByMethod.get(methodHash) ?? [];
46304
+ bucket.push({
46305
+ currencyCode: currency.currencyCode,
46306
+ conversionRate: resolvedConversionRate,
46307
+ minConversionRate: currency.minConversionRate,
46308
+ managerRate: currency.managerRate ?? null,
46309
+ rateManagerId: currency.rateManagerId ?? null
46310
+ });
46311
+ currenciesByMethod.set(methodHash, bucket);
46528
46312
  }
46529
- return (rightId ?? "").localeCompare(leftId ?? "");
46530
- }
46531
- function isAggregateOrderField(field) {
46532
- return field === "currentDelegatedBalance" || field === "totalFilledVolume";
46313
+ return currenciesByMethod;
46533
46314
  }
46534
- function normalizeRateManagerEntity(manager) {
46315
+ function convertIndexerDepositToLegacyApiDeposit(deposit) {
46316
+ const currenciesByMethod = buildLegacyVerifierCurrencies(deposit);
46317
+ const verifiers = (deposit.paymentMethods ?? []).filter((paymentMethod) => paymentMethod.active !== false).map((paymentMethod) => ({
46318
+ depositId: Number(deposit.depositId),
46319
+ verifier: "",
46320
+ methodHash: paymentMethod.paymentMethodHash,
46321
+ intentGatingService: paymentMethod.intentGatingService,
46322
+ payeeDetailsHash: paymentMethod.payeeDetailsHash,
46323
+ data: "0x",
46324
+ currencies: currenciesByMethod.get(paymentMethod.paymentMethodHash) ?? []
46325
+ }));
46326
+ const remainingDeposits = toBigIntSafe(deposit.remainingDeposits);
46327
+ const outstandingIntentAmount = toBigIntSafe(deposit.outstandingIntentAmount);
46328
+ const totalAmountTaken = toBigIntSafe(deposit.totalAmountTaken);
46329
+ const totalWithdrawn = toBigIntSafe(deposit.totalWithdrawn);
46330
+ const amount = remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn;
46535
46331
  return {
46536
- ...manager,
46537
- rateManagerAddress: normalizeAddress3(manager.rateManagerAddress)
46332
+ id: Number(deposit.depositId),
46333
+ depositor: deposit.depositor,
46334
+ token: deposit.token,
46335
+ amount: amount.toString(),
46336
+ remainingDeposits: deposit.remainingDeposits,
46337
+ intentAmountMin: deposit.intentAmountMin,
46338
+ intentAmountMax: deposit.intentAmountMax,
46339
+ acceptingIntents: deposit.acceptingIntents,
46340
+ outstandingIntentAmount: deposit.outstandingIntentAmount,
46341
+ availableLiquidity: deposit.remainingDeposits,
46342
+ status: deposit.status,
46343
+ totalIntents: deposit.totalIntents,
46344
+ signaledIntents: deposit.signaledIntents,
46345
+ fulfilledIntents: deposit.fulfilledIntents,
46346
+ prunedIntents: deposit.prunedIntents,
46347
+ totalAmountTaken: deposit.totalAmountTaken,
46348
+ totalWithdrawn: deposit.totalWithdrawn,
46349
+ successRateBps: deposit.successRateBps,
46350
+ rateManagerId: deposit.rateManagerId ?? null,
46351
+ vaultName: null,
46352
+ rateManagerRegistry: null,
46353
+ createdAt: toDateFromUnixSeconds(deposit.timestamp),
46354
+ updatedAt: toDateFromUnixSeconds(deposit.updatedAt),
46355
+ verifiers
46538
46356
  };
46539
46357
  }
46540
- function toDelegationEntityFromDeposit(deposit) {
46541
- const rateManagerId = normalizeRateManagerId(deposit.rateManagerId);
46542
- if (!rateManagerId) return null;
46543
- const delegatedAt = deposit.delegatedAt ?? null;
46544
- return {
46545
- id: deposit.id,
46546
- chainId: deposit.chainId,
46547
- rateManagerId,
46548
- rateManagerAddress: normalizeAddress3(deposit.rateManagerAddress) || null,
46549
- depositId: deposit.id,
46550
- delegatedAt,
46551
- createdAt: delegatedAt ?? deposit.updatedAt,
46552
- updatedAt: deposit.updatedAt
46553
- };
46358
+ async function apiPostDepositDetails(req, baseApiUrl, timeoutMs) {
46359
+ return apiFetch({
46360
+ url: `${withApiBase(baseApiUrl)}/v2/makers/create`,
46361
+ method: "POST",
46362
+ body: req,
46363
+ timeoutMs
46364
+ });
46554
46365
  }
46555
- var IndexerRateManagerService = class {
46556
- constructor(client) {
46557
- this.client = client;
46558
- }
46559
- buildRateManagerScopeWhere(rateManagerIds) {
46560
- if (!rateManagerIds?.length) return void 0;
46561
- const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
46562
- const scopeConditions = [];
46563
- if (bare.size > 0) {
46564
- scopeConditions.push({
46565
- rateManagerId: { _in: [...bare] }
46566
- });
46567
- }
46568
- for (const scopedRateManager of scoped.values()) {
46569
- scopeConditions.push({
46570
- rateManagerId: { _eq: scopedRateManager.rateManagerId },
46571
- rateManagerAddress: { _eq: scopedRateManager.rateManagerAddress }
46572
- });
46573
- }
46574
- if (scopeConditions.length === 1) {
46575
- return scopeConditions[0];
46576
- }
46577
- if (scopeConditions.length > 1) {
46578
- return { _or: scopeConditions };
46366
+ async function apiGetQuote(req, baseApiUrl, timeoutMs, apiKey) {
46367
+ if (req.quotesToReturn !== void 0) {
46368
+ if (!Number.isInteger(req.quotesToReturn) || req.quotesToReturn < 1) {
46369
+ throw new exports.ValidationError("quotesToReturn must be a positive integer", "quotesToReturn");
46579
46370
  }
46580
- return void 0;
46581
46371
  }
46582
- buildWhere(filter) {
46583
- if (!filter) return void 0;
46584
- const where = {};
46585
- if (filter.manager) {
46586
- where.manager = { _ilike: filter.manager };
46587
- }
46588
- if (filter.name) {
46589
- where.name = { _ilike: `%${filter.name}%` };
46590
- }
46591
- if (filter.maxFee) {
46592
- where.maxFee = { _lte: filter.maxFee };
46593
- }
46594
- const scopeWhere = this.buildRateManagerScopeWhere(filter.rateManagerIds);
46595
- if (scopeWhere) {
46596
- Object.assign(where, scopeWhere);
46597
- }
46598
- return Object.keys(where).length ? where : void 0;
46372
+ if (!isValidHexAddress(req.user)) {
46373
+ throw new exports.ValidationError("user must be a valid Ethereum address", "user");
46599
46374
  }
46600
- buildAggregateWhere(filter) {
46601
- return this.buildRateManagerScopeWhere(filter?.rateManagerIds) ?? {};
46375
+ if (!isValidHexAddress(req.recipient)) {
46376
+ throw new exports.ValidationError("recipient must be a valid Ethereum address", "recipient");
46602
46377
  }
46603
- buildLegacyAggregateWhere(filter) {
46604
- const rateManagerIds = filter?.rateManagerIds;
46605
- if (!rateManagerIds?.length) return {};
46606
- const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
46607
- const scopeConditions = [];
46608
- if (bare.size > 0) {
46609
- scopeConditions.push({
46610
- rateManagerId: { _in: [...bare] }
46611
- });
46612
- }
46613
- for (const scopedRateManager of scoped.values()) {
46614
- scopeConditions.push({
46615
- rateManagerId: { _eq: scopedRateManager.rateManagerId },
46616
- id: {
46617
- _ilike: buildRateManagerAddressScopedIdPattern(
46618
- scopedRateManager.rateManagerId,
46619
- scopedRateManager.rateManagerAddress
46620
- )
46621
- }
46622
- });
46378
+ if (!isValidHexAddress(req.destinationToken)) {
46379
+ throw new exports.ValidationError(
46380
+ "destinationToken must be a valid Ethereum address",
46381
+ "destinationToken"
46382
+ );
46383
+ }
46384
+ const isExactFiat = req.isExactFiat !== false;
46385
+ const endpoint = isExactFiat ? "exact-fiat" : "exact-token";
46386
+ let url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
46387
+ if (req.quotesToReturn) url += `?quotesToReturn=${req.quotesToReturn}`;
46388
+ const requestBody = {
46389
+ ...req,
46390
+ [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
46391
+ amount: void 0,
46392
+ isExactFiat: void 0,
46393
+ quotesToReturn: void 0,
46394
+ includePrivateOrderbooks: req.includePrivateOrderbooks
46395
+ };
46396
+ Object.keys(requestBody).forEach((k) => requestBody[k] === void 0 && delete requestBody[k]);
46397
+ return apiFetch({
46398
+ url,
46399
+ method: "POST",
46400
+ body: requestBody,
46401
+ apiKey,
46402
+ timeoutMs
46403
+ });
46404
+ }
46405
+ async function apiGetQuotesBestByPlatform(req, baseApiUrl, timeoutMs, apiKey) {
46406
+ const isExactFiat = req.isExactFiat !== false;
46407
+ const endpoint = isExactFiat ? "best-by-platform" : "best-by-platform-exact-token";
46408
+ const url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
46409
+ const requestBody = {
46410
+ ...req,
46411
+ [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
46412
+ amount: void 0,
46413
+ isExactFiat: void 0,
46414
+ referrerFeeConfig: void 0
46415
+ };
46416
+ Object.keys(requestBody).forEach(
46417
+ (key) => requestBody[key] === void 0 && delete requestBody[key]
46418
+ );
46419
+ return apiFetch({
46420
+ url,
46421
+ method: "POST",
46422
+ body: requestBody,
46423
+ apiKey,
46424
+ timeoutMs
46425
+ });
46426
+ }
46427
+ async function apiGetPayeeDetails(req, baseApiUrl, timeoutMs) {
46428
+ return apiFetch({
46429
+ url: `${withApiBase(baseApiUrl)}/v2/makers/${req.processorName}/${req.hashedOnchainId}`,
46430
+ method: "GET",
46431
+ timeoutMs
46432
+ });
46433
+ }
46434
+ async function apiValidatePayeeDetails(req, baseApiUrl, timeoutMs) {
46435
+ const data52 = await apiFetch({
46436
+ url: `${withApiBase(baseApiUrl)}/v2/makers/validate`,
46437
+ method: "POST",
46438
+ body: req,
46439
+ timeoutMs
46440
+ });
46441
+ if (typeof data52?.responseObject === "boolean") {
46442
+ return {
46443
+ ...data52,
46444
+ responseObject: { isValid: data52.responseObject }
46445
+ };
46446
+ }
46447
+ return data52;
46448
+ }
46449
+ async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs) {
46450
+ const escrowAddress = requireEscrowAddress(
46451
+ req.escrowAddress,
46452
+ "apiGetOwnerDeposits requires escrowAddress"
46453
+ );
46454
+ const indexerEndpoint = defaultIndexerEndpoint(inferIndexerEnvFromBaseApiUrl(baseApiUrl));
46455
+ const indexerClient = new IndexerClient(indexerEndpoint, {
46456
+ apiKey,
46457
+ authorizationToken: authToken
46458
+ });
46459
+ const service = new IndexerDepositService(indexerClient);
46460
+ const deposits = await withOptionalTimeout(
46461
+ service.fetchDepositsWithRelations(
46462
+ {
46463
+ depositor: req.ownerAddress,
46464
+ escrowAddress,
46465
+ escrowAddresses: req.escrowAddresses?.length ? req.escrowAddresses : void 0,
46466
+ status: normalizeOwnerDepositsStatus(req.status)
46467
+ },
46468
+ void 0,
46469
+ { includeIntents: false }
46470
+ ),
46471
+ timeoutMs,
46472
+ indexerEndpoint
46473
+ );
46474
+ return {
46475
+ success: true,
46476
+ message: "ok",
46477
+ responseObject: deposits.map(convertIndexerDepositToLegacyApiDeposit),
46478
+ statusCode: 200
46479
+ };
46480
+ }
46481
+ async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
46482
+ const normalizedOwner = req.owner.toLowerCase();
46483
+ const query = new URLSearchParams({
46484
+ owner: normalizedOwner,
46485
+ chainId: String(req.chainId)
46486
+ });
46487
+ const endpoint = `/v2/taker/tier?${query.toString()}`;
46488
+ return apiFetch({
46489
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
46490
+ method: "GET",
46491
+ timeoutMs
46492
+ });
46493
+ }
46494
+ async function apiGetReferralDashboard(opts) {
46495
+ const address = opts.address ? normalizeReferralAddress(opts.address, "address") : void 0;
46496
+ const endpoint = address ? `/v2/referral?${new URLSearchParams({ address }).toString()}` : "/v2/referral";
46497
+ const authorizationToken = address ? void 0 : requireAuthorizationToken(opts.authorizationToken, endpoint);
46498
+ const response = await apiFetch({
46499
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46500
+ method: "GET",
46501
+ authorizationToken,
46502
+ timeoutMs: opts.timeoutMs
46503
+ });
46504
+ return unwrapResponseObject(response);
46505
+ }
46506
+ async function apiGetReferralEarnings(opts) {
46507
+ const address = opts.address ? normalizeReferralAddress(opts.address, "address") : void 0;
46508
+ const endpoint = address ? `/v2/referral/earnings?${new URLSearchParams({ address }).toString()}` : "/v2/referral/earnings";
46509
+ const authorizationToken = address ? void 0 : requireAuthorizationToken(opts.authorizationToken, endpoint);
46510
+ const response = await apiFetch({
46511
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46512
+ method: "GET",
46513
+ authorizationToken,
46514
+ timeoutMs: opts.timeoutMs
46515
+ });
46516
+ return unwrapResponseObject(response);
46517
+ }
46518
+ async function apiLookupReferralCode(code, opts) {
46519
+ const normalizedCode = normalizeReferralCode(code);
46520
+ const endpoint = `/v2/referral/code/${encodeURIComponent(normalizedCode)}`;
46521
+ const response = await apiFetch({
46522
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46523
+ method: "GET",
46524
+ timeoutMs: opts.timeoutMs
46525
+ });
46526
+ return unwrapResponseObject(response);
46527
+ }
46528
+ async function apiCreateReferralCode(req, opts) {
46529
+ const endpoint = "/v2/referral/code";
46530
+ const authorizationToken = requireReferralWriteAuth(
46531
+ opts.authorizationToken,
46532
+ req.signature,
46533
+ endpoint
46534
+ );
46535
+ const response = await apiFetch({
46536
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46537
+ method: "POST",
46538
+ body: req.signature ? { signature: req.signature } : {},
46539
+ authorizationToken,
46540
+ timeoutMs: opts.timeoutMs
46541
+ });
46542
+ return unwrapResponseObject(response);
46543
+ }
46544
+ async function apiRedeemReferralCode(req, opts) {
46545
+ const endpoint = "/v2/referral/redeem";
46546
+ const authorizationToken = requireReferralWriteAuth(
46547
+ opts.authorizationToken,
46548
+ req.signature,
46549
+ endpoint
46550
+ );
46551
+ const response = await apiFetch({
46552
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46553
+ method: "POST",
46554
+ body: {
46555
+ code: normalizeReferralCode(req.code),
46556
+ ...req.signature ? { signature: req.signature } : {}
46557
+ },
46558
+ authorizationToken,
46559
+ timeoutMs: opts.timeoutMs
46560
+ });
46561
+ return unwrapResponseObject(response);
46562
+ }
46563
+ async function apiUpdateReferralCode(req, opts) {
46564
+ const endpoint = "/v2/referral/code";
46565
+ const authorizationToken = requireReferralWriteAuth(
46566
+ opts.authorizationToken,
46567
+ req.signature,
46568
+ endpoint
46569
+ );
46570
+ const response = await apiFetch({
46571
+ url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
46572
+ method: "PATCH",
46573
+ body: {
46574
+ code: normalizeReferralCode(req.code),
46575
+ ...req.signature ? { signature: req.signature } : {}
46576
+ },
46577
+ authorizationToken,
46578
+ timeoutMs: opts.timeoutMs
46579
+ });
46580
+ return unwrapResponseObject(response);
46581
+ }
46582
+ async function apiUploadSellerCredential(processorName, payeeDetails, bundle, baseApiUrl, timeoutMs) {
46583
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
46584
+ payeeDetails
46585
+ )}/seller-credential`;
46586
+ return apiFetch({
46587
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
46588
+ method: "POST",
46589
+ body: bundle,
46590
+ timeoutMs
46591
+ });
46592
+ }
46593
+ async function apiUploadGoogleOAuthSellerCredential(processorName, payeeDetails, body, baseApiUrl, opts) {
46594
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
46595
+ payeeDetails
46596
+ )}/seller-credential/google-oauth`;
46597
+ return apiFetch({
46598
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
46599
+ method: "POST",
46600
+ body,
46601
+ timeoutMs: opts?.timeoutMs
46602
+ });
46603
+ }
46604
+ async function apiGetSellerCredentialStatus(processorName, payeeDetails, baseApiUrl, timeoutMs) {
46605
+ const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
46606
+ payeeDetails
46607
+ )}/seller-credential/status`;
46608
+ return apiFetch({
46609
+ url: `${withApiBase(baseApiUrl)}${endpoint}`,
46610
+ method: "GET",
46611
+ timeoutMs
46612
+ });
46613
+ }
46614
+ async function apiVerifySellerPayment(platform, req, baseApiUrl, timeoutMs, apiKey) {
46615
+ const body = {
46616
+ txId: req.txId,
46617
+ chainId: req.chainId,
46618
+ intent: req.intent,
46619
+ ...req.metadata !== void 0 ? { metadata: req.metadata } : {}
46620
+ };
46621
+ return apiFetch({
46622
+ url: `${withApiBase(baseApiUrl)}/v2/verify/seller/${encodeURIComponent(platform)}`,
46623
+ method: "POST",
46624
+ body,
46625
+ apiKey,
46626
+ timeoutMs
46627
+ });
46628
+ }
46629
+ async function apiGetOrderbook(params, optsOrBaseApiUrl, timeoutMs) {
46630
+ const opts = typeof optsOrBaseApiUrl === "string" ? {
46631
+ baseApiUrl: optsOrBaseApiUrl,
46632
+ timeoutMs
46633
+ } : optsOrBaseApiUrl;
46634
+ const query = new URLSearchParams();
46635
+ Object.entries(params).forEach(([key, value]) => {
46636
+ if (value === void 0 || value === null) return;
46637
+ query.set(key, String(value));
46638
+ });
46639
+ const response = await apiFetch({
46640
+ url: `${withApiBase(opts.baseApiUrl)}/v2/orderbook?${query.toString()}`,
46641
+ method: "GET",
46642
+ timeoutMs: opts.timeoutMs
46643
+ });
46644
+ return response.responseObject;
46645
+ }
46646
+ async function apiGetDepositBundle(params, optsOrBaseApiUrl, timeoutMs) {
46647
+ const opts = typeof optsOrBaseApiUrl === "string" ? {
46648
+ baseApiUrl: optsOrBaseApiUrl,
46649
+ timeoutMs
46650
+ } : optsOrBaseApiUrl;
46651
+ const escrowAddress = requireEscrowAddress(
46652
+ params.escrowAddress,
46653
+ "apiGetDepositBundle requires escrowAddress"
46654
+ );
46655
+ const query = new URLSearchParams({ escrowAddress });
46656
+ if (params.dailySnapshotLimit !== void 0) {
46657
+ query.set("dailySnapshotLimit", String(params.dailySnapshotLimit));
46658
+ }
46659
+ const response = await apiFetch({
46660
+ url: `${withApiBase(opts.baseApiUrl)}/v2/deposits/${params.depositId}/bundle?${query.toString()}`,
46661
+ method: "GET",
46662
+ timeoutMs: opts.timeoutMs
46663
+ });
46664
+ return response.responseObject;
46665
+ }
46666
+
46667
+ // src/client/ReferralAccountOperations.ts
46668
+ init_errors();
46669
+ var ReferralAccountOperations = class {
46670
+ constructor(config) {
46671
+ this.config = config;
46672
+ }
46673
+ async getReferralDashboard(opts) {
46674
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46675
+ const authorizationToken = opts?.address ? void 0 : await this.resolveAuthorizationToken(opts);
46676
+ return apiGetReferralDashboard({
46677
+ baseApiUrl,
46678
+ timeoutMs,
46679
+ authorizationToken,
46680
+ address: opts?.address
46681
+ });
46682
+ }
46683
+ async getReferralEarnings(opts) {
46684
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46685
+ const authorizationToken = opts?.address ? void 0 : await this.resolveAuthorizationToken(opts);
46686
+ return apiGetReferralEarnings({
46687
+ baseApiUrl,
46688
+ timeoutMs,
46689
+ authorizationToken,
46690
+ address: opts?.address
46691
+ });
46692
+ }
46693
+ async lookupReferralCode(code, opts) {
46694
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46695
+ return apiLookupReferralCode(code, { baseApiUrl, timeoutMs });
46696
+ }
46697
+ async createReferralCode(opts) {
46698
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46699
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
46700
+ return apiCreateReferralCode({}, { baseApiUrl, timeoutMs, authorizationToken });
46701
+ }
46702
+ async createReferralCodeWithSignature(opts) {
46703
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46704
+ const signature = await this.signCreateReferralCode(opts);
46705
+ return apiCreateReferralCode({ signature }, { baseApiUrl, timeoutMs });
46706
+ }
46707
+ async redeemReferralCode(code, opts) {
46708
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46709
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
46710
+ return apiRedeemReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
46711
+ }
46712
+ async redeemReferralCodeWithSignature(code, opts) {
46713
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46714
+ const normalizedCode = normalizeReferralCode(code);
46715
+ const lookup = opts?.referrerWalletAddress ? void 0 : await this.lookupReferralCode(normalizedCode, { baseApiUrl, timeoutMs });
46716
+ const referrerWalletAddress = opts?.referrerWalletAddress ?? lookup?.referrerWalletAddress;
46717
+ if (!referrerWalletAddress) {
46718
+ throw new exports.ValidationError(
46719
+ "referrerWalletAddress is required for referral signature auth",
46720
+ "referrerWalletAddress"
46721
+ );
46623
46722
  }
46624
- if (scopeConditions.length === 1) {
46625
- return scopeConditions[0] ?? {};
46723
+ if (lookup && !lookup.isActive) {
46724
+ throw new exports.ValidationError("Referral code is not active", "code");
46626
46725
  }
46627
- if (scopeConditions.length > 1) {
46628
- return { _or: scopeConditions };
46726
+ const signature = await this.signRedeemReferralCode(
46727
+ normalizedCode,
46728
+ referrerWalletAddress,
46729
+ opts
46730
+ );
46731
+ return apiRedeemReferralCode({ code: normalizedCode, signature }, { baseApiUrl, timeoutMs });
46732
+ }
46733
+ async updateReferralCode(code, opts) {
46734
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46735
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
46736
+ return apiUpdateReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
46737
+ }
46738
+ async updateReferralCodeWithSignature(code, opts) {
46739
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46740
+ const signature = await this.signRenameReferralCode(code, opts.oldCode, opts);
46741
+ return apiUpdateReferralCode({ code, signature }, { baseApiUrl, timeoutMs });
46742
+ }
46743
+ resolveRequestOptions(opts) {
46744
+ return {
46745
+ baseApiUrl: this.stripTrailingSlash(
46746
+ opts?.baseApiUrl ?? this.config.getBaseApiUrl() ?? DEFAULT_BASE_API_URL
46747
+ ),
46748
+ timeoutMs: opts?.timeoutMs ?? this.config.getApiTimeoutMs()
46749
+ };
46750
+ }
46751
+ stripTrailingSlash(url) {
46752
+ return url.replace(/\/$/, "");
46753
+ }
46754
+ async resolveAuthorizationToken(opts) {
46755
+ if (opts?.authorizationToken !== void 0) {
46756
+ return opts.authorizationToken;
46629
46757
  }
46630
- return {};
46758
+ const provider = opts?.getAuthorizationToken ?? this.config.getAuthorizationTokenProvider();
46759
+ if (provider) {
46760
+ return await provider() ?? void 0;
46761
+ }
46762
+ return this.config.getAuthorizationToken();
46763
+ }
46764
+ resolveAudience(audience) {
46765
+ if (audience) return audience;
46766
+ if (this.config.getChainId() === chains.hardhat.id) return "localhardhat";
46767
+ if (this.config.getRuntimeEnv() === "staging") return "base_staging";
46768
+ return "base_production";
46769
+ }
46770
+ resolveIssuedAt(issuedAt) {
46771
+ const resolved = issuedAt ?? Math.floor(Date.now() / 1e3);
46772
+ if (!Number.isInteger(resolved) || resolved <= 0) {
46773
+ throw new exports.ValidationError("issuedAt must be a positive unix timestamp", "issuedAt");
46774
+ }
46775
+ return resolved;
46631
46776
  }
46632
- buildOrderBy(pagination) {
46633
- const rawField = pagination?.orderBy ?? "createdAt";
46634
- const field = isAggregateOrderField(rawField) ? "createdAt" : rawField;
46635
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
46636
- return [{ [field]: direction }];
46777
+ getSigningAccount() {
46778
+ const walletClient = this.config.getWalletClient();
46779
+ const account = walletClient.account;
46780
+ if (!account) {
46781
+ throw new exports.ValidationError(
46782
+ "walletClient account is required for referral signature auth",
46783
+ "walletClient.account"
46784
+ );
46785
+ }
46786
+ const rawAddress = typeof account === "string" ? account : account.address;
46787
+ const walletAddress = normalizeAddress(rawAddress);
46788
+ if (!walletAddress) {
46789
+ throw new exports.ValidationError(
46790
+ "walletClient account address is required for referral signature auth",
46791
+ "walletClient.account"
46792
+ );
46793
+ }
46794
+ return { account, walletAddress };
46637
46795
  }
46638
- toRateManagerListItems(result) {
46639
- const managers = (result.RateManager ?? []).map(normalizeRateManagerEntity);
46640
- const aggregatesByScope = /* @__PURE__ */ new Map();
46641
- for (const aggregate of result.ManagerAggregateStats ?? []) {
46642
- const aggregateRateManagerAddress = normalizeAddress3(aggregate.rateManagerAddress) || extractRateManagerAddressFromScopedId(aggregate.id);
46643
- const scopeKey = getManagerScopeKey(aggregate.rateManagerId, aggregateRateManagerAddress);
46644
- aggregatesByScope.set(scopeKey, aggregate);
46796
+ normalizeReferralWalletAddress(address, field) {
46797
+ const normalized = normalizeAddress(address.toLowerCase());
46798
+ if (!normalized) {
46799
+ throw new exports.ValidationError(`${field} must be a valid Ethereum address`, field);
46645
46800
  }
46646
- return managers.map((manager) => ({
46647
- manager,
46648
- aggregate: aggregatesByScope.get(
46649
- getManagerScopeKey(manager.rateManagerId, normalizeAddress3(manager.rateManagerAddress))
46650
- ) ?? aggregatesByScope.get(getManagerScopeKey(manager.rateManagerId)) ?? null
46651
- }));
46801
+ return normalized;
46802
+ }
46803
+ async signCreateReferralCode(opts) {
46804
+ const { account, walletAddress } = this.getSigningAccount();
46805
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
46806
+ const audience = this.resolveAudience(opts?.audience);
46807
+ const signature = await this.config.getWalletClient().signTypedData({
46808
+ account,
46809
+ domain: REFERRAL_SIGNATURE_DOMAIN,
46810
+ types: REFERRAL_SIGNATURE_TYPES,
46811
+ primaryType: "CreateCode",
46812
+ message: { wallet: walletAddress, audience, issuedAt: BigInt(issuedAt) }
46813
+ });
46814
+ return { walletAddress, signature, issuedAt, audience };
46815
+ }
46816
+ async signRedeemReferralCode(code, referrerWalletAddress, opts) {
46817
+ const { account, walletAddress } = this.getSigningAccount();
46818
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
46819
+ const audience = this.resolveAudience(opts?.audience);
46820
+ const normalizedCode = normalizeReferralCode(code);
46821
+ const referrer = this.normalizeReferralWalletAddress(
46822
+ referrerWalletAddress,
46823
+ "referrerWalletAddress"
46824
+ );
46825
+ const signature = await this.config.getWalletClient().signTypedData({
46826
+ account,
46827
+ domain: REFERRAL_SIGNATURE_DOMAIN,
46828
+ types: REFERRAL_SIGNATURE_TYPES,
46829
+ primaryType: "RedeemCode",
46830
+ message: {
46831
+ wallet: walletAddress,
46832
+ code: normalizedCode,
46833
+ referrer,
46834
+ audience,
46835
+ issuedAt: BigInt(issuedAt)
46836
+ }
46837
+ });
46838
+ return { walletAddress, signature, issuedAt, audience, referrer };
46839
+ }
46840
+ async signRenameReferralCode(newCode, oldCode, opts) {
46841
+ const { account, walletAddress } = this.getSigningAccount();
46842
+ const issuedAt = this.resolveIssuedAt(opts?.issuedAt);
46843
+ const audience = this.resolveAudience(opts?.audience);
46844
+ const normalizedOldCode = normalizeReferralCode(oldCode);
46845
+ const normalizedNewCode = normalizeReferralCode(newCode);
46846
+ const signature = await this.config.getWalletClient().signTypedData({
46847
+ account,
46848
+ domain: REFERRAL_SIGNATURE_DOMAIN,
46849
+ types: REFERRAL_SIGNATURE_TYPES,
46850
+ primaryType: "RenameCode",
46851
+ message: {
46852
+ wallet: walletAddress,
46853
+ oldCode: normalizedOldCode,
46854
+ newCode: normalizedNewCode,
46855
+ audience,
46856
+ issuedAt: BigInt(issuedAt)
46857
+ }
46858
+ });
46859
+ return { walletAddress, signature, issuedAt, audience, oldCode: normalizedOldCode };
46652
46860
  }
46653
- applyHookFilter(rows, hasHook) {
46654
- if (hasHook === void 0) return rows;
46655
- return hasHook ? [] : rows;
46861
+ };
46862
+
46863
+ // src/client/VaultOperations.ts
46864
+ var VaultOperations = class {
46865
+ constructor(config) {
46866
+ this.config = config;
46867
+ }
46868
+ supportsInlineOracleRateConfig(params) {
46869
+ const escrowContext = this.config.host.resolveEscrowContext({
46870
+ escrowAddress: params?.escrowAddress
46871
+ });
46872
+ return escrowCurrencyHasOracleConfig(escrowContext.abi);
46873
+ }
46874
+ resolveRateManagerRegistryContract(registryAddress) {
46875
+ const abi = this.config.getRateManagerRegistryAbi();
46876
+ if (!abi) {
46877
+ throw this.buildRateManagerUnavailableError("Rate manager registry not available");
46878
+ }
46879
+ if (registryAddress) {
46880
+ return {
46881
+ address: registryAddress,
46882
+ abi
46883
+ };
46884
+ }
46885
+ const address = this.config.getRateManagerRegistryAddress();
46886
+ if (!address) {
46887
+ throw this.buildRateManagerUnavailableError("Rate manager registry not available");
46888
+ }
46889
+ return {
46890
+ address,
46891
+ abi
46892
+ };
46893
+ }
46894
+ buildRateManagerUnavailableError(reason) {
46895
+ const initError = this.config.getRateManagerInitError();
46896
+ if (!initError) {
46897
+ return new Error(reason);
46898
+ }
46899
+ return new Error(
46900
+ `${reason}. Rate manager contracts failed to initialize: ${initError.message}`
46901
+ );
46902
+ }
46903
+ buildCreateRateManagerConfig(config) {
46904
+ const registryAbi = this.config.getRateManagerRegistryAbi();
46905
+ const includeDepositHook = abiTupleHasComponent(
46906
+ registryAbi,
46907
+ "createRateManager",
46908
+ "depositHook"
46909
+ );
46910
+ const includeMinLiquidity = abiTupleHasComponent(
46911
+ registryAbi,
46912
+ "createRateManager",
46913
+ "minLiquidity"
46914
+ );
46915
+ const result = {
46916
+ manager: config.manager,
46917
+ feeRecipient: config.feeRecipient,
46918
+ maxFee: config.maxFee,
46919
+ fee: config.fee
46920
+ };
46921
+ if (includeDepositHook) {
46922
+ result.depositHook = config.depositHook ?? ZERO_ADDRESS;
46923
+ }
46924
+ if (includeMinLiquidity) {
46925
+ result.minLiquidity = config.minLiquidity ?? 0n;
46926
+ }
46927
+ result.name = config.name;
46928
+ result.uri = config.uri;
46929
+ return result;
46930
+ }
46931
+ buildSetRateManagerConfigArgs(params) {
46932
+ const registryAbi = this.config.getRateManagerRegistryAbi();
46933
+ const includeHook = abiFunctionHasInput(registryAbi, "setRateManagerConfig", "_newHook") || abiFunctionHasInput(registryAbi, "setRateManagerConfig", "newHook");
46934
+ if (includeHook) {
46935
+ return [
46936
+ params.rateManagerId,
46937
+ params.newManager,
46938
+ params.newFeeRecipient,
46939
+ params.newHook ?? ZERO_ADDRESS,
46940
+ params.newName,
46941
+ params.newUri
46942
+ ];
46943
+ }
46944
+ return [
46945
+ params.rateManagerId,
46946
+ params.newManager,
46947
+ params.newFeeRecipient,
46948
+ params.newName,
46949
+ params.newUri
46950
+ ];
46951
+ }
46952
+ prepareRateManagerRegistryTransaction(opts) {
46953
+ const contract = this.resolveRateManagerRegistryContract(opts.registry);
46954
+ const functionName = resolveAbiFunctionName(contract.abi, opts.functionNames);
46955
+ return this.config.host.prepareContractTransaction({
46956
+ address: contract.address,
46957
+ abi: contract.abi,
46958
+ functionName,
46959
+ args: opts.args,
46960
+ txOverrides: opts.txOverrides
46961
+ });
46656
46962
  }
46657
- async queryRateManagerList(variables, legacyVariables) {
46658
- try {
46659
- return await this.client.query({
46660
- query: RATE_MANAGER_LIST_QUERY,
46661
- variables
46662
- });
46663
- } catch (error) {
46664
- if (!isSchemaCompatibilityError(error)) {
46665
- throw error;
46666
- }
46667
- return this.client.query({
46668
- query: LEGACY_RATE_MANAGER_LIST_QUERY,
46669
- variables: legacyVariables
46670
- });
46671
- }
46963
+ prepareCreateRateManagerTransaction(params) {
46964
+ return this.prepareRateManagerRegistryTransaction({
46965
+ functionNames: ["createRateManager"],
46966
+ args: [this.buildCreateRateManagerConfig(params.config)],
46967
+ txOverrides: params.txOverrides
46968
+ });
46672
46969
  }
46673
- buildDelegationOrderBy(pagination) {
46674
- const rawField = pagination?.orderBy ?? "updatedAt";
46675
- const field = rawField === "createdAt" ? "delegatedAt" : rawField;
46676
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
46677
- return [{ [field]: direction }];
46970
+ prepareSetVaultRateTransaction(params) {
46971
+ return this.prepareRateManagerRegistryTransaction({
46972
+ functionNames: ["setRate", "setMinRate"],
46973
+ args: [params.rateManagerId, params.paymentMethodHash, params.currencyHash, params.rate],
46974
+ txOverrides: params.txOverrides
46975
+ });
46678
46976
  }
46679
- buildLegacyDelegationOrderBy(pagination) {
46680
- const rawField = pagination?.orderBy ?? "updatedAt";
46681
- const field = rawField === "delegatedAt" ? "createdAt" : rawField;
46682
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
46683
- return [{ [field]: direction }];
46977
+ prepareSetVaultRatesBatchTransaction(params) {
46978
+ return this.prepareRateManagerRegistryTransaction({
46979
+ functionNames: ["setRateBatch", "setMinRatesBatch"],
46980
+ args: [params.rateManagerId, params.paymentMethods, params.currencies, params.rates],
46981
+ txOverrides: params.txOverrides
46982
+ });
46684
46983
  }
46685
- async fetchCurrentRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
46686
- const scopes = /* @__PURE__ */ new Map();
46687
- let offset = 0;
46688
- for (; ; ) {
46689
- const delegations = await this.fetchRateManagerDelegations(rateManagerId, {
46690
- limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
46691
- offset,
46692
- orderBy: "delegatedAt",
46693
- orderDirection: "desc",
46694
- rateManagerAddress: rateManagerAddress || void 0
46695
- });
46696
- for (const delegation of delegations) {
46697
- const escrow = extractEscrowAddressFromCompositeDepositId(delegation.depositId);
46698
- const depositIdOnContract = extractDepositIdOnContract(delegation.depositId);
46699
- if (!escrow || !depositIdOnContract) continue;
46700
- const scope = { escrow, depositIdOnContract };
46701
- scopes.set(buildDepositScopeKey(scope), scope);
46702
- }
46703
- if (delegations.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
46704
- break;
46705
- }
46706
- offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
46984
+ prepareSetOracleRateConfigTransaction(params) {
46985
+ const escrowContext = this.config.host.resolveEscrowContext({
46986
+ escrowAddress: params.escrowAddress,
46987
+ depositId: params.depositId
46988
+ });
46989
+ if (escrowContext.version !== "v2") {
46990
+ throw new Error("setOracleRateConfig requires EscrowV2");
46707
46991
  }
46708
- return [...scopes.values()];
46992
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfig"]);
46993
+ return this.config.host.prepareEscrowTransaction({
46994
+ functionName,
46995
+ args: [
46996
+ parseRawDepositId(params.depositId),
46997
+ params.paymentMethodHash,
46998
+ params.currencyHash,
46999
+ normalizeOracleRateConfig(params.config)
47000
+ ],
47001
+ txOverrides: params.txOverrides,
47002
+ escrowAddress: escrowContext.address,
47003
+ escrowAbi: escrowContext.abi
47004
+ });
46709
47005
  }
46710
- async fetchHistoricalRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
46711
- const normalizedId = normalizeRateManagerId(rateManagerId);
46712
- const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
46713
- const scopes = /* @__PURE__ */ new Map();
46714
- const currentScopes = await this.fetchCurrentRateManagerDepositScopes(
46715
- normalizedId,
46716
- normalizedRateManagerAddress || void 0
46717
- );
46718
- for (const scope of currentScopes) {
46719
- scopes.set(buildDepositScopeKey(scope), scope);
47006
+ prepareRemoveOracleRateConfigTransaction(params) {
47007
+ const escrowContext = this.config.host.resolveEscrowContext({
47008
+ escrowAddress: params.escrowAddress,
47009
+ depositId: params.depositId
47010
+ });
47011
+ if (escrowContext.version !== "v2") {
47012
+ throw new Error("removeOracleRateConfig requires EscrowV2");
46720
47013
  }
46721
- try {
46722
- let offset = 0;
46723
- for (; ; ) {
46724
- const result = await this.client.query({
46725
- query: RATE_MANAGER_ASSIGNMENT_EVENTS_QUERY,
46726
- variables: {
46727
- setWhere: {
46728
- rateManagerId: { _eq: normalizedId },
46729
- ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
46730
- },
46731
- clearedWhere: {
46732
- rateManagerId: { _eq: normalizedId },
46733
- ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
46734
- },
46735
- limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
46736
- offset
46737
- }
46738
- });
46739
- const setEvents = result.EscrowV2_DepositRateManagerSet ?? [];
46740
- const clearedEvents = result.EscrowV2_DepositRateManagerCleared ?? [];
46741
- for (const event of [...setEvents, ...clearedEvents]) {
46742
- const escrow = normalizeAddress3(event.escrow);
46743
- const depositIdOnContract = event.depositIdOnContract?.toString() ?? "";
46744
- if (!escrow || !depositIdOnContract) continue;
46745
- const scope = { escrow, depositIdOnContract };
46746
- scopes.set(buildDepositScopeKey(scope), scope);
46747
- }
46748
- if (setEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE && clearedEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
46749
- break;
46750
- }
46751
- offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
46752
- }
46753
- } catch (error) {
46754
- if (!isSchemaCompatibilityError(error)) {
46755
- throw error;
46756
- }
47014
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["removeOracleRateConfig"]);
47015
+ return this.config.host.prepareEscrowTransaction({
47016
+ functionName,
47017
+ args: [parseRawDepositId(params.depositId), params.paymentMethodHash, params.currencyHash],
47018
+ txOverrides: params.txOverrides,
47019
+ escrowAddress: escrowContext.address,
47020
+ escrowAbi: escrowContext.abi
47021
+ });
47022
+ }
47023
+ prepareSetOracleRateConfigBatchTransaction(params) {
47024
+ const escrowContext = this.config.host.resolveEscrowContext({
47025
+ escrowAddress: params.escrowAddress,
47026
+ depositId: params.depositId
47027
+ });
47028
+ if (escrowContext.version !== "v2") {
47029
+ throw new Error("setOracleRateConfigBatch requires EscrowV2");
46757
47030
  }
46758
- return [...scopes.values()];
47031
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["setOracleRateConfigBatch"]);
47032
+ return this.config.host.prepareEscrowTransaction({
47033
+ functionName,
47034
+ args: [
47035
+ parseRawDepositId(params.depositId),
47036
+ params.paymentMethods,
47037
+ params.currencies,
47038
+ params.configs.map((group) => group.map((config) => normalizeOracleRateConfig(config)))
47039
+ ],
47040
+ txOverrides: params.txOverrides,
47041
+ escrowAddress: escrowContext.address,
47042
+ escrowAbi: escrowContext.abi
47043
+ });
46759
47044
  }
46760
- async fetchRateManagers(pagination, filter) {
46761
- const orderBy = pagination?.orderBy ?? "createdAt";
46762
- const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
46763
- const limit = pagination?.limit ?? DEFAULT_LIMIT2;
46764
- const offset = pagination?.offset ?? 0;
46765
- const where = this.buildWhere(filter);
46766
- const aggregateWhere = this.buildAggregateWhere(filter);
46767
- const legacyAggregateWhere = this.buildLegacyAggregateWhere(filter);
46768
- if (isAggregateOrderField(orderBy)) {
46769
- const result2 = await this.queryRateManagerList(
46770
- {
46771
- where,
46772
- aggregateWhere,
46773
- order_by: [{ createdAt: "desc" }]
46774
- },
46775
- {
46776
- where,
46777
- aggregateWhere: legacyAggregateWhere,
46778
- order_by: [{ createdAt: "desc" }]
46779
- }
46780
- );
46781
- const scopedRows = this.applyHookFilter(this.toRateManagerListItems(result2), filter?.hasHook);
46782
- const sorted = scopedRows.sort((a, b) => {
46783
- const av = orderBy === "currentDelegatedBalance" ? toSafeBigInt(a.aggregate?.currentDelegatedBalance) : toSafeBigInt(a.aggregate?.totalFilledVolume);
46784
- const bv = orderBy === "currentDelegatedBalance" ? toSafeBigInt(b.aggregate?.currentDelegatedBalance) : toSafeBigInt(b.aggregate?.totalFilledVolume);
46785
- const aggregateCmp = compareBigInt(av, bv, direction);
46786
- if (aggregateCmp !== 0) return aggregateCmp;
46787
- const createdAtCmp = compareBigInt(
46788
- toSafeBigInt(a.manager.createdAt),
46789
- toSafeBigInt(b.manager.createdAt),
46790
- "desc"
46791
- );
46792
- if (createdAtCmp !== 0) return createdAtCmp;
46793
- return a.manager.rateManagerId.localeCompare(b.manager.rateManagerId);
46794
- });
46795
- return sorted.slice(offset, offset + limit);
47045
+ prepareUpdateCurrencyConfigBatchTransaction(params) {
47046
+ const escrowContext = this.config.host.resolveEscrowContext({
47047
+ escrowAddress: params.escrowAddress,
47048
+ depositId: params.depositId
47049
+ });
47050
+ if (escrowContext.version !== "v2") {
47051
+ throw new Error("updateCurrencyConfigBatch requires EscrowV2");
46796
47052
  }
46797
- const result = await this.queryRateManagerList(
46798
- {
46799
- where,
46800
- aggregateWhere,
46801
- order_by: this.buildOrderBy(pagination),
46802
- limit,
46803
- offset
46804
- },
46805
- {
46806
- where,
46807
- aggregateWhere: legacyAggregateWhere,
46808
- order_by: this.buildOrderBy(pagination),
46809
- limit,
46810
- offset
46811
- }
46812
- );
46813
- return this.applyHookFilter(this.toRateManagerListItems(result), filter?.hasHook);
47053
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["updateCurrencyConfigBatch"]);
47054
+ return this.config.host.prepareEscrowTransaction({
47055
+ functionName,
47056
+ args: [
47057
+ parseRawDepositId(params.depositId),
47058
+ params.paymentMethods,
47059
+ params.updates.map(
47060
+ (group) => group.map((update) => ({
47061
+ code: update.code,
47062
+ minConversionRate: typeof update.minConversionRate === "bigint" ? update.minConversionRate : BigInt(update.minConversionRate),
47063
+ updateOracle: update.updateOracle,
47064
+ oracleRateConfig: normalizeOracleRateConfig(update.oracleRateConfig)
47065
+ }))
47066
+ )
47067
+ ],
47068
+ txOverrides: params.txOverrides,
47069
+ escrowAddress: escrowContext.address,
47070
+ escrowAbi: escrowContext.abi
47071
+ });
47072
+ }
47073
+ prepareDeactivateCurrenciesBatchTransaction(params) {
47074
+ const escrowContext = this.config.host.resolveEscrowContext({
47075
+ escrowAddress: params.escrowAddress,
47076
+ depositId: params.depositId
47077
+ });
47078
+ if (escrowContext.version !== "v2") {
47079
+ throw new Error("deactivateCurrenciesBatch requires EscrowV2");
47080
+ }
47081
+ const functionName = resolveAbiFunctionName(escrowContext.abi, ["deactivateCurrenciesBatch"]);
47082
+ return this.config.host.prepareEscrowTransaction({
47083
+ functionName,
47084
+ args: [parseRawDepositId(params.depositId), params.paymentMethods, params.currencyCodes],
47085
+ txOverrides: params.txOverrides,
47086
+ escrowAddress: escrowContext.address,
47087
+ escrowAbi: escrowContext.abi
47088
+ });
46814
47089
  }
46815
- async fetchRateManagerDetail(rateManagerId, options) {
46816
- if (!rateManagerId) return null;
46817
- const normalizedId = normalizeRateManagerId(rateManagerId);
46818
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
46819
- const baseVariables = {
46820
- managerWhere: {
46821
- rateManagerId: { _eq: normalizedId },
46822
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46823
- },
46824
- rateWhere: {
46825
- rateManagerId: { _eq: normalizedId },
46826
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46827
- },
46828
- aggregateWhere: {
46829
- rateManagerId: { _eq: normalizedId },
46830
- ...normalizedRateManagerAddress ? {
46831
- id: {
46832
- _ilike: buildRateManagerAddressScopedIdPattern(
46833
- normalizedId,
46834
- normalizedRateManagerAddress
46835
- )
46836
- }
46837
- } : {}
46838
- },
46839
- statsWhere: {
46840
- rateManagerId: { _eq: normalizedId },
46841
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46842
- },
46843
- delegationWhere: {
46844
- rateManagerId: { _eq: normalizedId },
46845
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46846
- },
46847
- statsLimit: options?.statsLimit ?? 20
46848
- };
46849
- const legacyVariables = {
46850
- ...baseVariables,
46851
- floorWhere: {
46852
- rateManagerId: { _eq: normalizedId },
46853
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46854
- }
46855
- };
46856
- let managerRaw;
46857
- let scopedRates = [];
46858
- let scopedRecentStats = [];
46859
- let scopedDelegations = [];
46860
- let aggregate = null;
46861
- try {
46862
- const result = await this.client.query({
46863
- query: RATE_MANAGER_DETAIL_QUERY,
46864
- variables: baseVariables
46865
- });
46866
- managerRaw = result.RateManager?.[0];
46867
- if (!managerRaw) return null;
46868
- const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
46869
- scopedRates = (result.RateManagerRate ?? []).filter(
46870
- (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
46871
- );
46872
- scopedRecentStats = (result.ManagerStats ?? []).filter((stats) => {
46873
- const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
46874
- return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
47090
+ prepareSetVaultConfigTransaction(params) {
47091
+ return this.prepareRateManagerRegistryTransaction({
47092
+ functionNames: ["setRateManagerConfig"],
47093
+ args: this.buildSetRateManagerConfigArgs(params),
47094
+ txOverrides: params.txOverrides
47095
+ });
47096
+ }
47097
+ async getDepositRateManager(escrow, depositId) {
47098
+ const id = parseRawDepositId(depositId);
47099
+ const escrowContext = this.config.host.resolveEscrowContext({
47100
+ escrowAddress: escrow,
47101
+ depositId
47102
+ });
47103
+ if (getRateManagerReadFunction(escrowContext.abi, "getDepositRateManager")) {
47104
+ const result = await this.config.getPublicClient().readContract({
47105
+ address: escrowContext.address,
47106
+ abi: escrowContext.abi,
47107
+ functionName: "getDepositRateManager",
47108
+ args: [id]
46875
47109
  });
46876
- scopedDelegations = (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation)).filter(
46877
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
46878
- );
46879
- aggregate = (result.ManagerAggregateStats ?? []).find(
46880
- (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
46881
- ) ?? result.ManagerAggregateStats?.[0] ?? null;
46882
- } catch (error) {
46883
- if (!isSchemaCompatibilityError(error)) {
46884
- throw error;
47110
+ if (result && result.length >= 2) {
47111
+ return {
47112
+ registry: result[0],
47113
+ rateManagerId: result[1]
47114
+ };
46885
47115
  }
46886
- const legacyResult = await this.client.query({
46887
- query: LEGACY_RATE_MANAGER_DETAIL_QUERY,
46888
- variables: legacyVariables
46889
- });
46890
- managerRaw = legacyResult.RateManager?.[0];
46891
- if (!managerRaw) return null;
46892
- const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
46893
- scopedRates = (legacyResult.RateManagerRate ?? []).filter(
46894
- (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
46895
- );
46896
- scopedRecentStats = (legacyResult.ManagerStats ?? []).filter((stats) => {
46897
- const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
46898
- return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
47116
+ }
47117
+ const controllerAddress = this.config.getRateManagerControllerAddress();
47118
+ const controllerAbi = this.config.getRateManagerControllerAbi();
47119
+ if (!controllerAddress || !controllerAbi) {
47120
+ throw this.buildRateManagerUnavailableError("Rate manager controller not available");
47121
+ }
47122
+ const legacyResult = await this.config.getPublicClient().readContract({
47123
+ address: controllerAddress,
47124
+ abi: controllerAbi,
47125
+ functionName: "getDepositRateManager",
47126
+ args: [escrow, id]
47127
+ });
47128
+ return {
47129
+ registry: legacyResult[0],
47130
+ rateManagerId: legacyResult[1]
47131
+ };
47132
+ }
47133
+ async getManagerFee(escrow, depositId) {
47134
+ const id = parseRawDepositId(depositId);
47135
+ const escrowContext = this.config.host.resolveEscrowContext({
47136
+ escrowAddress: escrow,
47137
+ depositId
47138
+ });
47139
+ if (getRateManagerReadFunction(escrowContext.abi, "getManagerFee")) {
47140
+ const result2 = await this.config.getPublicClient().readContract({
47141
+ address: escrowContext.address,
47142
+ abi: escrowContext.abi,
47143
+ functionName: "getManagerFee",
47144
+ args: [id]
46899
47145
  });
46900
- scopedDelegations = (legacyResult.RateManagerDelegation ?? []).filter(
46901
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
47146
+ return parseManagerFeeFromRead(result2);
47147
+ }
47148
+ const controllerAddress = this.config.getRateManagerControllerAddress();
47149
+ const controllerAbi = this.config.getRateManagerControllerAbi();
47150
+ if (!controllerAddress || !controllerAbi) {
47151
+ throw this.buildRateManagerUnavailableError("Rate manager controller not available");
47152
+ }
47153
+ const result = await this.config.getPublicClient().readContract({
47154
+ address: controllerAddress,
47155
+ abi: controllerAbi,
47156
+ functionName: "getManagerFee",
47157
+ args: [escrow, id]
47158
+ });
47159
+ return parseManagerFeeFromRead(result);
47160
+ }
47161
+ async getEffectiveRate(params) {
47162
+ const escrowContext = this.config.host.resolveEscrowContext({
47163
+ escrowAddress: params.escrow,
47164
+ depositId: params.depositId
47165
+ });
47166
+ const id = parseRawDepositId(params.depositId);
47167
+ return await this.config.getPublicClient().readContract({
47168
+ address: escrowContext.address,
47169
+ abi: escrowContext.abi,
47170
+ functionName: "getEffectiveRate",
47171
+ args: [id, params.paymentMethod, params.fiatCurrency]
47172
+ });
47173
+ }
47174
+ };
47175
+ var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && abi.some(
47176
+ (item) => item.type === "function" && item.name === functionName
47177
+ );
47178
+
47179
+ // src/indexer/rateManagerService.ts
47180
+ init_bigint();
47181
+ var DEFAULT_LIMIT2 = 50;
47182
+ var RATE_MANAGER_HISTORY_PAGE_SIZE = 250;
47183
+ var EVM_ADDRESS_REGEX = /^0x[a-f0-9]{40}$/;
47184
+ function normalizeRateManagerId(value) {
47185
+ if (!value) return "";
47186
+ return value.toLowerCase();
47187
+ }
47188
+ function normalizeAddress3(value) {
47189
+ if (!value) return "";
47190
+ return value.toLowerCase();
47191
+ }
47192
+ function escapeLikePatternLiteral(value) {
47193
+ return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
47194
+ }
47195
+ function parseScopedRateManagerFilterId(value) {
47196
+ const trimmed = value.trim().toLowerCase();
47197
+ if (!trimmed) return null;
47198
+ const separatorIndex = trimmed.indexOf(":");
47199
+ if (separatorIndex <= 0) return null;
47200
+ const rateManagerAddress = normalizeAddress3(trimmed.slice(0, separatorIndex));
47201
+ const rateManagerId = normalizeRateManagerId(trimmed.slice(separatorIndex + 1));
47202
+ if (!EVM_ADDRESS_REGEX.test(rateManagerAddress) || !rateManagerId) {
47203
+ return null;
47204
+ }
47205
+ return { rateManagerAddress, rateManagerId };
47206
+ }
47207
+ function getManagerScopeKey(rateManagerId, rateManagerAddress) {
47208
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47209
+ const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
47210
+ return normalizedRateManagerAddress ? `${normalizedRateManagerAddress}:${normalizedId}` : normalizedId;
47211
+ }
47212
+ function extractRateManagerAddressFromScopedId(id) {
47213
+ if (!id) return null;
47214
+ const parts = id.split("_");
47215
+ if (parts.length < 3) return null;
47216
+ const rateManagerAddress = parts[1] ?? "";
47217
+ return rateManagerAddress.startsWith("0x") ? rateManagerAddress.toLowerCase() : null;
47218
+ }
47219
+ function buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress) {
47220
+ const normalizedId = escapeLikePatternLiteral(normalizeRateManagerId(rateManagerId));
47221
+ const normalizedRateManagerAddress = escapeLikePatternLiteral(
47222
+ normalizeAddress3(rateManagerAddress)
47223
+ );
47224
+ return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
47225
+ }
47226
+ function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
47227
+ return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
47228
+ }
47229
+ function normalizeCompositeDepositId(depositId, escrowAddress) {
47230
+ const normalizedDepositId = depositId.trim().toLowerCase();
47231
+ if (!normalizedDepositId) return "";
47232
+ if (normalizedDepositId.includes("_")) return normalizedDepositId;
47233
+ const normalizedEscrow = normalizeAddress3(escrowAddress);
47234
+ if (normalizedEscrow) {
47235
+ return `${normalizedEscrow}_${normalizedDepositId}`;
47236
+ }
47237
+ return normalizedDepositId;
47238
+ }
47239
+ function extractDepositIdOnContract(compositeDepositId) {
47240
+ if (!compositeDepositId) return null;
47241
+ const parts = compositeDepositId.split("_");
47242
+ const rawDepositId = parts[parts.length - 1];
47243
+ return rawDepositId && /^\d+$/.test(rawDepositId) ? rawDepositId : null;
47244
+ }
47245
+ function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
47246
+ if (!compositeDepositId) return null;
47247
+ const [escrowAddress] = compositeDepositId.split("_");
47248
+ return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
47249
+ }
47250
+ function parseRateManagerFilterIds(rateManagerIds) {
47251
+ const bare = /* @__PURE__ */ new Set();
47252
+ const scoped = /* @__PURE__ */ new Map();
47253
+ for (const value of rateManagerIds) {
47254
+ const scopedRateManager = parseScopedRateManagerFilterId(value);
47255
+ if (scopedRateManager) {
47256
+ scoped.set(
47257
+ getManagerScopeKey(scopedRateManager.rateManagerId, scopedRateManager.rateManagerAddress),
47258
+ scopedRateManager
46902
47259
  );
46903
- aggregate = (legacyResult.ManagerAggregateStats ?? []).find(
46904
- (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
46905
- ) ?? legacyResult.ManagerAggregateStats?.[0] ?? null;
47260
+ continue;
46906
47261
  }
46907
- if (!managerRaw) return null;
46908
- const manager = normalizeRateManagerEntity(managerRaw);
47262
+ if (value.includes(":")) {
47263
+ continue;
47264
+ }
47265
+ const normalizedRateManagerId = normalizeRateManagerId(value);
47266
+ if (normalizedRateManagerId) {
47267
+ bare.add(normalizedRateManagerId);
47268
+ }
47269
+ }
47270
+ return { bare, scoped };
47271
+ }
47272
+ function buildDepositScopeKey(scope) {
47273
+ return `${scope.escrow}:${scope.depositIdOnContract}`;
47274
+ }
47275
+ function toSafeBigInt(value) {
47276
+ if (!value) return 0n;
47277
+ try {
47278
+ return parseBigIntLike(value);
47279
+ } catch {
47280
+ return 0n;
47281
+ }
47282
+ }
47283
+ function compareBigInt(a, b, direction) {
47284
+ if (a === b) return 0;
47285
+ if (direction === "asc") return a < b ? -1 : 1;
47286
+ return a > b ? -1 : 1;
47287
+ }
47288
+ function parseEventCursorId(id) {
47289
+ if (!id) return null;
47290
+ const [chainIdRaw, blockNumberRaw, logIndexRaw] = id.split("_");
47291
+ if (!chainIdRaw || !blockNumberRaw || !logIndexRaw) return null;
47292
+ if (!/^\d+$/.test(chainIdRaw) || !/^\d+$/.test(blockNumberRaw) || !/^\d+$/.test(logIndexRaw)) {
47293
+ return null;
47294
+ }
47295
+ try {
46909
47296
  return {
46910
- manager,
46911
- rates: scopedRates,
46912
- aggregate,
46913
- recentStats: scopedRecentStats,
46914
- delegations: scopedDelegations
47297
+ chainId: BigInt(chainIdRaw),
47298
+ blockNumber: BigInt(blockNumberRaw),
47299
+ logIndex: BigInt(logIndexRaw)
46915
47300
  };
47301
+ } catch {
47302
+ return null;
46916
47303
  }
46917
- async fetchRateManagerDelegations(rateManagerId, pagination) {
46918
- if (!rateManagerId) return [];
46919
- const normalizedId = normalizeRateManagerId(rateManagerId);
46920
- const normalizedRateManagerAddress = normalizeAddress3(pagination?.rateManagerAddress);
46921
- const variables = {
46922
- where: {
46923
- rateManagerId: { _eq: normalizedId },
46924
- ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
46925
- },
46926
- order_by: this.buildDelegationOrderBy(pagination),
46927
- limit: pagination?.limit ?? DEFAULT_LIMIT2,
46928
- offset: pagination?.offset ?? 0
46929
- };
46930
- try {
46931
- const result = await this.client.query({
46932
- query: RATE_MANAGER_DELEGATIONS_QUERY,
46933
- variables
47304
+ }
47305
+ function compareEventCursorIdsByRecency(leftId, rightId) {
47306
+ const left = parseEventCursorId(leftId);
47307
+ const right = parseEventCursorId(rightId);
47308
+ if (left && right) {
47309
+ if (left.chainId !== right.chainId) {
47310
+ return left.chainId > right.chainId ? -1 : 1;
47311
+ }
47312
+ if (left.blockNumber !== right.blockNumber) {
47313
+ return left.blockNumber > right.blockNumber ? -1 : 1;
47314
+ }
47315
+ if (left.logIndex !== right.logIndex) {
47316
+ return left.logIndex > right.logIndex ? -1 : 1;
47317
+ }
47318
+ return 0;
47319
+ }
47320
+ return (rightId ?? "").localeCompare(leftId ?? "");
47321
+ }
47322
+ function isAggregateOrderField(field) {
47323
+ return field === "currentDelegatedBalance" || field === "totalFilledVolume";
47324
+ }
47325
+ function normalizeRateManagerEntity(manager) {
47326
+ return {
47327
+ ...manager,
47328
+ rateManagerAddress: normalizeAddress3(manager.rateManagerAddress)
47329
+ };
47330
+ }
47331
+ function toDelegationEntityFromDeposit(deposit) {
47332
+ const rateManagerId = normalizeRateManagerId(deposit.rateManagerId);
47333
+ if (!rateManagerId) return null;
47334
+ const delegatedAt = deposit.delegatedAt ?? null;
47335
+ return {
47336
+ id: deposit.id,
47337
+ chainId: deposit.chainId,
47338
+ rateManagerId,
47339
+ rateManagerAddress: normalizeAddress3(deposit.rateManagerAddress) || null,
47340
+ depositId: deposit.id,
47341
+ delegatedAt,
47342
+ createdAt: delegatedAt ?? deposit.updatedAt,
47343
+ updatedAt: deposit.updatedAt
47344
+ };
47345
+ }
47346
+ var IndexerRateManagerService = class {
47347
+ constructor(client) {
47348
+ this.client = client;
47349
+ }
47350
+ buildRateManagerScopeWhere(rateManagerIds) {
47351
+ if (!rateManagerIds?.length) return void 0;
47352
+ const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
47353
+ const scopeConditions = [];
47354
+ if (bare.size > 0) {
47355
+ scopeConditions.push({
47356
+ rateManagerId: { _in: [...bare] }
46934
47357
  });
46935
- return (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation));
46936
- } catch (error) {
46937
- if (!isSchemaCompatibilityError(error)) {
46938
- throw error;
46939
- }
46940
- const legacyResult = await this.client.query({
46941
- query: LEGACY_RATE_MANAGER_DELEGATIONS_QUERY,
46942
- variables: {
46943
- ...variables,
46944
- order_by: this.buildLegacyDelegationOrderBy(pagination)
46945
- }
47358
+ }
47359
+ for (const scopedRateManager of scoped.values()) {
47360
+ scopeConditions.push({
47361
+ rateManagerId: { _eq: scopedRateManager.rateManagerId },
47362
+ rateManagerAddress: { _eq: scopedRateManager.rateManagerAddress }
46946
47363
  });
46947
- return legacyResult.RateManagerDelegation ?? [];
46948
47364
  }
47365
+ if (scopeConditions.length === 1) {
47366
+ return scopeConditions[0];
47367
+ }
47368
+ if (scopeConditions.length > 1) {
47369
+ return { _or: scopeConditions };
47370
+ }
47371
+ return void 0;
46949
47372
  }
46950
- async fetchManagerDailySnapshots(rateManagerId, options) {
46951
- if (!rateManagerId) return [];
46952
- const normalizedId = normalizeRateManagerId(rateManagerId);
46953
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
46954
- try {
46955
- const result = await this.client.query({
46956
- query: MANAGER_DAILY_SNAPSHOTS_QUERY,
46957
- variables: {
46958
- where: {
46959
- rateManagerId: { _eq: normalizedId },
46960
- ...normalizedRateManagerAddress ? {
46961
- id: {
46962
- _ilike: buildRateManagerScopedIdPattern(
46963
- normalizedId,
46964
- normalizedRateManagerAddress
46965
- )
46966
- }
46967
- } : {}
46968
- },
46969
- order_by: [{ dayTimestamp: "asc" }],
46970
- limit: options?.limit ?? 365
46971
- }
46972
- });
46973
- return result.ManagerDailySnapshot ?? [];
46974
- } catch (error) {
46975
- if (!isSchemaCompatibilityError(error)) {
46976
- throw error;
46977
- }
46978
- return [];
47373
+ buildWhere(filter) {
47374
+ if (!filter) return void 0;
47375
+ const where = {};
47376
+ if (filter.manager) {
47377
+ where.manager = { _ilike: filter.manager };
47378
+ }
47379
+ if (filter.name) {
47380
+ where.name = { _ilike: `%${filter.name}%` };
46979
47381
  }
47382
+ if (filter.maxFee) {
47383
+ where.maxFee = { _lte: filter.maxFee };
47384
+ }
47385
+ const scopeWhere = this.buildRateManagerScopeWhere(filter.rateManagerIds);
47386
+ if (scopeWhere) {
47387
+ Object.assign(where, scopeWhere);
47388
+ }
47389
+ return Object.keys(where).length ? where : void 0;
46980
47390
  }
46981
- async fetchDelegationForDeposit(depositId, options) {
46982
- if (!depositId) return null;
46983
- const normalizedDepositId = normalizeCompositeDepositId(depositId, options?.escrowAddress);
46984
- try {
46985
- const result = await this.client.query({
46986
- query: DEPOSIT_DELEGATION_QUERY,
46987
- variables: {
46988
- depositId: normalizedDepositId
46989
- }
47391
+ buildAggregateWhere(filter) {
47392
+ return this.buildRateManagerScopeWhere(filter?.rateManagerIds) ?? {};
47393
+ }
47394
+ buildLegacyAggregateWhere(filter) {
47395
+ const rateManagerIds = filter?.rateManagerIds;
47396
+ if (!rateManagerIds?.length) return {};
47397
+ const { bare, scoped } = parseRateManagerFilterIds(rateManagerIds);
47398
+ const scopeConditions = [];
47399
+ if (bare.size > 0) {
47400
+ scopeConditions.push({
47401
+ rateManagerId: { _in: [...bare] }
46990
47402
  });
46991
- const delegationDeposit = result.Deposit?.[0];
46992
- if (!delegationDeposit) {
46993
- return null;
46994
- }
46995
- return toDelegationEntityFromDeposit(delegationDeposit) ?? null;
46996
- } catch (error) {
46997
- if (!isSchemaCompatibilityError(error)) {
46998
- throw error;
46999
- }
47000
- const legacyResult = await this.client.query({
47001
- query: LEGACY_DEPOSIT_DELEGATION_QUERY,
47002
- variables: {
47003
- depositId: normalizedDepositId
47403
+ }
47404
+ for (const scopedRateManager of scoped.values()) {
47405
+ scopeConditions.push({
47406
+ rateManagerId: { _eq: scopedRateManager.rateManagerId },
47407
+ id: {
47408
+ _ilike: buildRateManagerAddressScopedIdPattern(
47409
+ scopedRateManager.rateManagerId,
47410
+ scopedRateManager.rateManagerAddress
47411
+ )
47004
47412
  }
47005
47413
  });
47006
- return legacyResult.RateManagerDelegation?.[0] ?? null;
47007
47414
  }
47415
+ if (scopeConditions.length === 1) {
47416
+ return scopeConditions[0] ?? {};
47417
+ }
47418
+ if (scopeConditions.length > 1) {
47419
+ return { _or: scopeConditions };
47420
+ }
47421
+ return {};
47422
+ }
47423
+ buildOrderBy(pagination) {
47424
+ const rawField = pagination?.orderBy ?? "createdAt";
47425
+ const field = isAggregateOrderField(rawField) ? "createdAt" : rawField;
47426
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
47427
+ return [{ [field]: direction }];
47428
+ }
47429
+ toRateManagerListItems(result) {
47430
+ const managers = (result.RateManager ?? []).map(normalizeRateManagerEntity);
47431
+ const aggregatesByScope = /* @__PURE__ */ new Map();
47432
+ for (const aggregate of result.ManagerAggregateStats ?? []) {
47433
+ const aggregateRateManagerAddress = normalizeAddress3(aggregate.rateManagerAddress) || extractRateManagerAddressFromScopedId(aggregate.id);
47434
+ const scopeKey = getManagerScopeKey(aggregate.rateManagerId, aggregateRateManagerAddress);
47435
+ aggregatesByScope.set(scopeKey, aggregate);
47436
+ }
47437
+ return managers.map((manager) => ({
47438
+ manager,
47439
+ aggregate: aggregatesByScope.get(
47440
+ getManagerScopeKey(manager.rateManagerId, normalizeAddress3(manager.rateManagerAddress))
47441
+ ) ?? aggregatesByScope.get(getManagerScopeKey(manager.rateManagerId)) ?? null
47442
+ }));
47008
47443
  }
47009
- async fetchManualRateUpdates(rateManagerId, options) {
47010
- if (!rateManagerId) return [];
47011
- const normalizedId = normalizeRateManagerId(rateManagerId);
47444
+ applyHookFilter(rows, hasHook) {
47445
+ if (hasHook === void 0) return rows;
47446
+ return hasHook ? [] : rows;
47447
+ }
47448
+ async queryRateManagerList(variables, legacyVariables) {
47012
47449
  try {
47013
- const result = await this.client.query({
47014
- query: MANUAL_RATE_UPDATES_QUERY,
47015
- variables: {
47016
- where: {
47017
- rateManagerId: { _eq: normalizedId }
47018
- },
47019
- order_by: [{ id: "desc" }],
47020
- limit: options?.limit ?? 100
47021
- }
47450
+ return await this.client.query({
47451
+ query: RATE_MANAGER_LIST_QUERY,
47452
+ variables
47022
47453
  });
47023
- return (result.RateManagerV1_RateManagerRateUpdated ?? []).map((e) => ({
47024
- ...e,
47025
- currency: e.currency ?? e.currencyCode ?? "",
47026
- minRate: e.minRate ?? e.rate ?? "0"
47027
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47028
47454
  } catch (error) {
47029
47455
  if (!isSchemaCompatibilityError(error)) {
47030
47456
  throw error;
47031
47457
  }
47032
- return [];
47458
+ return this.client.query({
47459
+ query: LEGACY_RATE_MANAGER_LIST_QUERY,
47460
+ variables: legacyVariables
47461
+ });
47033
47462
  }
47034
47463
  }
47035
- async fetchOracleConfigUpdates(rateManagerId, options) {
47036
- if (!rateManagerId) return [];
47037
- const normalizedId = normalizeRateManagerId(rateManagerId);
47038
- const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
47039
- const limit = options?.limit ?? 100;
47040
- try {
47041
- const depositScopes = await this.fetchHistoricalRateManagerDepositScopes(
47042
- normalizedId,
47043
- normalizedRateManagerAddress || void 0
47044
- );
47045
- if (!depositScopes.length) {
47046
- return [];
47047
- }
47048
- const scopedKeys = new Set(depositScopes.map((scope) => buildDepositScopeKey(scope)));
47049
- const result = await this.client.query({
47050
- query: ORACLE_CONFIG_UPDATES_QUERY,
47051
- variables: {
47052
- where: {
47053
- _or: depositScopes.map((scope) => ({
47054
- _and: [
47055
- { depositId: { _eq: scope.depositIdOnContract } },
47056
- { escrow: { _eq: scope.escrow } }
47057
- ]
47058
- }))
47059
- },
47060
- order_by: [{ id: "desc" }],
47061
- limit
47062
- }
47464
+ buildDelegationOrderBy(pagination) {
47465
+ const rawField = pagination?.orderBy ?? "updatedAt";
47466
+ const field = rawField === "createdAt" ? "delegatedAt" : rawField;
47467
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
47468
+ return [{ [field]: direction }];
47469
+ }
47470
+ buildLegacyDelegationOrderBy(pagination) {
47471
+ const rawField = pagination?.orderBy ?? "updatedAt";
47472
+ const field = rawField === "delegatedAt" ? "createdAt" : rawField;
47473
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
47474
+ return [{ [field]: direction }];
47475
+ }
47476
+ async fetchCurrentRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
47477
+ const scopes = /* @__PURE__ */ new Map();
47478
+ let offset = 0;
47479
+ for (; ; ) {
47480
+ const delegations = await this.fetchRateManagerDelegations(rateManagerId, {
47481
+ limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
47482
+ offset,
47483
+ orderBy: "delegatedAt",
47484
+ orderDirection: "desc",
47485
+ rateManagerAddress: rateManagerAddress || void 0
47063
47486
  });
47064
- return (result.EscrowV2_DepositOracleRateConfigSet ?? []).filter((event) => {
47065
- const escrow = normalizeAddress3(event.escrow);
47066
- const depositIdOnContract = event.depositIdOnContract ?? event.depositId?.toString?.() ?? "";
47067
- if (!escrow || !depositIdOnContract) return false;
47068
- return scopedKeys.has(
47069
- buildDepositScopeKey({
47070
- escrow,
47071
- depositIdOnContract
47072
- })
47073
- );
47074
- }).map((e) => ({
47075
- ...e,
47076
- rateManagerId: normalizedId,
47077
- escrow: normalizeAddress3(e.escrow) || void 0,
47078
- currency: e.currency ?? e.currencyCode ?? "",
47079
- depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
47080
- adapter: e.adapter ?? "",
47081
- spreadBps: e.spreadBps ?? 0
47082
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47083
- } catch (error) {
47084
- if (isSchemaCompatibilityError(error)) ; else {
47085
- throw error;
47487
+ for (const delegation of delegations) {
47488
+ const escrow = extractEscrowAddressFromCompositeDepositId(delegation.depositId);
47489
+ const depositIdOnContract = extractDepositIdOnContract(delegation.depositId);
47490
+ if (!escrow || !depositIdOnContract) continue;
47491
+ const scope = { escrow, depositIdOnContract };
47492
+ scopes.set(buildDepositScopeKey(scope), scope);
47086
47493
  }
47087
- const legacyResult = await this.client.query({
47088
- query: LEGACY_ORACLE_CONFIG_UPDATES_QUERY,
47089
- variables: {
47090
- where: {
47091
- rateManagerId: { _eq: normalizedId }
47092
- },
47093
- order_by: [{ id: "desc" }],
47094
- limit
47095
- }
47096
- });
47097
- return (legacyResult.RateManagerV1_DepositorFloorSet ?? []).map((e) => ({
47098
- ...e,
47099
- currency: e.currency ?? e.currencyCode ?? "",
47100
- depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
47101
- adapter: e.adapter ?? e.oracleAdapter ?? "",
47102
- spreadBps: e.spreadBps ?? e.floorSpreadBps ?? 0
47103
- })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47494
+ if (delegations.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
47495
+ break;
47496
+ }
47497
+ offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
47104
47498
  }
47499
+ return [...scopes.values()];
47105
47500
  }
47106
- };
47107
-
47108
- // src/indexer/intentVerification.ts
47109
- async function fetchFulfillmentAndPayment(client, intentHash) {
47110
- return client.query({
47111
- query: FULFILLMENT_AND_PAYMENT_QUERY,
47112
- variables: { intentHash }
47113
- });
47114
- }
47115
-
47116
- // src/client/Zkp2pClient.ts
47117
- init_contracts();
47118
-
47119
- // src/adapters/api.ts
47120
- init_errors();
47121
-
47122
- // src/utils/logger.ts
47123
- var currentLevel = "info";
47124
- function setLogLevel(level) {
47125
- currentLevel = level;
47126
- }
47127
- function shouldLog(level) {
47128
- switch (currentLevel) {
47129
- case "debug":
47130
- return true;
47131
- case "info":
47132
- return level !== "debug";
47133
- case "error":
47134
- return level === "error";
47135
- default:
47136
- return true;
47137
- }
47138
- }
47139
- var logger = {
47140
- debug: (...args) => {
47141
- if (shouldLog("debug")) {
47142
- console.log("[DEBUG]", ...args);
47143
- }
47144
- },
47145
- info: (...args) => {
47146
- if (shouldLog("info")) {
47147
- console.log("[INFO]", ...args);
47148
- }
47149
- },
47150
- warn: (...args) => {
47151
- if (shouldLog("info")) {
47152
- console.warn("[WARN]", ...args);
47501
+ async fetchHistoricalRateManagerDepositScopes(rateManagerId, rateManagerAddress) {
47502
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47503
+ const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
47504
+ const scopes = /* @__PURE__ */ new Map();
47505
+ const currentScopes = await this.fetchCurrentRateManagerDepositScopes(
47506
+ normalizedId,
47507
+ normalizedRateManagerAddress || void 0
47508
+ );
47509
+ for (const scope of currentScopes) {
47510
+ scopes.set(buildDepositScopeKey(scope), scope);
47153
47511
  }
47154
- },
47155
- error: (...args) => {
47156
- console.error("[ERROR]", ...args);
47157
- }
47158
- };
47159
-
47160
- // src/adapters/api.ts
47161
- function createHeaders(apiKey) {
47162
- const headers2 = { "Content-Type": "application/json" };
47163
- if (apiKey) headers2["x-api-key"] = apiKey;
47164
- return headers2;
47165
- }
47166
- function withApiBase(baseApiUrl) {
47167
- const trimmed = (baseApiUrl || "").trim();
47168
- let base2 = trimmed.replace(/\/+$/, "");
47169
- base2 = base2.replace(/\/v1$/i, "");
47170
- base2 = base2.replace(/\/v2$/i, "");
47171
- return base2;
47172
- }
47173
- async function apiFetch({
47174
- url,
47175
- method = "GET",
47176
- body,
47177
- apiKey,
47178
- timeoutMs,
47179
- retryCount = 3,
47180
- retryDelayMs = 1e3
47181
- }) {
47182
- const endpoint = url.replace(/^[^/]*\/\/[^/]*/, "");
47183
- return withRetry(
47184
- async () => {
47185
- let res;
47186
- try {
47187
- const options = {
47188
- method,
47189
- headers: createHeaders(apiKey)
47190
- };
47191
- if (body && method !== "GET") {
47192
- options.body = JSON.stringify(body);
47512
+ try {
47513
+ let offset = 0;
47514
+ for (; ; ) {
47515
+ const result = await this.client.query({
47516
+ query: RATE_MANAGER_ASSIGNMENT_EVENTS_QUERY,
47517
+ variables: {
47518
+ setWhere: {
47519
+ rateManagerId: { _eq: normalizedId },
47520
+ ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
47521
+ },
47522
+ clearedWhere: {
47523
+ rateManagerId: { _eq: normalizedId },
47524
+ ...normalizedRateManagerAddress ? { rateManager: { _eq: normalizedRateManagerAddress } } : {}
47525
+ },
47526
+ limit: RATE_MANAGER_HISTORY_PAGE_SIZE,
47527
+ offset
47528
+ }
47529
+ });
47530
+ const setEvents = result.EscrowV2_DepositRateManagerSet ?? [];
47531
+ const clearedEvents = result.EscrowV2_DepositRateManagerCleared ?? [];
47532
+ for (const event of [...setEvents, ...clearedEvents]) {
47533
+ const escrow = normalizeAddress3(event.escrow);
47534
+ const depositIdOnContract = event.depositIdOnContract?.toString() ?? "";
47535
+ if (!escrow || !depositIdOnContract) continue;
47536
+ const scope = { escrow, depositIdOnContract };
47537
+ scopes.set(buildDepositScopeKey(scope), scope);
47193
47538
  }
47194
- res = await fetch(url, options);
47195
- } catch (error) {
47196
- throw new exports.NetworkError("Failed to connect to API server", { endpoint, error });
47539
+ if (setEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE && clearedEvents.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
47540
+ break;
47541
+ }
47542
+ offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
47197
47543
  }
47198
- if (!res.ok) {
47199
- const errorText = await res.text();
47200
- throw parseAPIError(res, errorText);
47544
+ } catch (error) {
47545
+ if (!isSchemaCompatibilityError(error)) {
47546
+ throw error;
47201
47547
  }
47202
- return res.json();
47203
- },
47204
- retryCount,
47205
- retryDelayMs,
47206
- timeoutMs
47207
- );
47208
- }
47209
- function requireEscrowAddress(escrowAddress, endpoint) {
47210
- if (!escrowAddress) {
47211
- throw new exports.ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
47212
- }
47213
- return escrowAddress;
47214
- }
47215
- function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
47216
- const normalized = withApiBase(baseApiUrl).toLowerCase();
47217
- if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
47218
- return "PREPRODUCTION";
47219
- }
47220
- if (normalized.includes("staging") || normalized.includes("/staging/") || normalized.includes("localhost") || normalized.includes("127.0.0.1")) {
47221
- return "STAGING";
47222
- }
47223
- return "PRODUCTION";
47224
- }
47225
- async function withOptionalTimeout(promise, timeoutMs, endpoint) {
47226
- if (!timeoutMs || timeoutMs <= 0) return promise;
47227
- let timer;
47228
- try {
47229
- return await Promise.race([
47230
- promise,
47231
- new Promise((_, reject) => {
47232
- timer = setTimeout(() => {
47233
- reject(new exports.NetworkError("Request timed out", { endpoint }));
47234
- }, timeoutMs);
47235
- })
47236
- ]);
47237
- } finally {
47238
- if (timer) clearTimeout(timer);
47239
- }
47240
- }
47241
- function toDateFromUnixSeconds(value) {
47242
- if (!value) return void 0;
47243
- const numeric = Number(value);
47244
- if (!Number.isFinite(numeric) || numeric <= 0) return void 0;
47245
- return new Date(numeric * 1e3);
47246
- }
47247
- function toBigIntSafe(value) {
47248
- if (value === null || value === void 0) return 0n;
47249
- try {
47250
- return BigInt(value);
47251
- } catch {
47252
- return 0n;
47548
+ }
47549
+ return [...scopes.values()];
47253
47550
  }
47254
- }
47255
- function normalizeOwnerDepositsStatus(status) {
47256
- if (!status) return void 0;
47257
- if (status === "WITHDRAWN") return "CLOSED";
47258
- return status;
47259
- }
47260
- function buildLegacyVerifierCurrencies(deposit) {
47261
- const currenciesByMethod = /* @__PURE__ */ new Map();
47262
- for (const currency of deposit.currencies ?? []) {
47263
- const methodHash = currency.paymentMethodHash;
47264
- const resolvedConversionRate = currency.conversionRate ?? currency.minConversionRate;
47265
- if (resolvedConversionRate === null || resolvedConversionRate === void 0) {
47266
- logger.warn(
47267
- `[sdk] Skipping currency with missing conversion rate (deposit ${deposit.depositId}, currency ${currency.currencyCode})`
47551
+ async fetchRateManagers(pagination, filter) {
47552
+ const orderBy = pagination?.orderBy ?? "createdAt";
47553
+ const direction = pagination?.orderDirection === "asc" ? "asc" : "desc";
47554
+ const limit = pagination?.limit ?? DEFAULT_LIMIT2;
47555
+ const offset = pagination?.offset ?? 0;
47556
+ const where = this.buildWhere(filter);
47557
+ const aggregateWhere = this.buildAggregateWhere(filter);
47558
+ const legacyAggregateWhere = this.buildLegacyAggregateWhere(filter);
47559
+ if (isAggregateOrderField(orderBy)) {
47560
+ const result2 = await this.queryRateManagerList(
47561
+ {
47562
+ where,
47563
+ aggregateWhere,
47564
+ order_by: [{ createdAt: "desc" }]
47565
+ },
47566
+ {
47567
+ where,
47568
+ aggregateWhere: legacyAggregateWhere,
47569
+ order_by: [{ createdAt: "desc" }]
47570
+ }
47268
47571
  );
47269
- continue;
47572
+ const scopedRows = this.applyHookFilter(this.toRateManagerListItems(result2), filter?.hasHook);
47573
+ const sorted = scopedRows.sort((a, b) => {
47574
+ const av = orderBy === "currentDelegatedBalance" ? toSafeBigInt(a.aggregate?.currentDelegatedBalance) : toSafeBigInt(a.aggregate?.totalFilledVolume);
47575
+ const bv = orderBy === "currentDelegatedBalance" ? toSafeBigInt(b.aggregate?.currentDelegatedBalance) : toSafeBigInt(b.aggregate?.totalFilledVolume);
47576
+ const aggregateCmp = compareBigInt(av, bv, direction);
47577
+ if (aggregateCmp !== 0) return aggregateCmp;
47578
+ const createdAtCmp = compareBigInt(
47579
+ toSafeBigInt(a.manager.createdAt),
47580
+ toSafeBigInt(b.manager.createdAt),
47581
+ "desc"
47582
+ );
47583
+ if (createdAtCmp !== 0) return createdAtCmp;
47584
+ return a.manager.rateManagerId.localeCompare(b.manager.rateManagerId);
47585
+ });
47586
+ return sorted.slice(offset, offset + limit);
47270
47587
  }
47271
- const bucket = currenciesByMethod.get(methodHash) ?? [];
47272
- bucket.push({
47273
- currencyCode: currency.currencyCode,
47274
- conversionRate: resolvedConversionRate,
47275
- minConversionRate: currency.minConversionRate,
47276
- managerRate: currency.managerRate ?? null,
47277
- rateManagerId: currency.rateManagerId ?? null
47278
- });
47279
- currenciesByMethod.set(methodHash, bucket);
47588
+ const result = await this.queryRateManagerList(
47589
+ {
47590
+ where,
47591
+ aggregateWhere,
47592
+ order_by: this.buildOrderBy(pagination),
47593
+ limit,
47594
+ offset
47595
+ },
47596
+ {
47597
+ where,
47598
+ aggregateWhere: legacyAggregateWhere,
47599
+ order_by: this.buildOrderBy(pagination),
47600
+ limit,
47601
+ offset
47602
+ }
47603
+ );
47604
+ return this.applyHookFilter(this.toRateManagerListItems(result), filter?.hasHook);
47280
47605
  }
47281
- return currenciesByMethod;
47282
- }
47283
- function convertIndexerDepositToLegacyApiDeposit(deposit) {
47284
- const currenciesByMethod = buildLegacyVerifierCurrencies(deposit);
47285
- const verifiers = (deposit.paymentMethods ?? []).filter((paymentMethod) => paymentMethod.active !== false).map((paymentMethod) => ({
47286
- depositId: Number(deposit.depositId),
47287
- verifier: "",
47288
- methodHash: paymentMethod.paymentMethodHash,
47289
- intentGatingService: paymentMethod.intentGatingService,
47290
- payeeDetailsHash: paymentMethod.payeeDetailsHash,
47291
- data: "0x",
47292
- currencies: currenciesByMethod.get(paymentMethod.paymentMethodHash) ?? []
47293
- }));
47294
- const remainingDeposits = toBigIntSafe(deposit.remainingDeposits);
47295
- const outstandingIntentAmount = toBigIntSafe(deposit.outstandingIntentAmount);
47296
- const totalAmountTaken = toBigIntSafe(deposit.totalAmountTaken);
47297
- const totalWithdrawn = toBigIntSafe(deposit.totalWithdrawn);
47298
- const amount = remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn;
47299
- return {
47300
- id: Number(deposit.depositId),
47301
- depositor: deposit.depositor,
47302
- token: deposit.token,
47303
- amount: amount.toString(),
47304
- remainingDeposits: deposit.remainingDeposits,
47305
- intentAmountMin: deposit.intentAmountMin,
47306
- intentAmountMax: deposit.intentAmountMax,
47307
- acceptingIntents: deposit.acceptingIntents,
47308
- outstandingIntentAmount: deposit.outstandingIntentAmount,
47309
- availableLiquidity: deposit.remainingDeposits,
47310
- status: deposit.status,
47311
- totalIntents: deposit.totalIntents,
47312
- signaledIntents: deposit.signaledIntents,
47313
- fulfilledIntents: deposit.fulfilledIntents,
47314
- prunedIntents: deposit.prunedIntents,
47315
- totalAmountTaken: deposit.totalAmountTaken,
47316
- totalWithdrawn: deposit.totalWithdrawn,
47317
- successRateBps: deposit.successRateBps,
47318
- rateManagerId: deposit.rateManagerId ?? null,
47319
- vaultName: null,
47320
- rateManagerRegistry: null,
47321
- createdAt: toDateFromUnixSeconds(deposit.timestamp),
47322
- updatedAt: toDateFromUnixSeconds(deposit.updatedAt),
47323
- verifiers
47324
- };
47325
- }
47326
- async function apiPostDepositDetails(req, baseApiUrl, timeoutMs) {
47327
- return apiFetch({
47328
- url: `${withApiBase(baseApiUrl)}/v2/makers/create`,
47329
- method: "POST",
47330
- body: req,
47331
- timeoutMs
47332
- });
47333
- }
47334
- async function apiGetQuote(req, baseApiUrl, timeoutMs, apiKey) {
47335
- if (req.quotesToReturn !== void 0) {
47336
- if (!Number.isInteger(req.quotesToReturn) || req.quotesToReturn < 1) {
47337
- throw new exports.ValidationError("quotesToReturn must be a positive integer", "quotesToReturn");
47606
+ async fetchRateManagerDetail(rateManagerId, options) {
47607
+ if (!rateManagerId) return null;
47608
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47609
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
47610
+ const baseVariables = {
47611
+ managerWhere: {
47612
+ rateManagerId: { _eq: normalizedId },
47613
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47614
+ },
47615
+ rateWhere: {
47616
+ rateManagerId: { _eq: normalizedId },
47617
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47618
+ },
47619
+ aggregateWhere: {
47620
+ rateManagerId: { _eq: normalizedId },
47621
+ ...normalizedRateManagerAddress ? {
47622
+ id: {
47623
+ _ilike: buildRateManagerAddressScopedIdPattern(
47624
+ normalizedId,
47625
+ normalizedRateManagerAddress
47626
+ )
47627
+ }
47628
+ } : {}
47629
+ },
47630
+ statsWhere: {
47631
+ rateManagerId: { _eq: normalizedId },
47632
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47633
+ },
47634
+ delegationWhere: {
47635
+ rateManagerId: { _eq: normalizedId },
47636
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47637
+ },
47638
+ statsLimit: options?.statsLimit ?? 20
47639
+ };
47640
+ const legacyVariables = {
47641
+ ...baseVariables,
47642
+ floorWhere: {
47643
+ rateManagerId: { _eq: normalizedId },
47644
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47645
+ }
47646
+ };
47647
+ let managerRaw;
47648
+ let scopedRates = [];
47649
+ let scopedRecentStats = [];
47650
+ let scopedDelegations = [];
47651
+ let aggregate = null;
47652
+ try {
47653
+ const result = await this.client.query({
47654
+ query: RATE_MANAGER_DETAIL_QUERY,
47655
+ variables: baseVariables
47656
+ });
47657
+ managerRaw = result.RateManager?.[0];
47658
+ if (!managerRaw) return null;
47659
+ const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
47660
+ scopedRates = (result.RateManagerRate ?? []).filter(
47661
+ (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
47662
+ );
47663
+ scopedRecentStats = (result.ManagerStats ?? []).filter((stats) => {
47664
+ const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
47665
+ return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
47666
+ });
47667
+ scopedDelegations = (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation)).filter(
47668
+ (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
47669
+ );
47670
+ aggregate = (result.ManagerAggregateStats ?? []).find(
47671
+ (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
47672
+ ) ?? result.ManagerAggregateStats?.[0] ?? null;
47673
+ } catch (error) {
47674
+ if (!isSchemaCompatibilityError(error)) {
47675
+ throw error;
47676
+ }
47677
+ const legacyResult = await this.client.query({
47678
+ query: LEGACY_RATE_MANAGER_DETAIL_QUERY,
47679
+ variables: legacyVariables
47680
+ });
47681
+ managerRaw = legacyResult.RateManager?.[0];
47682
+ if (!managerRaw) return null;
47683
+ const scopedRateManagerAddress = normalizeAddress3(managerRaw.rateManagerAddress);
47684
+ scopedRates = (legacyResult.RateManagerRate ?? []).filter(
47685
+ (rate) => normalizeAddress3(rate.rateManagerAddress) === scopedRateManagerAddress
47686
+ );
47687
+ scopedRecentStats = (legacyResult.ManagerStats ?? []).filter((stats) => {
47688
+ const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
47689
+ return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
47690
+ });
47691
+ scopedDelegations = (legacyResult.RateManagerDelegation ?? []).filter(
47692
+ (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
47693
+ );
47694
+ aggregate = (legacyResult.ManagerAggregateStats ?? []).find(
47695
+ (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
47696
+ ) ?? legacyResult.ManagerAggregateStats?.[0] ?? null;
47338
47697
  }
47339
- }
47340
- if (!isValidHexAddress(req.user)) {
47341
- throw new exports.ValidationError("user must be a valid Ethereum address", "user");
47342
- }
47343
- if (!isValidHexAddress(req.recipient)) {
47344
- throw new exports.ValidationError("recipient must be a valid Ethereum address", "recipient");
47345
- }
47346
- if (!isValidHexAddress(req.destinationToken)) {
47347
- throw new exports.ValidationError(
47348
- "destinationToken must be a valid Ethereum address",
47349
- "destinationToken"
47350
- );
47351
- }
47352
- const isExactFiat = req.isExactFiat !== false;
47353
- const endpoint = isExactFiat ? "exact-fiat" : "exact-token";
47354
- let url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
47355
- if (req.quotesToReturn) url += `?quotesToReturn=${req.quotesToReturn}`;
47356
- const requestBody = {
47357
- ...req,
47358
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
47359
- amount: void 0,
47360
- isExactFiat: void 0,
47361
- quotesToReturn: void 0,
47362
- includePrivateOrderbooks: req.includePrivateOrderbooks
47363
- };
47364
- Object.keys(requestBody).forEach((k) => requestBody[k] === void 0 && delete requestBody[k]);
47365
- return apiFetch({
47366
- url,
47367
- method: "POST",
47368
- body: requestBody,
47369
- apiKey,
47370
- timeoutMs
47371
- });
47372
- }
47373
- async function apiGetQuotesBestByPlatform(req, baseApiUrl, timeoutMs, apiKey) {
47374
- const isExactFiat = req.isExactFiat !== false;
47375
- const endpoint = isExactFiat ? "best-by-platform" : "best-by-platform-exact-token";
47376
- const url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
47377
- const requestBody = {
47378
- ...req,
47379
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
47380
- amount: void 0,
47381
- isExactFiat: void 0,
47382
- referrerFeeConfig: void 0
47383
- };
47384
- Object.keys(requestBody).forEach(
47385
- (key) => requestBody[key] === void 0 && delete requestBody[key]
47386
- );
47387
- return apiFetch({
47388
- url,
47389
- method: "POST",
47390
- body: requestBody,
47391
- apiKey,
47392
- timeoutMs
47393
- });
47394
- }
47395
- async function apiGetPayeeDetails(req, baseApiUrl, timeoutMs) {
47396
- return apiFetch({
47397
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/${req.processorName}/${req.hashedOnchainId}`,
47398
- method: "GET",
47399
- timeoutMs
47400
- });
47401
- }
47402
- async function apiValidatePayeeDetails(req, baseApiUrl, timeoutMs) {
47403
- const data52 = await apiFetch({
47404
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/validate`,
47405
- method: "POST",
47406
- body: req,
47407
- timeoutMs
47408
- });
47409
- if (typeof data52?.responseObject === "boolean") {
47698
+ if (!managerRaw) return null;
47699
+ const manager = normalizeRateManagerEntity(managerRaw);
47410
47700
  return {
47411
- ...data52,
47412
- responseObject: { isValid: data52.responseObject }
47701
+ manager,
47702
+ rates: scopedRates,
47703
+ aggregate,
47704
+ recentStats: scopedRecentStats,
47705
+ delegations: scopedDelegations
47413
47706
  };
47414
47707
  }
47415
- return data52;
47416
- }
47417
- async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs) {
47418
- const escrowAddress = requireEscrowAddress(
47419
- req.escrowAddress,
47420
- "apiGetOwnerDeposits requires escrowAddress"
47421
- );
47422
- const indexerEndpoint = defaultIndexerEndpoint(inferIndexerEnvFromBaseApiUrl(baseApiUrl));
47423
- const indexerClient = new IndexerClient(indexerEndpoint, {
47424
- apiKey,
47425
- authorizationToken: authToken
47426
- });
47427
- const service = new IndexerDepositService(indexerClient);
47428
- const deposits = await withOptionalTimeout(
47429
- service.fetchDepositsWithRelations(
47430
- {
47431
- depositor: req.ownerAddress,
47432
- escrowAddress,
47433
- escrowAddresses: req.escrowAddresses?.length ? req.escrowAddresses : void 0,
47434
- status: normalizeOwnerDepositsStatus(req.status)
47708
+ async fetchRateManagerDelegations(rateManagerId, pagination) {
47709
+ if (!rateManagerId) return [];
47710
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47711
+ const normalizedRateManagerAddress = normalizeAddress3(pagination?.rateManagerAddress);
47712
+ const variables = {
47713
+ where: {
47714
+ rateManagerId: { _eq: normalizedId },
47715
+ ...normalizedRateManagerAddress ? { rateManagerAddress: { _eq: normalizedRateManagerAddress } } : {}
47435
47716
  },
47436
- void 0,
47437
- { includeIntents: false }
47438
- ),
47439
- timeoutMs,
47440
- indexerEndpoint
47441
- );
47442
- return {
47443
- success: true,
47444
- message: "ok",
47445
- responseObject: deposits.map(convertIndexerDepositToLegacyApiDeposit),
47446
- statusCode: 200
47447
- };
47448
- }
47449
- async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
47450
- const normalizedOwner = req.owner.toLowerCase();
47451
- const query = new URLSearchParams({
47452
- owner: normalizedOwner,
47453
- chainId: String(req.chainId)
47454
- });
47455
- const endpoint = `/v2/taker/tier?${query.toString()}`;
47456
- return apiFetch({
47457
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47458
- method: "GET",
47459
- timeoutMs
47460
- });
47461
- }
47462
- async function apiUploadSellerCredential(processorName, payeeDetails, bundle, baseApiUrl, timeoutMs) {
47463
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47464
- payeeDetails
47465
- )}/seller-credential`;
47466
- return apiFetch({
47467
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47468
- method: "POST",
47469
- body: bundle,
47470
- timeoutMs
47471
- });
47472
- }
47473
- async function apiUploadGoogleOAuthSellerCredential(processorName, payeeDetails, body, baseApiUrl, opts) {
47474
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47475
- payeeDetails
47476
- )}/seller-credential/google-oauth`;
47477
- return apiFetch({
47478
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47479
- method: "POST",
47480
- body,
47481
- timeoutMs: opts?.timeoutMs
47482
- });
47483
- }
47484
- async function apiGetSellerCredentialStatus(processorName, payeeDetails, baseApiUrl, timeoutMs) {
47485
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47486
- payeeDetails
47487
- )}/seller-credential/status`;
47488
- return apiFetch({
47489
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47490
- method: "GET",
47491
- timeoutMs
47492
- });
47493
- }
47494
- async function apiVerifySellerPayment(platform, req, baseApiUrl, timeoutMs, apiKey) {
47495
- const body = {
47496
- txId: req.txId,
47497
- chainId: req.chainId,
47498
- intent: req.intent,
47499
- ...req.metadata !== void 0 ? { metadata: req.metadata } : {}
47500
- };
47501
- return apiFetch({
47502
- url: `${withApiBase(baseApiUrl)}/v2/verify/seller/${encodeURIComponent(platform)}`,
47503
- method: "POST",
47504
- body,
47505
- apiKey,
47506
- timeoutMs
47507
- });
47508
- }
47509
- async function apiGetOrderbook(params, optsOrBaseApiUrl, timeoutMs) {
47510
- const opts = typeof optsOrBaseApiUrl === "string" ? {
47511
- baseApiUrl: optsOrBaseApiUrl,
47512
- timeoutMs
47513
- } : optsOrBaseApiUrl;
47514
- const query = new URLSearchParams();
47515
- Object.entries(params).forEach(([key, value]) => {
47516
- if (value === void 0 || value === null) return;
47517
- query.set(key, String(value));
47518
- });
47519
- const response = await apiFetch({
47520
- url: `${withApiBase(opts.baseApiUrl)}/v2/orderbook?${query.toString()}`,
47521
- method: "GET",
47522
- timeoutMs: opts.timeoutMs
47523
- });
47524
- return response.responseObject;
47525
- }
47526
- async function apiGetDepositBundle(params, optsOrBaseApiUrl, timeoutMs) {
47527
- const opts = typeof optsOrBaseApiUrl === "string" ? {
47528
- baseApiUrl: optsOrBaseApiUrl,
47529
- timeoutMs
47530
- } : optsOrBaseApiUrl;
47531
- const escrowAddress = requireEscrowAddress(
47532
- params.escrowAddress,
47533
- "apiGetDepositBundle requires escrowAddress"
47534
- );
47535
- const query = new URLSearchParams({ escrowAddress });
47536
- if (params.dailySnapshotLimit !== void 0) {
47537
- query.set("dailySnapshotLimit", String(params.dailySnapshotLimit));
47717
+ order_by: this.buildDelegationOrderBy(pagination),
47718
+ limit: pagination?.limit ?? DEFAULT_LIMIT2,
47719
+ offset: pagination?.offset ?? 0
47720
+ };
47721
+ try {
47722
+ const result = await this.client.query({
47723
+ query: RATE_MANAGER_DELEGATIONS_QUERY,
47724
+ variables
47725
+ });
47726
+ return (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation));
47727
+ } catch (error) {
47728
+ if (!isSchemaCompatibilityError(error)) {
47729
+ throw error;
47730
+ }
47731
+ const legacyResult = await this.client.query({
47732
+ query: LEGACY_RATE_MANAGER_DELEGATIONS_QUERY,
47733
+ variables: {
47734
+ ...variables,
47735
+ order_by: this.buildLegacyDelegationOrderBy(pagination)
47736
+ }
47737
+ });
47738
+ return legacyResult.RateManagerDelegation ?? [];
47739
+ }
47538
47740
  }
47539
- const response = await apiFetch({
47540
- url: `${withApiBase(opts.baseApiUrl)}/v2/deposits/${params.depositId}/bundle?${query.toString()}`,
47541
- method: "GET",
47542
- timeoutMs: opts.timeoutMs
47741
+ async fetchManagerDailySnapshots(rateManagerId, options) {
47742
+ if (!rateManagerId) return [];
47743
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47744
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
47745
+ try {
47746
+ const result = await this.client.query({
47747
+ query: MANAGER_DAILY_SNAPSHOTS_QUERY,
47748
+ variables: {
47749
+ where: {
47750
+ rateManagerId: { _eq: normalizedId },
47751
+ ...normalizedRateManagerAddress ? {
47752
+ id: {
47753
+ _ilike: buildRateManagerScopedIdPattern(
47754
+ normalizedId,
47755
+ normalizedRateManagerAddress
47756
+ )
47757
+ }
47758
+ } : {}
47759
+ },
47760
+ order_by: [{ dayTimestamp: "asc" }],
47761
+ limit: options?.limit ?? 365
47762
+ }
47763
+ });
47764
+ return result.ManagerDailySnapshot ?? [];
47765
+ } catch (error) {
47766
+ if (!isSchemaCompatibilityError(error)) {
47767
+ throw error;
47768
+ }
47769
+ return [];
47770
+ }
47771
+ }
47772
+ async fetchDelegationForDeposit(depositId, options) {
47773
+ if (!depositId) return null;
47774
+ const normalizedDepositId = normalizeCompositeDepositId(depositId, options?.escrowAddress);
47775
+ try {
47776
+ const result = await this.client.query({
47777
+ query: DEPOSIT_DELEGATION_QUERY,
47778
+ variables: {
47779
+ depositId: normalizedDepositId
47780
+ }
47781
+ });
47782
+ const delegationDeposit = result.Deposit?.[0];
47783
+ if (!delegationDeposit) {
47784
+ return null;
47785
+ }
47786
+ return toDelegationEntityFromDeposit(delegationDeposit) ?? null;
47787
+ } catch (error) {
47788
+ if (!isSchemaCompatibilityError(error)) {
47789
+ throw error;
47790
+ }
47791
+ const legacyResult = await this.client.query({
47792
+ query: LEGACY_DEPOSIT_DELEGATION_QUERY,
47793
+ variables: {
47794
+ depositId: normalizedDepositId
47795
+ }
47796
+ });
47797
+ return legacyResult.RateManagerDelegation?.[0] ?? null;
47798
+ }
47799
+ }
47800
+ async fetchManualRateUpdates(rateManagerId, options) {
47801
+ if (!rateManagerId) return [];
47802
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47803
+ try {
47804
+ const result = await this.client.query({
47805
+ query: MANUAL_RATE_UPDATES_QUERY,
47806
+ variables: {
47807
+ where: {
47808
+ rateManagerId: { _eq: normalizedId }
47809
+ },
47810
+ order_by: [{ id: "desc" }],
47811
+ limit: options?.limit ?? 100
47812
+ }
47813
+ });
47814
+ return (result.RateManagerV1_RateManagerRateUpdated ?? []).map((e) => ({
47815
+ ...e,
47816
+ currency: e.currency ?? e.currencyCode ?? "",
47817
+ minRate: e.minRate ?? e.rate ?? "0"
47818
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47819
+ } catch (error) {
47820
+ if (!isSchemaCompatibilityError(error)) {
47821
+ throw error;
47822
+ }
47823
+ return [];
47824
+ }
47825
+ }
47826
+ async fetchOracleConfigUpdates(rateManagerId, options) {
47827
+ if (!rateManagerId) return [];
47828
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47829
+ const normalizedRateManagerAddress = normalizeAddress3(options?.rateManagerAddress);
47830
+ const limit = options?.limit ?? 100;
47831
+ try {
47832
+ const depositScopes = await this.fetchHistoricalRateManagerDepositScopes(
47833
+ normalizedId,
47834
+ normalizedRateManagerAddress || void 0
47835
+ );
47836
+ if (!depositScopes.length) {
47837
+ return [];
47838
+ }
47839
+ const scopedKeys = new Set(depositScopes.map((scope) => buildDepositScopeKey(scope)));
47840
+ const result = await this.client.query({
47841
+ query: ORACLE_CONFIG_UPDATES_QUERY,
47842
+ variables: {
47843
+ where: {
47844
+ _or: depositScopes.map((scope) => ({
47845
+ _and: [
47846
+ { depositId: { _eq: scope.depositIdOnContract } },
47847
+ { escrow: { _eq: scope.escrow } }
47848
+ ]
47849
+ }))
47850
+ },
47851
+ order_by: [{ id: "desc" }],
47852
+ limit
47853
+ }
47854
+ });
47855
+ return (result.EscrowV2_DepositOracleRateConfigSet ?? []).filter((event) => {
47856
+ const escrow = normalizeAddress3(event.escrow);
47857
+ const depositIdOnContract = event.depositIdOnContract ?? event.depositId?.toString?.() ?? "";
47858
+ if (!escrow || !depositIdOnContract) return false;
47859
+ return scopedKeys.has(
47860
+ buildDepositScopeKey({
47861
+ escrow,
47862
+ depositIdOnContract
47863
+ })
47864
+ );
47865
+ }).map((e) => ({
47866
+ ...e,
47867
+ rateManagerId: normalizedId,
47868
+ escrow: normalizeAddress3(e.escrow) || void 0,
47869
+ currency: e.currency ?? e.currencyCode ?? "",
47870
+ depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
47871
+ adapter: e.adapter ?? "",
47872
+ spreadBps: e.spreadBps ?? 0
47873
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47874
+ } catch (error) {
47875
+ if (isSchemaCompatibilityError(error)) ; else {
47876
+ throw error;
47877
+ }
47878
+ const legacyResult = await this.client.query({
47879
+ query: LEGACY_ORACLE_CONFIG_UPDATES_QUERY,
47880
+ variables: {
47881
+ where: {
47882
+ rateManagerId: { _eq: normalizedId }
47883
+ },
47884
+ order_by: [{ id: "desc" }],
47885
+ limit
47886
+ }
47887
+ });
47888
+ return (legacyResult.RateManagerV1_DepositorFloorSet ?? []).map((e) => ({
47889
+ ...e,
47890
+ currency: e.currency ?? e.currencyCode ?? "",
47891
+ depositIdOnContract: e.depositIdOnContract ?? e.depositId ?? "",
47892
+ adapter: e.adapter ?? e.oracleAdapter ?? "",
47893
+ spreadBps: e.spreadBps ?? e.floorSpreadBps ?? 0
47894
+ })).sort((a, b) => compareEventCursorIdsByRecency(a.id, b.id));
47895
+ }
47896
+ }
47897
+ };
47898
+
47899
+ // src/indexer/intentVerification.ts
47900
+ async function fetchFulfillmentAndPayment(client, intentHash) {
47901
+ return client.query({
47902
+ query: FULFILLMENT_AND_PAYMENT_QUERY,
47903
+ variables: { intentHash }
47543
47904
  });
47544
- return response.responseObject;
47545
47905
  }
47546
47906
 
47907
+ // src/client/Zkp2pClient.ts
47908
+ init_contracts();
47909
+
47547
47910
  // src/sellerCredentials.ts
47548
47911
  function normalizeBaseApiUrl(value) {
47549
47912
  return (value?.trim().replace(/\/+$/u, "") || DEFAULT_BASE_API_URL).replace(/\/v1$/u, "");
@@ -47754,9 +48117,7 @@ function isObjectRecord(value) {
47754
48117
  return true;
47755
48118
  }
47756
48119
  function normalizeTelegramUsername(value) {
47757
- if (typeof value !== "string") {
47758
- return value === null ? null : null;
47759
- }
48120
+ if (typeof value !== "string") return null;
47760
48121
  const normalized = value.trim();
47761
48122
  return normalized.length > 0 ? normalized : null;
47762
48123
  }
@@ -48050,7 +48411,7 @@ var Zkp2pClient = class {
48050
48411
  () => ({
48051
48412
  address: this.rateManagerControllerAddress,
48052
48413
  abi: this.rateManagerControllerAbi,
48053
- label: "Rate manager controller (staging only)"
48414
+ label: "Rate manager controller"
48054
48415
  }),
48055
48416
  "setDepositRateManager",
48056
48417
  (params) => {
@@ -48064,7 +48425,7 @@ var Zkp2pClient = class {
48064
48425
  () => ({
48065
48426
  address: this.rateManagerControllerAddress,
48066
48427
  abi: this.rateManagerControllerAbi,
48067
- label: "Rate manager controller (staging only)"
48428
+ label: "Rate manager controller"
48068
48429
  }),
48069
48430
  "clearDepositRateManager",
48070
48431
  (params) => {
@@ -48150,7 +48511,7 @@ var Zkp2pClient = class {
48150
48511
  () => ({
48151
48512
  address: this.rateManagerRegistryAddress,
48152
48513
  abi: this.rateManagerRegistryAbi,
48153
- label: "Rate manager registry (staging only)"
48514
+ label: "Rate manager registry"
48154
48515
  }),
48155
48516
  "setFee",
48156
48517
  (params) => {
@@ -48635,6 +48996,10 @@ var Zkp2pClient = class {
48635
48996
  const prepared = await this.prepareFulfillIntent(params);
48636
48997
  const txHash = await this.executePreparedTransaction(prepared, params.txOverrides);
48637
48998
  params?.callbacks?.onTxSent?.(txHash);
48999
+ if (params?.callbacks?.onTxMined) {
49000
+ await this.publicClient.waitForTransactionReceipt({ hash: txHash });
49001
+ params.callbacks.onTxMined(txHash);
49002
+ }
48638
49003
  return txHash;
48639
49004
  },
48640
49005
  {
@@ -48653,7 +49018,7 @@ var Zkp2pClient = class {
48653
49018
  this.walletClient = opts.walletClient;
48654
49019
  this.chainId = opts.chainId;
48655
49020
  this.runtimeEnv = opts.runtimeEnv ?? "production";
48656
- const inferredRpc = this.walletClient?.chain?.rpcUrls?.default?.http?.[0];
49021
+ const inferredRpc = this.walletClient.chain?.rpcUrls?.default?.http?.[0];
48657
49022
  const defaultRpcUrls = {
48658
49023
  [chains.base.id]: "https://mainnet.base.org",
48659
49024
  [chains.hardhat.id]: "http://127.0.0.1:8545"
@@ -48666,7 +49031,7 @@ var Zkp2pClient = class {
48666
49031
  const selectedChain = chainMap[this.chainId];
48667
49032
  this.publicClient = viem.createPublicClient({
48668
49033
  chain: selectedChain,
48669
- transport: viem.http(rpc, { batch: false })
49034
+ transport: opts.rpcTransport ?? viem.http(rpc, { batch: false })
48670
49035
  });
48671
49036
  const { addresses, abis } = getContracts(this.chainId, this.runtimeEnv);
48672
49037
  const toAddress = (value) => this.isValidHexAddress(value) ? value : void 0;
@@ -48684,12 +49049,10 @@ var Zkp2pClient = class {
48684
49049
  };
48685
49050
  this.escrowV2Address = toAddress(addresses.escrowV2 ?? addresses.escrow);
48686
49051
  this.escrowV2Abi = abis.escrowV2 ?? abis.escrow;
48687
- this.orchestratorV2Address = toAddress(
48688
- addresses.orchestratorV2 ?? addresses.orchestrator
48689
- );
49052
+ this.orchestratorV2Address = toAddress(addresses.orchestratorV2 ?? addresses.orchestrator);
48690
49053
  this.orchestratorV2Abi = abis.orchestratorV2 ?? abis.orchestrator;
48691
- const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter(Boolean);
48692
- const configuredOrchestratorAddresses = (addresses.orchestratorAddresses ?? []).map((value) => toAddress(value)).filter(Boolean);
49054
+ const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
49055
+ const configuredOrchestratorAddresses = (addresses.orchestratorAddresses ?? []).map((value) => toAddress(value)).filter((value) => Boolean(value));
48693
49056
  this.escrowAddresses = uniqAddresses([
48694
49057
  this.escrowV2Address ?? toAddress(addresses.escrow),
48695
49058
  ...configuredEscrowAddresses
@@ -48755,8 +49118,7 @@ var Zkp2pClient = class {
48755
49118
  orchestratorV2Abi: this.orchestratorV2Abi,
48756
49119
  orchestratorAddresses: this.orchestratorAddresses
48757
49120
  });
48758
- const maybeUsdc = addresses.usdc;
48759
- if (maybeUsdc) this._usdcAddress = maybeUsdc;
49121
+ if (addresses.usdc) this._usdcAddress = addresses.usdc;
48760
49122
  const runtimeToIndexerEnv = {
48761
49123
  production: "PRODUCTION",
48762
49124
  preproduction: "PREPRODUCTION",
@@ -48773,6 +49135,7 @@ var Zkp2pClient = class {
48773
49135
  this.baseApiUrl = opts.baseApiUrl;
48774
49136
  this.apiKey = opts.apiKey;
48775
49137
  this.authorizationToken = opts.authorizationToken;
49138
+ this.getAuthorizationToken = opts.getAuthorizationToken;
48776
49139
  this.apiTimeoutMs = opts.timeouts?.api ?? 15e3;
48777
49140
  this._pvReader = new ProtocolViewerReader({
48778
49141
  getPublicClient: () => this.publicClient,
@@ -48831,6 +49194,15 @@ var Zkp2pClient = class {
48831
49194
  getPvIntent: (intentHash) => this.getPvIntent(intentHash)
48832
49195
  }
48833
49196
  });
49197
+ this._referralOps = new ReferralAccountOperations({
49198
+ getWalletClient: () => this.walletClient,
49199
+ getChainId: () => this.chainId,
49200
+ getRuntimeEnv: () => this.runtimeEnv,
49201
+ getBaseApiUrl: () => this.baseApiUrl,
49202
+ getApiTimeoutMs: () => this.apiTimeoutMs,
49203
+ getAuthorizationToken: () => this.authorizationToken,
49204
+ getAuthorizationTokenProvider: () => this.getAuthorizationToken
49205
+ });
48834
49206
  }
48835
49207
  isValidHexAddress(addr) {
48836
49208
  return isValidHexAddress(addr);
@@ -48868,12 +49240,6 @@ var Zkp2pClient = class {
48868
49240
  `attestationServiceUrl is required when baseApiUrl is not a supported zkp2p API host: ${baseApiUrl}`
48869
49241
  );
48870
49242
  }
48871
- normalizeOracleRateConfig(config) {
48872
- return normalizeOracleRateConfig(config);
48873
- }
48874
- escrowCurrencyHasOracleConfig(abi) {
48875
- return escrowCurrencyHasOracleConfig(abi);
48876
- }
48877
49243
  /**
48878
49244
  * Normalizes currency tuples by appending an empty `oracleRateConfig` when the ABI
48879
49245
  * requires it and the caller hasn't provided one.
@@ -48886,21 +49252,9 @@ var Zkp2pClient = class {
48886
49252
  escrowAddress: params?.escrowAddress
48887
49253
  });
48888
49254
  }
48889
- parseManagerFeeFromRead(result) {
48890
- return parseManagerFeeFromRead(result);
48891
- }
48892
- getAbiFunction(abi, ...names) {
48893
- return getAbiFunction(abi, ...names);
48894
- }
48895
49255
  resolveAbiFunctionName(abi, names) {
48896
49256
  return resolveAbiFunctionName(abi, names);
48897
49257
  }
48898
- abiTupleHasComponent(abi, functionName, componentName) {
48899
- return abiTupleHasComponent(abi, functionName, componentName);
48900
- }
48901
- abiFunctionHasInput(abi, functionName, inputName) {
48902
- return abiFunctionHasInput(abi, functionName, inputName);
48903
- }
48904
49258
  resolveEscrowAddressOrThrow(escrowAddress, depositId, _methodName) {
48905
49259
  const resolved = escrowAddress ?? this.parseEscrowAddressFromCompositeDepositId(depositId);
48906
49260
  if (resolved) return resolved;
@@ -49026,7 +49380,7 @@ var Zkp2pClient = class {
49026
49380
  async lookupIntentEscrowOnchain(intentHash) {
49027
49381
  try {
49028
49382
  const view = await this.getPvIntent(intentHash);
49029
- return this.normalizeAddress(view?.intent?.escrow);
49383
+ return this.normalizeAddress(view.intent.escrow);
49030
49384
  } catch {
49031
49385
  return void 0;
49032
49386
  }
@@ -49091,6 +49445,15 @@ var Zkp2pClient = class {
49091
49445
  if (fallback) return fallback;
49092
49446
  throw new Error("Orchestrator not available");
49093
49447
  }
49448
+ /**
49449
+ * Spread helper for viem requests.
49450
+ * justified: TxOverrides mixes legacy gasPrice with EIP-1559 fee fields, which
49451
+ * viem's discriminated request unions reject; keep the suppression in one place.
49452
+ */
49453
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
49454
+ applyTxOverrides(overrides) {
49455
+ return overrides;
49456
+ }
49094
49457
  /**
49095
49458
  * Simulate a contract call (validation only) and send with ERC-8021 attribution.
49096
49459
  * Referrer codes are stripped from overrides for simulation and appended to calldata.
@@ -49103,7 +49466,7 @@ var Zkp2pClient = class {
49103
49466
  functionName: opts.functionName,
49104
49467
  args: opts.args ?? [],
49105
49468
  account: this.walletClient.account,
49106
- ...txOverrides
49469
+ ...this.applyTxOverrides(txOverrides)
49107
49470
  });
49108
49471
  return sendTransactionWithAttribution(
49109
49472
  this.walletClient,
@@ -49130,7 +49493,7 @@ var Zkp2pClient = class {
49130
49493
  functionName: prepared.functionName,
49131
49494
  args: prepared.args,
49132
49495
  account: this.walletClient.account,
49133
- ...overrides
49496
+ ...this.applyTxOverrides(overrides)
49134
49497
  });
49135
49498
  return this.walletClient.sendTransaction({
49136
49499
  to: prepared.to,
@@ -49138,7 +49501,7 @@ var Zkp2pClient = class {
49138
49501
  value: prepared.value,
49139
49502
  account: this.walletClient.account,
49140
49503
  chain: this.walletClient.chain,
49141
- ...overrides
49504
+ ...this.applyTxOverrides(overrides)
49142
49505
  });
49143
49506
  }
49144
49507
  prepareEscrowTransaction(opts) {
@@ -49744,20 +50107,18 @@ var Zkp2pClient = class {
49744
50107
  if (params.processorNames.length !== payeeData.length) {
49745
50108
  throw new Error("processorNames and payeeData length mismatch");
49746
50109
  }
49747
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
50110
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
49748
50111
  const depositDetails = params.processorNames.map(
49749
50112
  (processorName, index) => toPostDepositDetailsRequest(processorName, payeeData[index], index)
49750
50113
  );
49751
50114
  const apiResponses = await Promise.all(
49752
50115
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
49753
50116
  );
49754
- if (!apiResponses.every((r) => r?.success)) {
49755
- const failed = apiResponses.find((r) => !r?.success);
50117
+ if (!apiResponses.every((r) => r.success)) {
50118
+ const failed = apiResponses.find((r) => !r.success);
49756
50119
  throw new Error(failed?.message || "Failed to register payee details");
49757
50120
  }
49758
- const hashedOnchainIds = apiResponses.map(
49759
- (r) => r.responseObject?.hashedOnchainId
49760
- );
50121
+ const hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
49761
50122
  return { depositDetails, hashedOnchainIds };
49762
50123
  }
49763
50124
  /**
@@ -49881,17 +50242,15 @@ var Zkp2pClient = class {
49881
50242
  }
49882
50243
  hashedOnchainIds = payeeDetailsHashes;
49883
50244
  } else {
49884
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
50245
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
49885
50246
  const apiResponses = await Promise.all(
49886
50247
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
49887
50248
  );
49888
- if (!apiResponses.every((r) => r?.success)) {
49889
- const failed = apiResponses.find((r) => !r?.success);
50249
+ if (!apiResponses.every((r) => r.success)) {
50250
+ const failed = apiResponses.find((r) => !r.success);
49890
50251
  throw new Error(failed?.message || "Failed to create deposit details");
49891
50252
  }
49892
- hashedOnchainIds = apiResponses.map(
49893
- (r) => r.responseObject?.hashedOnchainId
49894
- );
50253
+ hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
49895
50254
  }
49896
50255
  paymentMethodData = hashedOnchainIds.map((hid) => ({
49897
50256
  intentGatingService,
@@ -49913,10 +50272,10 @@ var Zkp2pClient = class {
49913
50272
  }
49914
50273
  });
49915
50274
  const { mapConversionRatesToOnchainMinRate: mapConversionRatesToOnchainMinRate2 } = await Promise.resolve().then(() => (init_currency(), currency_exports));
49916
- const normalized = params.conversionRates.map(
49917
- (group) => group.map((r) => ({ currency: r.currency, conversionRate: r.conversionRate }))
50275
+ currencies = mapConversionRatesToOnchainMinRate2(
50276
+ params.conversionRates,
50277
+ paymentMethods.length
49918
50278
  );
49919
- currencies = mapConversionRatesToOnchainMinRate2(normalized, paymentMethods.length);
49920
50279
  }
49921
50280
  const escrowContext = this.resolveEscrowContext({
49922
50281
  escrowAddress: params.escrowAddress
@@ -50008,9 +50367,6 @@ var Zkp2pClient = class {
50008
50367
  async prepareFulfillIntent(params) {
50009
50368
  return this._intentOps.prepareFulfillIntent(params);
50010
50369
  }
50011
- defaultAttestationService() {
50012
- return this._intentOps.defaultAttestationService();
50013
- }
50014
50370
  // ───────────────────────────────────────────────────────────────────────────
50015
50371
  // SUPPORTING: QUOTES API
50016
50372
  // (Used by frontends to find available liquidity)
@@ -50058,7 +50414,7 @@ var Zkp2pClient = class {
50058
50414
  */
50059
50415
  async getQuote(req, opts) {
50060
50416
  const referrerFeeConfig = assertValidReferrerFeeConfig(req.referrerFeeConfig, "getQuote");
50061
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50417
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50062
50418
  /\/$/,
50063
50419
  ""
50064
50420
  );
@@ -50073,9 +50429,8 @@ var Zkp2pClient = class {
50073
50429
  const quote = await apiGetQuote(reqWithEscrow, baseApiUrl, timeoutMs, this.apiKey);
50074
50430
  const quotes = quote?.responseObject?.quotes ?? [];
50075
50431
  for (const q of quotes) {
50076
- const maker = q?.maker;
50077
- const payeeData = normalizeQuotePayeeData(maker);
50078
- if (payeeData && typeof q === "object") {
50432
+ const payeeData = normalizeQuotePayeeData(q.maker);
50433
+ if (payeeData) {
50079
50434
  q.payeeData = payeeData;
50080
50435
  }
50081
50436
  }
@@ -50096,7 +50451,7 @@ var Zkp2pClient = class {
50096
50451
  req.referrerFeeConfig,
50097
50452
  "getQuotesBestByPlatform"
50098
50453
  );
50099
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50454
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50100
50455
  /\/$/,
50101
50456
  ""
50102
50457
  );
@@ -50145,13 +50500,71 @@ var Zkp2pClient = class {
50145
50500
  * @returns Taker tier response
50146
50501
  */
50147
50502
  async getTakerTier(req, opts) {
50148
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50503
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50149
50504
  /\/$/,
50150
50505
  ""
50151
50506
  );
50152
50507
  const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
50153
50508
  return apiGetTakerTier(req, baseApiUrl, timeoutMs);
50154
50509
  }
50510
+ /**
50511
+ * Fetch a referral dashboard. Pass `address` for a public wallet-keyed read;
50512
+ * omit it to use the authenticated caller mode.
50513
+ */
50514
+ async getReferralDashboard(opts) {
50515
+ return this._referralOps.getReferralDashboard(opts);
50516
+ }
50517
+ /**
50518
+ * Fetch referral earnings. Pass `address` for a public wallet-keyed read;
50519
+ * omit it to use the authenticated caller mode.
50520
+ */
50521
+ async getReferralEarnings(opts) {
50522
+ return this._referralOps.getReferralEarnings(opts);
50523
+ }
50524
+ /**
50525
+ * Publicly look up a referral code's owner wallet and active status.
50526
+ */
50527
+ async lookupReferralCode(code, opts) {
50528
+ return this._referralOps.lookupReferralCode(code, opts);
50529
+ }
50530
+ /**
50531
+ * Create or fetch the authenticated caller's referral code with bearer auth.
50532
+ */
50533
+ async createReferralCode(opts) {
50534
+ return this._referralOps.createReferralCode(opts);
50535
+ }
50536
+ /**
50537
+ * Create or fetch the wallet's referral code with EIP-712 signature auth.
50538
+ */
50539
+ async createReferralCodeWithSignature(opts) {
50540
+ return this._referralOps.createReferralCodeWithSignature(opts);
50541
+ }
50542
+ /**
50543
+ * Apply another user's referral code with bearer auth.
50544
+ */
50545
+ async redeemReferralCode(code, opts) {
50546
+ return this._referralOps.redeemReferralCode(code, opts);
50547
+ }
50548
+ /**
50549
+ * Apply another user's referral code with EIP-712 signature auth. If
50550
+ * `referrerWalletAddress` is omitted, the SDK looks up the code first and signs
50551
+ * the current owner wallet into the redeem payload.
50552
+ */
50553
+ async redeemReferralCodeWithSignature(code, opts) {
50554
+ return this._referralOps.redeemReferralCodeWithSignature(code, opts);
50555
+ }
50556
+ /**
50557
+ * Customize the authenticated caller's referral code with bearer auth.
50558
+ */
50559
+ async updateReferralCode(code, opts) {
50560
+ return this._referralOps.updateReferralCode(code, opts);
50561
+ }
50562
+ /**
50563
+ * Customize the wallet's referral code with EIP-712 signature auth.
50564
+ */
50565
+ async updateReferralCodeWithSignature(code, opts) {
50566
+ return this._referralOps.updateReferralCodeWithSignature(code, opts);
50567
+ }
50155
50568
  /**
50156
50569
  * The signed `credentialValidatedAt` field is an upload-time freshness witness minted by
50157
50570
  * attestation-service. `credentialExpiresAt` carries an upstream session expiry hint when one
@@ -50172,44 +50585,14 @@ var Zkp2pClient = class {
50172
50585
  const attestationServiceUrl = this.stripTrailingSlash(
50173
50586
  opts?.attestationServiceUrl ?? this.defaultAttestationServiceForBaseApiUrl(baseApiUrl)
50174
50587
  );
50175
- const createBundle = (uploadPayload) => {
50176
- const requestOptions = opts?.attestationServiceFallbackUrls ? { fallbackUrls: opts.attestationServiceFallbackUrls } : void 0;
50177
- if (opts?.attestationRuntime && requestOptions) {
50178
- return apiCreateSellerCredentialBundle(
50179
- uploadPayload,
50180
- attestationServiceUrl,
50181
- params.platform,
50182
- timeoutMs,
50183
- opts.attestationRuntime,
50184
- requestOptions
50185
- );
50186
- }
50187
- if (opts?.attestationRuntime) {
50188
- return apiCreateSellerCredentialBundle(
50189
- uploadPayload,
50190
- attestationServiceUrl,
50191
- params.platform,
50192
- timeoutMs,
50193
- opts.attestationRuntime
50194
- );
50195
- }
50196
- if (requestOptions) {
50197
- return apiCreateSellerCredentialBundle(
50198
- uploadPayload,
50199
- attestationServiceUrl,
50200
- params.platform,
50201
- timeoutMs,
50202
- void 0,
50203
- requestOptions
50204
- );
50205
- }
50206
- return apiCreateSellerCredentialBundle(
50207
- uploadPayload,
50208
- attestationServiceUrl,
50209
- params.platform,
50210
- timeoutMs
50211
- );
50212
- };
50588
+ const createBundle = (uploadPayload) => apiCreateSellerCredentialBundle(
50589
+ uploadPayload,
50590
+ attestationServiceUrl,
50591
+ params.platform,
50592
+ timeoutMs,
50593
+ opts?.attestationRuntime,
50594
+ opts?.attestationServiceFallbackUrls ? { fallbackUrls: opts.attestationServiceFallbackUrls } : void 0
50595
+ );
50213
50596
  if (params.platform === "wise") {
50214
50597
  const bundleResponse2 = await createBundle({
50215
50598
  sessionMaterial: params.sessionMaterial
@@ -50355,19 +50738,6 @@ var Zkp2pClient = class {
50355
50738
  protocolViewerFunctionInputCount(functionName) {
50356
50739
  return this._pvReader.protocolViewerFunctionInputCount(functionName);
50357
50740
  }
50358
- /**
50359
- * Returns the input count for a function on a specific PV entry's ABI.
50360
- * Used to branch between 1-input (V1) and 2-input (V2) PV call signatures.
50361
- */
50362
- pvEntryFunctionInputCount(entry, functionName) {
50363
- return this._pvReader.pvEntryFunctionInputCount(entry, functionName);
50364
- }
50365
- isZeroAddressValue(value) {
50366
- return this._pvReader.isZeroAddressValue(value);
50367
- }
50368
- toBigIntOrZero(value, fieldName = "numeric field") {
50369
- return this._pvReader.toBigIntOrZero(value, fieldName);
50370
- }
50371
50741
  buildProtocolViewerContexts(options) {
50372
50742
  return this._pvReader.buildProtocolViewerContexts(options);
50373
50743
  }
@@ -50380,9 +50750,6 @@ var Zkp2pClient = class {
50380
50750
  buildDepositViewFromEscrowDeposit(rawDeposit, depositId) {
50381
50751
  return this._pvReader.buildDepositViewFromEscrowDeposit(rawDeposit, depositId);
50382
50752
  }
50383
- convertIndexerDepositToPvView(deposit) {
50384
- return this._pvReader.convertIndexerDepositToPvView(deposit);
50385
- }
50386
50753
  async getPvAccountDepositsFromIndexer(owner) {
50387
50754
  return this._pvReader.getPvAccountDepositsFromIndexer(owner);
50388
50755
  }
@@ -50629,6 +50996,8 @@ exports.PLATFORM_METADATA = PLATFORM_METADATA;
50629
50996
  exports.PYTH_CONTRACT_BASE = PYTH_CONTRACT_BASE;
50630
50997
  exports.PYTH_ORACLE_ADAPTER = PYTH_ORACLE_ADAPTER;
50631
50998
  exports.PYTH_ORACLE_FEEDS = PYTH_ORACLE_FEEDS;
50999
+ exports.REFERRAL_SIGNATURE_DOMAIN = REFERRAL_SIGNATURE_DOMAIN;
51000
+ exports.REFERRAL_SIGNATURE_TYPES = REFERRAL_SIGNATURE_TYPES;
50632
51001
  exports.SPREAD_ORACLE_FEEDS = SPREAD_ORACLE_FEEDS;
50633
51002
  exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS;
50634
51003
  exports.TAKER_TIER_CAPS = TAKER_TIER_CAPS;
@@ -50640,15 +51009,21 @@ exports.ZERO_RATE_MANAGER_ID = ZERO_RATE_MANAGER_ID;
50640
51009
  exports.ZKP2P_ANDROID_REFERRER = ZKP2P_ANDROID_REFERRER;
50641
51010
  exports.ZKP2P_IOS_REFERRER = ZKP2P_IOS_REFERRER;
50642
51011
  exports.Zkp2pClient = Zkp2pClient;
51012
+ exports.apiCreateReferralCode = apiCreateReferralCode;
50643
51013
  exports.apiCreateSellerCredentialBundle = apiCreateSellerCredentialBundle;
50644
51014
  exports.apiGetDepositBundle = apiGetDepositBundle;
50645
51015
  exports.apiGetOrderbook = apiGetOrderbook;
50646
51016
  exports.apiGetOwnerDeposits = apiGetOwnerDeposits;
50647
51017
  exports.apiGetPayeeDetails = apiGetPayeeDetails;
50648
51018
  exports.apiGetQuotesBestByPlatform = apiGetQuotesBestByPlatform;
51019
+ exports.apiGetReferralDashboard = apiGetReferralDashboard;
51020
+ exports.apiGetReferralEarnings = apiGetReferralEarnings;
50649
51021
  exports.apiGetTakerTier = apiGetTakerTier;
51022
+ exports.apiLookupReferralCode = apiLookupReferralCode;
50650
51023
  exports.apiPostDepositDetails = apiPostDepositDetails;
51024
+ exports.apiRedeemReferralCode = apiRedeemReferralCode;
50651
51025
  exports.apiRequestIdentityAttestation = apiRequestIdentityAttestation;
51026
+ exports.apiUpdateReferralCode = apiUpdateReferralCode;
50652
51027
  exports.apiUploadGoogleOAuthSellerCredential = apiUploadGoogleOAuthSellerCredential;
50653
51028
  exports.apiUploadSellerCredentialBundle = apiUploadSellerCredentialBundle;
50654
51029
  exports.apiValidatePayeeDetails = apiValidatePayeeDetails;
@@ -50687,12 +51062,14 @@ exports.getSpreadOracleConfig = getSpreadOracleConfig;
50687
51062
  exports.getTakerTierFeeDiscountBps = getTakerTierFeeDiscountBps;
50688
51063
  exports.isPeerExtensionAvailable = isPeerExtensionAvailable;
50689
51064
  exports.isSupportedCurrencyHash = isSupportedCurrencyHash;
51065
+ exports.isValidReferralCode = isValidReferralCode;
50690
51066
  exports.isValidReferrerFeeBps = isValidReferrerFeeBps;
50691
51067
  exports.isValidReferrerFeeRecipient = isValidReferrerFeeRecipient;
50692
51068
  exports.isZeroRateManagerId = isZeroRateManagerId;
50693
51069
  exports.logger = logger;
50694
51070
  exports.mapConversionRatesToOnchainMinRate = mapConversionRatesToOnchainMinRate;
50695
51071
  exports.normalizeRateManagerId = normalizeRateManagerId2;
51072
+ exports.normalizeReferralCode = normalizeReferralCode;
50696
51073
  exports.normalizeRegistry = normalizeRegistry;
50697
51074
  exports.openPeerExtensionInstallPage = openPeerExtensionInstallPage;
50698
51075
  exports.parseDepositView = parseDepositView;