@zkp2p/sdk 0.7.1 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.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,1231 +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();
46396
- }
46397
- function normalizeAddress3(value) {
46398
- if (!value) return "";
46399
- return value.toLowerCase();
46400
- }
46401
- function escapeLikePatternLiteral(value) {
46402
- return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
46403
- }
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;
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}`;
46413
46157
  }
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;
46158
+ return headers2;
46420
46159
  }
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;
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;
46427
46166
  }
46428
- function buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress) {
46429
- const normalizedId = escapeLikePatternLiteral(normalizeRateManagerId(rateManagerId));
46430
- const normalizedRateManagerAddress = escapeLikePatternLiteral(
46431
- normalizeAddress3(rateManagerAddress)
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
46432
46202
  );
46433
- return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
46434
46203
  }
46435
- function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
46436
- return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
46204
+ function unwrapResponseObject(payload) {
46205
+ if (payload && typeof payload === "object" && "responseObject" in payload) {
46206
+ return payload.responseObject;
46207
+ }
46208
+ return payload;
46437
46209
  }
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}`;
46210
+ function requireAuthorizationToken(authorizationToken, endpoint) {
46211
+ if (!authorizationToken) {
46212
+ throw new exports.ValidationError(
46213
+ `authorizationToken is required for ${endpoint}`,
46214
+ "authorizationToken"
46215
+ );
46445
46216
  }
46446
- return normalizedDepositId;
46217
+ return authorizationToken;
46447
46218
  }
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;
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;
46453
46233
  }
46454
- function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
46455
- if (!compositeDepositId) return null;
46456
- const [escrowAddress] = compositeDepositId.split("_");
46457
- return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
46234
+ function requireEscrowAddress(escrowAddress, endpoint) {
46235
+ if (!escrowAddress) {
46236
+ throw new exports.ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
46237
+ }
46238
+ return escrowAddress;
46458
46239
  }
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
- }
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);
46478
46244
  }
46479
- return { bare, scoped };
46245
+ return normalized;
46480
46246
  }
46481
- function buildDepositScopeKey(scope) {
46482
- return `${scope.escrow}:${scope.depositIdOnContract}`;
46247
+ function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
46248
+ const normalized = withApiBase(baseApiUrl).toLowerCase();
46249
+ if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
46250
+ return "PREPRODUCTION";
46251
+ }
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
- });
46623
- }
46624
- if (scopeConditions.length === 1) {
46625
- return scopeConditions[0] ?? {};
46626
- }
46627
- if (scopeConditions.length > 1) {
46628
- return { _or: scopeConditions };
46629
- }
46630
- return {};
46378
+ if (!isValidHexAddress(req.destinationToken)) {
46379
+ throw new exports.ValidationError(
46380
+ "destinationToken must be a valid Ethereum address",
46381
+ "destinationToken"
46382
+ );
46631
46383
  }
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 }];
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
+ };
46637
46446
  }
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);
46645
- }
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
- }));
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));
46652
46658
  }
46653
- applyHookFilter(rows, hasHook) {
46654
- if (hasHook === void 0) return rows;
46655
- return hasHook ? [] : rows;
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;
46656
46672
  }
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
- }
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
+ });
46672
46682
  }
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 }];
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
+ });
46678
46692
  }
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 }];
46693
+ async lookupReferralCode(code, opts) {
46694
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46695
+ return apiLookupReferralCode(code, { baseApiUrl, timeoutMs });
46684
46696
  }
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;
46707
- }
46708
- return [...scopes.values()];
46697
+ async createReferralCode(opts) {
46698
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46699
+ const authorizationToken = await this.resolveAuthorizationToken(opts);
46700
+ return apiCreateReferralCode({}, { baseApiUrl, timeoutMs, authorizationToken });
46709
46701
  }
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);
46720
- }
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
- }
46757
- }
46758
- return [...scopes.values()];
46702
+ async createReferralCodeWithSignature(opts) {
46703
+ const { baseApiUrl, timeoutMs } = this.resolveRequestOptions(opts);
46704
+ const signature = await this.signCreateReferralCode(opts);
46705
+ return apiCreateReferralCode({ signature }, { baseApiUrl, timeoutMs });
46759
46706
  }
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
- }
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"
46780
46721
  );
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);
46796
46722
  }
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
- }
46723
+ if (lookup && !lookup.isActive) {
46724
+ throw new exports.ValidationError("Referral code is not active", "code");
46725
+ }
46726
+ const signature = await this.signRedeemReferralCode(
46727
+ normalizedCode,
46728
+ referrerWalletAddress,
46729
+ opts
46812
46730
  );
46813
- return this.applyHookFilter(this.toRateManagerListItems(result), filter?.hasHook);
46814
- }
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
- }
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()
46855
46749
  };
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
46750
+ }
46751
+ stripTrailingSlash(url) {
46752
+ return url.replace(/\/$/, "");
46753
+ }
46754
+ async resolveAuthorizationToken(opts) {
46755
+ if (opts?.authorizationToken !== void 0) {
46756
+ return opts.authorizationToken;
46757
+ }
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;
46776
+ }
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"
46871
46784
  );
46872
- scopedRecentStats = (result.ManagerStats ?? []).filter((stats) => {
46873
- const statsRateManagerAddress = normalizeAddress3(stats.rateManagerAddress);
46874
- return !statsRateManagerAddress || statsRateManagerAddress === scopedRateManagerAddress;
46875
- });
46876
- scopedDelegations = (result.Deposit ?? []).map((deposit) => toDelegationEntityFromDeposit(deposit)).filter((delegation) => Boolean(delegation)).filter(
46877
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
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"
46878
46792
  );
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;
46793
+ }
46794
+ return { account, walletAddress };
46795
+ }
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);
46800
+ }
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)
46885
46836
  }
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;
46899
- });
46900
- scopedDelegations = (legacyResult.RateManagerDelegation ?? []).filter(
46901
- (delegation) => normalizeAddress3(delegation.rateManagerAddress) === scopedRateManagerAddress
46902
- );
46903
- aggregate = (legacyResult.ManagerAggregateStats ?? []).find(
46904
- (stats) => (normalizeAddress3(stats.rateManagerAddress) || extractRateManagerAddressFromScopedId(stats.id)) === scopedRateManagerAddress
46905
- ) ?? legacyResult.ManagerAggregateStats?.[0] ?? null;
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 };
46860
+ }
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");
46906
46888
  }
46907
- if (!managerRaw) return null;
46908
- const manager = normalizeRateManagerEntity(managerRaw);
46909
46889
  return {
46910
- manager,
46911
- rates: scopedRates,
46912
- aggregate,
46913
- recentStats: scopedRecentStats,
46914
- delegations: scopedDelegations
46890
+ address,
46891
+ abi
46915
46892
  };
46916
46893
  }
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
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
46929
46920
  };
46930
- try {
46931
- const result = await this.client.query({
46932
- query: RATE_MANAGER_DELEGATIONS_QUERY,
46933
- variables
46934
- });
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
- }
46946
- });
46947
- return legacyResult.RateManagerDelegation ?? [];
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
+ });
46962
+ }
46963
+ prepareCreateRateManagerTransaction(params) {
46964
+ return this.prepareRateManagerRegistryTransaction({
46965
+ functionNames: ["createRateManager"],
46966
+ args: [this.buildCreateRateManagerConfig(params.config)],
46967
+ txOverrides: params.txOverrides
46968
+ });
46969
+ }
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
+ });
46976
+ }
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
+ });
46983
+ }
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");
46991
+ }
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
+ });
47005
+ }
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");
46948
47013
  }
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
+ });
46949
47022
  }
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 [];
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");
46979
47030
  }
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
+ });
46980
47044
  }
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
- }
46990
- });
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
47004
- }
47005
- });
47006
- return legacyResult.RateManagerDelegation?.[0] ?? null;
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");
47007
47052
  }
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
+ });
47008
47072
  }
47009
- async fetchManualRateUpdates(rateManagerId, options) {
47010
- if (!rateManagerId) return [];
47011
- const normalizedId = normalizeRateManagerId(rateManagerId);
47012
- 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
- }
47022
- });
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
- } catch (error) {
47029
- if (!isSchemaCompatibilityError(error)) {
47030
- throw error;
47031
- }
47032
- return [];
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");
47033
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
+ });
47034
47089
  }
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
- }
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]
47063
47109
  });
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;
47110
+ if (result && result.length >= 2) {
47111
+ return {
47112
+ registry: result[0],
47113
+ rateManagerId: result[1]
47114
+ };
47086
47115
  }
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
- }
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]
47096
47145
  });
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));
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");
47104
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
+ });
47105
47173
  }
47106
47174
  };
47175
+ var getRateManagerReadFunction = (abi, functionName) => Array.isArray(abi) && abi.some(
47176
+ (item) => item.type === "function" && item.name === functionName
47177
+ );
47107
47178
 
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
- });
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();
47114
47187
  }
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;
47188
+ function normalizeAddress3(value) {
47189
+ if (!value) return "";
47190
+ return value.toLowerCase();
47126
47191
  }
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
- }
47192
+ function escapeLikePatternLiteral(value) {
47193
+ return value.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
47138
47194
  }
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);
47153
- }
47154
- },
47155
- error: (...args) => {
47156
- console.error("[ERROR]", ...args);
47157
- }
47158
- };
47159
-
47160
- // src/referral.ts
47161
- var normalizeReferralCode = (code) => code.trim().toUpperCase();
47162
- var isValidReferralCode = (code) => /^[A-Z0-9]{6}$/.test(normalizeReferralCode(code));
47163
-
47164
- // src/adapters/api.ts
47165
- function createHeaders(apiKey, authorizationToken) {
47166
- const headers2 = { "Content-Type": "application/json" };
47167
- if (apiKey) headers2["x-api-key"] = apiKey;
47168
- if (authorizationToken) {
47169
- headers2.Authorization = authorizationToken.startsWith("Bearer ") ? authorizationToken : `Bearer ${authorizationToken}`;
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;
47170
47204
  }
47171
- return headers2;
47205
+ return { rateManagerAddress, rateManagerId };
47172
47206
  }
47173
- function withApiBase(baseApiUrl) {
47174
- const trimmed = (baseApiUrl || "").trim();
47175
- let base2 = trimmed.replace(/\/+$/, "");
47176
- base2 = base2.replace(/\/v1$/i, "");
47177
- base2 = base2.replace(/\/v2$/i, "");
47178
- return base2;
47207
+ function getManagerScopeKey(rateManagerId, rateManagerAddress) {
47208
+ const normalizedId = normalizeRateManagerId(rateManagerId);
47209
+ const normalizedRateManagerAddress = normalizeAddress3(rateManagerAddress);
47210
+ return normalizedRateManagerAddress ? `${normalizedRateManagerAddress}:${normalizedId}` : normalizedId;
47179
47211
  }
47180
- async function apiFetch({
47181
- url,
47182
- method = "GET",
47183
- body,
47184
- apiKey,
47185
- authorizationToken,
47186
- timeoutMs,
47187
- retryCount = 3,
47188
- retryDelayMs = 1e3
47189
- }) {
47190
- const endpoint = url.replace(/^[^/]*\/\/[^/]*/, "");
47191
- return withRetry(
47192
- async () => {
47193
- let res;
47194
- try {
47195
- const options = {
47196
- method,
47197
- headers: createHeaders(apiKey, authorizationToken)
47198
- };
47199
- if (body && method !== "GET") {
47200
- options.body = JSON.stringify(body);
47201
- }
47202
- res = await fetch(url, options);
47203
- } catch (error) {
47204
- throw new exports.NetworkError("Failed to connect to API server", { endpoint, error });
47205
- }
47206
- if (!res.ok) {
47207
- const errorText = await res.text();
47208
- throw parseAPIError(res, errorText);
47209
- }
47210
- return res.json();
47211
- },
47212
- retryCount,
47213
- retryDelayMs,
47214
- timeoutMs
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)
47215
47223
  );
47224
+ return `%\\_${normalizedRateManagerAddress}\\_${normalizedId}`;
47216
47225
  }
47217
- function unwrapResponseObject(payload) {
47218
- if (payload && typeof payload === "object" && "responseObject" in payload) {
47219
- return payload.responseObject;
47220
- }
47221
- return payload;
47226
+ function buildRateManagerScopedIdPattern(rateManagerId, rateManagerAddress) {
47227
+ return `${buildRateManagerAddressScopedIdPattern(rateManagerId, rateManagerAddress)}\\_%`;
47222
47228
  }
47223
- function requireAuthorizationToken(authorizationToken, endpoint) {
47224
- if (!authorizationToken) {
47225
- throw new exports.ValidationError(`authorizationToken is required for ${endpoint}`, "authorizationToken");
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}`;
47226
47236
  }
47227
- return authorizationToken;
47237
+ return normalizedDepositId;
47228
47238
  }
47229
- function requireEscrowAddress(escrowAddress, endpoint) {
47230
- if (!escrowAddress) {
47231
- throw new exports.ValidationError(`escrowAddress is required for ${endpoint}`, "escrowAddress");
47232
- }
47233
- return escrowAddress;
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;
47234
47244
  }
47235
- function inferIndexerEnvFromBaseApiUrl(baseApiUrl) {
47236
- const normalized = withApiBase(baseApiUrl).toLowerCase();
47237
- if (normalized.includes("preprod") || normalized.includes("preproduction") || normalized.includes("/preprod/")) {
47238
- return "PREPRODUCTION";
47239
- }
47240
- if (normalized.includes("staging") || normalized.includes("/staging/") || normalized.includes("localhost") || normalized.includes("127.0.0.1")) {
47241
- return "STAGING";
47242
- }
47243
- return "PRODUCTION";
47245
+ function extractEscrowAddressFromCompositeDepositId(compositeDepositId) {
47246
+ if (!compositeDepositId) return null;
47247
+ const [escrowAddress] = compositeDepositId.split("_");
47248
+ return escrowAddress?.startsWith("0x") ? escrowAddress.toLowerCase() : null;
47244
47249
  }
47245
- async function withOptionalTimeout(promise, timeoutMs, endpoint) {
47246
- if (!timeoutMs || timeoutMs <= 0) return promise;
47247
- let timer;
47248
- try {
47249
- return await Promise.race([
47250
- promise,
47251
- new Promise((_, reject) => {
47252
- timer = setTimeout(() => {
47253
- reject(new exports.NetworkError("Request timed out", { endpoint }));
47254
- }, timeoutMs);
47255
- })
47256
- ]);
47257
- } finally {
47258
- if (timer) clearTimeout(timer);
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
47259
+ );
47260
+ continue;
47261
+ }
47262
+ if (value.includes(":")) {
47263
+ continue;
47264
+ }
47265
+ const normalizedRateManagerId = normalizeRateManagerId(value);
47266
+ if (normalizedRateManagerId) {
47267
+ bare.add(normalizedRateManagerId);
47268
+ }
47259
47269
  }
47270
+ return { bare, scoped };
47260
47271
  }
47261
- function toDateFromUnixSeconds(value) {
47262
- if (!value) return void 0;
47263
- const numeric = Number(value);
47264
- if (!Number.isFinite(numeric) || numeric <= 0) return void 0;
47265
- return new Date(numeric * 1e3);
47272
+ function buildDepositScopeKey(scope) {
47273
+ return `${scope.escrow}:${scope.depositIdOnContract}`;
47266
47274
  }
47267
- function toBigIntSafe(value) {
47268
- if (value === null || value === void 0) return 0n;
47275
+ function toSafeBigInt(value) {
47276
+ if (!value) return 0n;
47269
47277
  try {
47270
- return BigInt(value);
47278
+ return parseBigIntLike(value);
47271
47279
  } catch {
47272
47280
  return 0n;
47273
47281
  }
47274
47282
  }
47275
- function normalizeOwnerDepositsStatus(status) {
47276
- if (!status) return void 0;
47277
- if (status === "WITHDRAWN") return "CLOSED";
47278
- return status;
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;
47279
47287
  }
47280
- function buildLegacyVerifierCurrencies(deposit) {
47281
- const currenciesByMethod = /* @__PURE__ */ new Map();
47282
- for (const currency of deposit.currencies ?? []) {
47283
- const methodHash = currency.paymentMethodHash;
47284
- const resolvedConversionRate = currency.conversionRate ?? currency.minConversionRate;
47285
- if (resolvedConversionRate === null || resolvedConversionRate === void 0) {
47286
- logger.warn(
47287
- `[sdk] Skipping currency with missing conversion rate (deposit ${deposit.depositId}, currency ${currency.currencyCode})`
47288
- );
47289
- continue;
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 {
47296
+ return {
47297
+ chainId: BigInt(chainIdRaw),
47298
+ blockNumber: BigInt(blockNumberRaw),
47299
+ logIndex: BigInt(logIndexRaw)
47300
+ };
47301
+ } catch {
47302
+ return null;
47303
+ }
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;
47290
47311
  }
47291
- const bucket = currenciesByMethod.get(methodHash) ?? [];
47292
- bucket.push({
47293
- currencyCode: currency.currencyCode,
47294
- conversionRate: resolvedConversionRate,
47295
- minConversionRate: currency.minConversionRate,
47296
- managerRate: currency.managerRate ?? null,
47297
- rateManagerId: currency.rateManagerId ?? null
47298
- });
47299
- currenciesByMethod.set(methodHash, bucket);
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;
47300
47319
  }
47301
- return currenciesByMethod;
47320
+ return (rightId ?? "").localeCompare(leftId ?? "");
47302
47321
  }
47303
- function convertIndexerDepositToLegacyApiDeposit(deposit) {
47304
- const currenciesByMethod = buildLegacyVerifierCurrencies(deposit);
47305
- const verifiers = (deposit.paymentMethods ?? []).filter((paymentMethod) => paymentMethod.active !== false).map((paymentMethod) => ({
47306
- depositId: Number(deposit.depositId),
47307
- verifier: "",
47308
- methodHash: paymentMethod.paymentMethodHash,
47309
- intentGatingService: paymentMethod.intentGatingService,
47310
- payeeDetailsHash: paymentMethod.payeeDetailsHash,
47311
- data: "0x",
47312
- currencies: currenciesByMethod.get(paymentMethod.paymentMethodHash) ?? []
47313
- }));
47314
- const remainingDeposits = toBigIntSafe(deposit.remainingDeposits);
47315
- const outstandingIntentAmount = toBigIntSafe(deposit.outstandingIntentAmount);
47316
- const totalAmountTaken = toBigIntSafe(deposit.totalAmountTaken);
47317
- const totalWithdrawn = toBigIntSafe(deposit.totalWithdrawn);
47318
- const amount = remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn;
47322
+ function isAggregateOrderField(field) {
47323
+ return field === "currentDelegatedBalance" || field === "totalFilledVolume";
47324
+ }
47325
+ function normalizeRateManagerEntity(manager) {
47319
47326
  return {
47320
- id: Number(deposit.depositId),
47321
- depositor: deposit.depositor,
47322
- token: deposit.token,
47323
- amount: amount.toString(),
47324
- remainingDeposits: deposit.remainingDeposits,
47325
- intentAmountMin: deposit.intentAmountMin,
47326
- intentAmountMax: deposit.intentAmountMax,
47327
- acceptingIntents: deposit.acceptingIntents,
47328
- outstandingIntentAmount: deposit.outstandingIntentAmount,
47329
- availableLiquidity: deposit.remainingDeposits,
47330
- status: deposit.status,
47331
- totalIntents: deposit.totalIntents,
47332
- signaledIntents: deposit.signaledIntents,
47333
- fulfilledIntents: deposit.fulfilledIntents,
47334
- prunedIntents: deposit.prunedIntents,
47335
- totalAmountTaken: deposit.totalAmountTaken,
47336
- totalWithdrawn: deposit.totalWithdrawn,
47337
- successRateBps: deposit.successRateBps,
47338
- rateManagerId: deposit.rateManagerId ?? null,
47339
- vaultName: null,
47340
- rateManagerRegistry: null,
47341
- createdAt: toDateFromUnixSeconds(deposit.timestamp),
47342
- updatedAt: toDateFromUnixSeconds(deposit.updatedAt),
47343
- verifiers
47327
+ ...manager,
47328
+ rateManagerAddress: normalizeAddress3(manager.rateManagerAddress)
47344
47329
  };
47345
47330
  }
47346
- async function apiPostDepositDetails(req, baseApiUrl, timeoutMs) {
47347
- return apiFetch({
47348
- url: `${withApiBase(baseApiUrl)}/v2/makers/create`,
47349
- method: "POST",
47350
- body: req,
47351
- timeoutMs
47352
- });
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
+ };
47353
47345
  }
47354
- async function apiGetQuote(req, baseApiUrl, timeoutMs, apiKey) {
47355
- if (req.quotesToReturn !== void 0) {
47356
- if (!Number.isInteger(req.quotesToReturn) || req.quotesToReturn < 1) {
47357
- throw new exports.ValidationError("quotesToReturn must be a positive integer", "quotesToReturn");
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] }
47357
+ });
47358
+ }
47359
+ for (const scopedRateManager of scoped.values()) {
47360
+ scopeConditions.push({
47361
+ rateManagerId: { _eq: scopedRateManager.rateManagerId },
47362
+ rateManagerAddress: { _eq: scopedRateManager.rateManagerAddress }
47363
+ });
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;
47372
+ }
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}%` };
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;
47390
+ }
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] }
47402
+ });
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
+ )
47412
+ }
47413
+ });
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
+ }));
47443
+ }
47444
+ applyHookFilter(rows, hasHook) {
47445
+ if (hasHook === void 0) return rows;
47446
+ return hasHook ? [] : rows;
47447
+ }
47448
+ async queryRateManagerList(variables, legacyVariables) {
47449
+ try {
47450
+ return await this.client.query({
47451
+ query: RATE_MANAGER_LIST_QUERY,
47452
+ variables
47453
+ });
47454
+ } catch (error) {
47455
+ if (!isSchemaCompatibilityError(error)) {
47456
+ throw error;
47457
+ }
47458
+ return this.client.query({
47459
+ query: LEGACY_RATE_MANAGER_LIST_QUERY,
47460
+ variables: legacyVariables
47461
+ });
47358
47462
  }
47359
47463
  }
47360
- if (!isValidHexAddress(req.user)) {
47361
- throw new exports.ValidationError("user must be a valid Ethereum address", "user");
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 }];
47362
47469
  }
47363
- if (!isValidHexAddress(req.recipient)) {
47364
- throw new exports.ValidationError("recipient must be a valid Ethereum address", "recipient");
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 }];
47365
47475
  }
47366
- if (!isValidHexAddress(req.destinationToken)) {
47367
- throw new exports.ValidationError(
47368
- "destinationToken must be a valid Ethereum address",
47369
- "destinationToken"
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
47486
+ });
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);
47493
+ }
47494
+ if (delegations.length < RATE_MANAGER_HISTORY_PAGE_SIZE) {
47495
+ break;
47496
+ }
47497
+ offset += RATE_MANAGER_HISTORY_PAGE_SIZE;
47498
+ }
47499
+ return [...scopes.values()];
47500
+ }
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
47370
47508
  );
47509
+ for (const scope of currentScopes) {
47510
+ scopes.set(buildDepositScopeKey(scope), scope);
47511
+ }
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);
47538
+ }
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;
47543
+ }
47544
+ } catch (error) {
47545
+ if (!isSchemaCompatibilityError(error)) {
47546
+ throw error;
47547
+ }
47548
+ }
47549
+ return [...scopes.values()];
47371
47550
  }
47372
- const isExactFiat = req.isExactFiat !== false;
47373
- const endpoint = isExactFiat ? "exact-fiat" : "exact-token";
47374
- let url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
47375
- if (req.quotesToReturn) url += `?quotesToReturn=${req.quotesToReturn}`;
47376
- const requestBody = {
47377
- ...req,
47378
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
47379
- amount: void 0,
47380
- isExactFiat: void 0,
47381
- quotesToReturn: void 0,
47382
- includePrivateOrderbooks: req.includePrivateOrderbooks
47383
- };
47384
- Object.keys(requestBody).forEach((k) => requestBody[k] === void 0 && delete requestBody[k]);
47385
- return apiFetch({
47386
- url,
47387
- method: "POST",
47388
- body: requestBody,
47389
- apiKey,
47390
- timeoutMs
47391
- });
47392
- }
47393
- async function apiGetQuotesBestByPlatform(req, baseApiUrl, timeoutMs, apiKey) {
47394
- const isExactFiat = req.isExactFiat !== false;
47395
- const endpoint = isExactFiat ? "best-by-platform" : "best-by-platform-exact-token";
47396
- const url = `${withApiBase(baseApiUrl)}/v2/quote/${endpoint}`;
47397
- const requestBody = {
47398
- ...req,
47399
- [isExactFiat ? "exactFiatAmount" : "exactTokenAmount"]: String(req.amount),
47400
- amount: void 0,
47401
- isExactFiat: void 0,
47402
- referrerFeeConfig: void 0
47403
- };
47404
- Object.keys(requestBody).forEach(
47405
- (key) => requestBody[key] === void 0 && delete requestBody[key]
47406
- );
47407
- return apiFetch({
47408
- url,
47409
- method: "POST",
47410
- body: requestBody,
47411
- apiKey,
47412
- timeoutMs
47413
- });
47414
- }
47415
- async function apiGetPayeeDetails(req, baseApiUrl, timeoutMs) {
47416
- return apiFetch({
47417
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/${req.processorName}/${req.hashedOnchainId}`,
47418
- method: "GET",
47419
- timeoutMs
47420
- });
47421
- }
47422
- async function apiValidatePayeeDetails(req, baseApiUrl, timeoutMs) {
47423
- const data52 = await apiFetch({
47424
- url: `${baseApiUrl.replace(/\/$/, "")}/v2/makers/validate`,
47425
- method: "POST",
47426
- body: req,
47427
- timeoutMs
47428
- });
47429
- if (typeof data52?.responseObject === "boolean") {
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
+ }
47571
+ );
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);
47587
+ }
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);
47605
+ }
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;
47697
+ }
47698
+ if (!managerRaw) return null;
47699
+ const manager = normalizeRateManagerEntity(managerRaw);
47430
47700
  return {
47431
- ...data52,
47432
- responseObject: { isValid: data52.responseObject }
47701
+ manager,
47702
+ rates: scopedRates,
47703
+ aggregate,
47704
+ recentStats: scopedRecentStats,
47705
+ delegations: scopedDelegations
47433
47706
  };
47434
47707
  }
47435
- return data52;
47436
- }
47437
- async function apiGetOwnerDeposits(req, apiKey, baseApiUrl, authToken, timeoutMs) {
47438
- const escrowAddress = requireEscrowAddress(
47439
- req.escrowAddress,
47440
- "apiGetOwnerDeposits requires escrowAddress"
47441
- );
47442
- const indexerEndpoint = defaultIndexerEndpoint(inferIndexerEnvFromBaseApiUrl(baseApiUrl));
47443
- const indexerClient = new IndexerClient(indexerEndpoint, {
47444
- apiKey,
47445
- authorizationToken: authToken
47446
- });
47447
- const service = new IndexerDepositService(indexerClient);
47448
- const deposits = await withOptionalTimeout(
47449
- service.fetchDepositsWithRelations(
47450
- {
47451
- depositor: req.ownerAddress,
47452
- escrowAddress,
47453
- escrowAddresses: req.escrowAddresses?.length ? req.escrowAddresses : void 0,
47454
- 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 } } : {}
47455
47716
  },
47456
- void 0,
47457
- { includeIntents: false }
47458
- ),
47459
- timeoutMs,
47460
- indexerEndpoint
47461
- );
47462
- return {
47463
- success: true,
47464
- message: "ok",
47465
- responseObject: deposits.map(convertIndexerDepositToLegacyApiDeposit),
47466
- statusCode: 200
47467
- };
47468
- }
47469
- async function apiGetTakerTier(req, baseApiUrl, timeoutMs) {
47470
- const normalizedOwner = req.owner.toLowerCase();
47471
- const query = new URLSearchParams({
47472
- owner: normalizedOwner,
47473
- chainId: String(req.chainId)
47474
- });
47475
- const endpoint = `/v2/taker/tier?${query.toString()}`;
47476
- return apiFetch({
47477
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47478
- method: "GET",
47479
- timeoutMs
47480
- });
47481
- }
47482
- async function apiGetReferralDashboard(opts) {
47483
- const endpoint = "/v2/referral";
47484
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
47485
- const response = await apiFetch({
47486
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
47487
- method: "GET",
47488
- authorizationToken,
47489
- timeoutMs: opts.timeoutMs
47490
- });
47491
- return unwrapResponseObject(response);
47492
- }
47493
- async function apiGetReferralEarnings(opts) {
47494
- const endpoint = "/v2/referral/earnings";
47495
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
47496
- const response = await apiFetch({
47497
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
47498
- method: "GET",
47499
- authorizationToken,
47500
- timeoutMs: opts.timeoutMs
47501
- });
47502
- return unwrapResponseObject(response);
47503
- }
47504
- async function apiRedeemReferralCode(req, opts) {
47505
- const endpoint = "/v2/referral/redeem";
47506
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
47507
- const response = await apiFetch({
47508
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
47509
- method: "POST",
47510
- body: { code: normalizeReferralCode(req.code) },
47511
- authorizationToken,
47512
- timeoutMs: opts.timeoutMs
47513
- });
47514
- return unwrapResponseObject(response);
47515
- }
47516
- async function apiUpdateReferralCode(req, opts) {
47517
- const endpoint = "/v2/referral/code";
47518
- const authorizationToken = requireAuthorizationToken(opts.authorizationToken, endpoint);
47519
- const response = await apiFetch({
47520
- url: `${withApiBase(opts.baseApiUrl)}${endpoint}`,
47521
- method: "PATCH",
47522
- body: { code: normalizeReferralCode(req.code) },
47523
- authorizationToken,
47524
- timeoutMs: opts.timeoutMs
47525
- });
47526
- return unwrapResponseObject(response);
47527
- }
47528
- async function apiUploadSellerCredential(processorName, payeeDetails, bundle, baseApiUrl, timeoutMs) {
47529
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47530
- payeeDetails
47531
- )}/seller-credential`;
47532
- return apiFetch({
47533
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47534
- method: "POST",
47535
- body: bundle,
47536
- timeoutMs
47537
- });
47538
- }
47539
- async function apiUploadGoogleOAuthSellerCredential(processorName, payeeDetails, body, baseApiUrl, opts) {
47540
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47541
- payeeDetails
47542
- )}/seller-credential/google-oauth`;
47543
- return apiFetch({
47544
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47545
- method: "POST",
47546
- body,
47547
- timeoutMs: opts?.timeoutMs
47548
- });
47549
- }
47550
- async function apiGetSellerCredentialStatus(processorName, payeeDetails, baseApiUrl, timeoutMs) {
47551
- const endpoint = `/v2/makers/${encodeURIComponent(processorName)}/${encodeURIComponent(
47552
- payeeDetails
47553
- )}/seller-credential/status`;
47554
- return apiFetch({
47555
- url: `${withApiBase(baseApiUrl)}${endpoint}`,
47556
- method: "GET",
47557
- timeoutMs
47558
- });
47559
- }
47560
- async function apiVerifySellerPayment(platform, req, baseApiUrl, timeoutMs, apiKey) {
47561
- const body = {
47562
- txId: req.txId,
47563
- chainId: req.chainId,
47564
- intent: req.intent,
47565
- ...req.metadata !== void 0 ? { metadata: req.metadata } : {}
47566
- };
47567
- return apiFetch({
47568
- url: `${withApiBase(baseApiUrl)}/v2/verify/seller/${encodeURIComponent(platform)}`,
47569
- method: "POST",
47570
- body,
47571
- apiKey,
47572
- timeoutMs
47573
- });
47574
- }
47575
- async function apiGetOrderbook(params, optsOrBaseApiUrl, timeoutMs) {
47576
- const opts = typeof optsOrBaseApiUrl === "string" ? {
47577
- baseApiUrl: optsOrBaseApiUrl,
47578
- timeoutMs
47579
- } : optsOrBaseApiUrl;
47580
- const query = new URLSearchParams();
47581
- Object.entries(params).forEach(([key, value]) => {
47582
- if (value === void 0 || value === null) return;
47583
- query.set(key, String(value));
47584
- });
47585
- const response = await apiFetch({
47586
- url: `${withApiBase(opts.baseApiUrl)}/v2/orderbook?${query.toString()}`,
47587
- method: "GET",
47588
- timeoutMs: opts.timeoutMs
47589
- });
47590
- return response.responseObject;
47591
- }
47592
- async function apiGetDepositBundle(params, optsOrBaseApiUrl, timeoutMs) {
47593
- const opts = typeof optsOrBaseApiUrl === "string" ? {
47594
- baseApiUrl: optsOrBaseApiUrl,
47595
- timeoutMs
47596
- } : optsOrBaseApiUrl;
47597
- const escrowAddress = requireEscrowAddress(
47598
- params.escrowAddress,
47599
- "apiGetDepositBundle requires escrowAddress"
47600
- );
47601
- const query = new URLSearchParams({ escrowAddress });
47602
- if (params.dailySnapshotLimit !== void 0) {
47603
- 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
+ }
47740
+ }
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
+ }
47604
47771
  }
47605
- const response = await apiFetch({
47606
- url: `${withApiBase(opts.baseApiUrl)}/v2/deposits/${params.depositId}/bundle?${query.toString()}`,
47607
- method: "GET",
47608
- timeoutMs: opts.timeoutMs
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 }
47609
47904
  });
47610
- return response.responseObject;
47611
47905
  }
47612
47906
 
47907
+ // src/client/Zkp2pClient.ts
47908
+ init_contracts();
47909
+
47613
47910
  // src/sellerCredentials.ts
47614
47911
  function normalizeBaseApiUrl(value) {
47615
47912
  return (value?.trim().replace(/\/+$/u, "") || DEFAULT_BASE_API_URL).replace(/\/v1$/u, "");
@@ -47820,9 +48117,7 @@ function isObjectRecord(value) {
47820
48117
  return true;
47821
48118
  }
47822
48119
  function normalizeTelegramUsername(value) {
47823
- if (typeof value !== "string") {
47824
- return value === null ? null : null;
47825
- }
48120
+ if (typeof value !== "string") return null;
47826
48121
  const normalized = value.trim();
47827
48122
  return normalized.length > 0 ? normalized : null;
47828
48123
  }
@@ -48116,7 +48411,7 @@ var Zkp2pClient = class {
48116
48411
  () => ({
48117
48412
  address: this.rateManagerControllerAddress,
48118
48413
  abi: this.rateManagerControllerAbi,
48119
- label: "Rate manager controller (staging only)"
48414
+ label: "Rate manager controller"
48120
48415
  }),
48121
48416
  "setDepositRateManager",
48122
48417
  (params) => {
@@ -48130,7 +48425,7 @@ var Zkp2pClient = class {
48130
48425
  () => ({
48131
48426
  address: this.rateManagerControllerAddress,
48132
48427
  abi: this.rateManagerControllerAbi,
48133
- label: "Rate manager controller (staging only)"
48428
+ label: "Rate manager controller"
48134
48429
  }),
48135
48430
  "clearDepositRateManager",
48136
48431
  (params) => {
@@ -48216,7 +48511,7 @@ var Zkp2pClient = class {
48216
48511
  () => ({
48217
48512
  address: this.rateManagerRegistryAddress,
48218
48513
  abi: this.rateManagerRegistryAbi,
48219
- label: "Rate manager registry (staging only)"
48514
+ label: "Rate manager registry"
48220
48515
  }),
48221
48516
  "setFee",
48222
48517
  (params) => {
@@ -48701,6 +48996,10 @@ var Zkp2pClient = class {
48701
48996
  const prepared = await this.prepareFulfillIntent(params);
48702
48997
  const txHash = await this.executePreparedTransaction(prepared, params.txOverrides);
48703
48998
  params?.callbacks?.onTxSent?.(txHash);
48999
+ if (params?.callbacks?.onTxMined) {
49000
+ await this.publicClient.waitForTransactionReceipt({ hash: txHash });
49001
+ params.callbacks.onTxMined(txHash);
49002
+ }
48704
49003
  return txHash;
48705
49004
  },
48706
49005
  {
@@ -48719,7 +49018,7 @@ var Zkp2pClient = class {
48719
49018
  this.walletClient = opts.walletClient;
48720
49019
  this.chainId = opts.chainId;
48721
49020
  this.runtimeEnv = opts.runtimeEnv ?? "production";
48722
- const inferredRpc = this.walletClient?.chain?.rpcUrls?.default?.http?.[0];
49021
+ const inferredRpc = this.walletClient.chain?.rpcUrls?.default?.http?.[0];
48723
49022
  const defaultRpcUrls = {
48724
49023
  [chains.base.id]: "https://mainnet.base.org",
48725
49024
  [chains.hardhat.id]: "http://127.0.0.1:8545"
@@ -48732,7 +49031,7 @@ var Zkp2pClient = class {
48732
49031
  const selectedChain = chainMap[this.chainId];
48733
49032
  this.publicClient = viem.createPublicClient({
48734
49033
  chain: selectedChain,
48735
- transport: viem.http(rpc, { batch: false })
49034
+ transport: opts.rpcTransport ?? viem.http(rpc, { batch: false })
48736
49035
  });
48737
49036
  const { addresses, abis } = getContracts(this.chainId, this.runtimeEnv);
48738
49037
  const toAddress = (value) => this.isValidHexAddress(value) ? value : void 0;
@@ -48750,12 +49049,10 @@ var Zkp2pClient = class {
48750
49049
  };
48751
49050
  this.escrowV2Address = toAddress(addresses.escrowV2 ?? addresses.escrow);
48752
49051
  this.escrowV2Abi = abis.escrowV2 ?? abis.escrow;
48753
- this.orchestratorV2Address = toAddress(
48754
- addresses.orchestratorV2 ?? addresses.orchestrator
48755
- );
49052
+ this.orchestratorV2Address = toAddress(addresses.orchestratorV2 ?? addresses.orchestrator);
48756
49053
  this.orchestratorV2Abi = abis.orchestratorV2 ?? abis.orchestrator;
48757
- const configuredEscrowAddresses = (addresses.escrowAddresses ?? []).map((value) => toAddress(value)).filter(Boolean);
48758
- 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));
48759
49056
  this.escrowAddresses = uniqAddresses([
48760
49057
  this.escrowV2Address ?? toAddress(addresses.escrow),
48761
49058
  ...configuredEscrowAddresses
@@ -48821,8 +49118,7 @@ var Zkp2pClient = class {
48821
49118
  orchestratorV2Abi: this.orchestratorV2Abi,
48822
49119
  orchestratorAddresses: this.orchestratorAddresses
48823
49120
  });
48824
- const maybeUsdc = addresses.usdc;
48825
- if (maybeUsdc) this._usdcAddress = maybeUsdc;
49121
+ if (addresses.usdc) this._usdcAddress = addresses.usdc;
48826
49122
  const runtimeToIndexerEnv = {
48827
49123
  production: "PRODUCTION",
48828
49124
  preproduction: "PREPRODUCTION",
@@ -48898,6 +49194,15 @@ var Zkp2pClient = class {
48898
49194
  getPvIntent: (intentHash) => this.getPvIntent(intentHash)
48899
49195
  }
48900
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
+ });
48901
49206
  }
48902
49207
  isValidHexAddress(addr) {
48903
49208
  return isValidHexAddress(addr);
@@ -48935,22 +49240,6 @@ var Zkp2pClient = class {
48935
49240
  `attestationServiceUrl is required when baseApiUrl is not a supported zkp2p API host: ${baseApiUrl}`
48936
49241
  );
48937
49242
  }
48938
- async resolveAuthorizationToken(opts) {
48939
- if (opts?.authorizationToken !== void 0) {
48940
- return opts.authorizationToken;
48941
- }
48942
- const provider = opts?.getAuthorizationToken ?? this.getAuthorizationToken;
48943
- if (provider) {
48944
- return await provider() ?? void 0;
48945
- }
48946
- return this.authorizationToken;
48947
- }
48948
- normalizeOracleRateConfig(config) {
48949
- return normalizeOracleRateConfig(config);
48950
- }
48951
- escrowCurrencyHasOracleConfig(abi) {
48952
- return escrowCurrencyHasOracleConfig(abi);
48953
- }
48954
49243
  /**
48955
49244
  * Normalizes currency tuples by appending an empty `oracleRateConfig` when the ABI
48956
49245
  * requires it and the caller hasn't provided one.
@@ -48963,21 +49252,9 @@ var Zkp2pClient = class {
48963
49252
  escrowAddress: params?.escrowAddress
48964
49253
  });
48965
49254
  }
48966
- parseManagerFeeFromRead(result) {
48967
- return parseManagerFeeFromRead(result);
48968
- }
48969
- getAbiFunction(abi, ...names) {
48970
- return getAbiFunction(abi, ...names);
48971
- }
48972
49255
  resolveAbiFunctionName(abi, names) {
48973
49256
  return resolveAbiFunctionName(abi, names);
48974
49257
  }
48975
- abiTupleHasComponent(abi, functionName, componentName) {
48976
- return abiTupleHasComponent(abi, functionName, componentName);
48977
- }
48978
- abiFunctionHasInput(abi, functionName, inputName) {
48979
- return abiFunctionHasInput(abi, functionName, inputName);
48980
- }
48981
49258
  resolveEscrowAddressOrThrow(escrowAddress, depositId, _methodName) {
48982
49259
  const resolved = escrowAddress ?? this.parseEscrowAddressFromCompositeDepositId(depositId);
48983
49260
  if (resolved) return resolved;
@@ -49103,7 +49380,7 @@ var Zkp2pClient = class {
49103
49380
  async lookupIntentEscrowOnchain(intentHash) {
49104
49381
  try {
49105
49382
  const view = await this.getPvIntent(intentHash);
49106
- return this.normalizeAddress(view?.intent?.escrow);
49383
+ return this.normalizeAddress(view.intent.escrow);
49107
49384
  } catch {
49108
49385
  return void 0;
49109
49386
  }
@@ -49168,6 +49445,15 @@ var Zkp2pClient = class {
49168
49445
  if (fallback) return fallback;
49169
49446
  throw new Error("Orchestrator not available");
49170
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
+ }
49171
49457
  /**
49172
49458
  * Simulate a contract call (validation only) and send with ERC-8021 attribution.
49173
49459
  * Referrer codes are stripped from overrides for simulation and appended to calldata.
@@ -49180,7 +49466,7 @@ var Zkp2pClient = class {
49180
49466
  functionName: opts.functionName,
49181
49467
  args: opts.args ?? [],
49182
49468
  account: this.walletClient.account,
49183
- ...txOverrides
49469
+ ...this.applyTxOverrides(txOverrides)
49184
49470
  });
49185
49471
  return sendTransactionWithAttribution(
49186
49472
  this.walletClient,
@@ -49207,7 +49493,7 @@ var Zkp2pClient = class {
49207
49493
  functionName: prepared.functionName,
49208
49494
  args: prepared.args,
49209
49495
  account: this.walletClient.account,
49210
- ...overrides
49496
+ ...this.applyTxOverrides(overrides)
49211
49497
  });
49212
49498
  return this.walletClient.sendTransaction({
49213
49499
  to: prepared.to,
@@ -49215,7 +49501,7 @@ var Zkp2pClient = class {
49215
49501
  value: prepared.value,
49216
49502
  account: this.walletClient.account,
49217
49503
  chain: this.walletClient.chain,
49218
- ...overrides
49504
+ ...this.applyTxOverrides(overrides)
49219
49505
  });
49220
49506
  }
49221
49507
  prepareEscrowTransaction(opts) {
@@ -49821,20 +50107,18 @@ var Zkp2pClient = class {
49821
50107
  if (params.processorNames.length !== payeeData.length) {
49822
50108
  throw new Error("processorNames and payeeData length mismatch");
49823
50109
  }
49824
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
50110
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
49825
50111
  const depositDetails = params.processorNames.map(
49826
50112
  (processorName, index) => toPostDepositDetailsRequest(processorName, payeeData[index], index)
49827
50113
  );
49828
50114
  const apiResponses = await Promise.all(
49829
50115
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
49830
50116
  );
49831
- if (!apiResponses.every((r) => r?.success)) {
49832
- const failed = apiResponses.find((r) => !r?.success);
50117
+ if (!apiResponses.every((r) => r.success)) {
50118
+ const failed = apiResponses.find((r) => !r.success);
49833
50119
  throw new Error(failed?.message || "Failed to register payee details");
49834
50120
  }
49835
- const hashedOnchainIds = apiResponses.map(
49836
- (r) => r.responseObject?.hashedOnchainId
49837
- );
50121
+ const hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
49838
50122
  return { depositDetails, hashedOnchainIds };
49839
50123
  }
49840
50124
  /**
@@ -49958,17 +50242,15 @@ var Zkp2pClient = class {
49958
50242
  }
49959
50243
  hashedOnchainIds = payeeDetailsHashes;
49960
50244
  } else {
49961
- const baseApiUrl = (this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(/\/$/, "");
50245
+ const baseApiUrl = (this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(/\/$/, "");
49962
50246
  const apiResponses = await Promise.all(
49963
50247
  depositDetails.map((req) => apiPostDepositDetails(req, baseApiUrl, this.apiTimeoutMs))
49964
50248
  );
49965
- if (!apiResponses.every((r) => r?.success)) {
49966
- const failed = apiResponses.find((r) => !r?.success);
50249
+ if (!apiResponses.every((r) => r.success)) {
50250
+ const failed = apiResponses.find((r) => !r.success);
49967
50251
  throw new Error(failed?.message || "Failed to create deposit details");
49968
50252
  }
49969
- hashedOnchainIds = apiResponses.map(
49970
- (r) => r.responseObject?.hashedOnchainId
49971
- );
50253
+ hashedOnchainIds = apiResponses.map((r) => r.responseObject.hashedOnchainId);
49972
50254
  }
49973
50255
  paymentMethodData = hashedOnchainIds.map((hid) => ({
49974
50256
  intentGatingService,
@@ -49990,10 +50272,10 @@ var Zkp2pClient = class {
49990
50272
  }
49991
50273
  });
49992
50274
  const { mapConversionRatesToOnchainMinRate: mapConversionRatesToOnchainMinRate2 } = await Promise.resolve().then(() => (init_currency(), currency_exports));
49993
- const normalized = params.conversionRates.map(
49994
- (group) => group.map((r) => ({ currency: r.currency, conversionRate: r.conversionRate }))
50275
+ currencies = mapConversionRatesToOnchainMinRate2(
50276
+ params.conversionRates,
50277
+ paymentMethods.length
49995
50278
  );
49996
- currencies = mapConversionRatesToOnchainMinRate2(normalized, paymentMethods.length);
49997
50279
  }
49998
50280
  const escrowContext = this.resolveEscrowContext({
49999
50281
  escrowAddress: params.escrowAddress
@@ -50085,9 +50367,6 @@ var Zkp2pClient = class {
50085
50367
  async prepareFulfillIntent(params) {
50086
50368
  return this._intentOps.prepareFulfillIntent(params);
50087
50369
  }
50088
- defaultAttestationService() {
50089
- return this._intentOps.defaultAttestationService();
50090
- }
50091
50370
  // ───────────────────────────────────────────────────────────────────────────
50092
50371
  // SUPPORTING: QUOTES API
50093
50372
  // (Used by frontends to find available liquidity)
@@ -50135,7 +50414,7 @@ var Zkp2pClient = class {
50135
50414
  */
50136
50415
  async getQuote(req, opts) {
50137
50416
  const referrerFeeConfig = assertValidReferrerFeeConfig(req.referrerFeeConfig, "getQuote");
50138
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50417
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50139
50418
  /\/$/,
50140
50419
  ""
50141
50420
  );
@@ -50150,9 +50429,8 @@ var Zkp2pClient = class {
50150
50429
  const quote = await apiGetQuote(reqWithEscrow, baseApiUrl, timeoutMs, this.apiKey);
50151
50430
  const quotes = quote?.responseObject?.quotes ?? [];
50152
50431
  for (const q of quotes) {
50153
- const maker = q?.maker;
50154
- const payeeData = normalizeQuotePayeeData(maker);
50155
- if (payeeData && typeof q === "object") {
50432
+ const payeeData = normalizeQuotePayeeData(q.maker);
50433
+ if (payeeData) {
50156
50434
  q.payeeData = payeeData;
50157
50435
  }
50158
50436
  }
@@ -50173,7 +50451,7 @@ var Zkp2pClient = class {
50173
50451
  req.referrerFeeConfig,
50174
50452
  "getQuotesBestByPlatform"
50175
50453
  );
50176
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50454
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50177
50455
  /\/$/,
50178
50456
  ""
50179
50457
  );
@@ -50222,7 +50500,7 @@ var Zkp2pClient = class {
50222
50500
  * @returns Taker tier response
50223
50501
  */
50224
50502
  async getTakerTier(req, opts) {
50225
- const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? "https://api.zkp2p.xyz").replace(
50503
+ const baseApiUrl = (opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL).replace(
50226
50504
  /\/$/,
50227
50505
  ""
50228
50506
  );
@@ -50230,49 +50508,62 @@ var Zkp2pClient = class {
50230
50508
  return apiGetTakerTier(req, baseApiUrl, timeoutMs);
50231
50509
  }
50232
50510
  /**
50233
- * Fetch the authenticated user's referral dashboard, including their generated
50234
- * code, reward rates, referee counts, and lifetime referral fees.
50511
+ * Fetch a referral dashboard. Pass `address` for a public wallet-keyed read;
50512
+ * omit it to use the authenticated caller mode.
50235
50513
  */
50236
50514
  async getReferralDashboard(opts) {
50237
- const baseApiUrl = this.stripTrailingSlash(
50238
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
50239
- );
50240
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
50241
- const authorizationToken = await this.resolveAuthorizationToken(opts);
50242
- return apiGetReferralDashboard({ baseApiUrl, timeoutMs, authorizationToken });
50515
+ return this._referralOps.getReferralDashboard(opts);
50243
50516
  }
50244
50517
  /**
50245
- * Fetch the authenticated user's referral earnings totals.
50518
+ * Fetch referral earnings. Pass `address` for a public wallet-keyed read;
50519
+ * omit it to use the authenticated caller mode.
50246
50520
  */
50247
50521
  async getReferralEarnings(opts) {
50248
- const baseApiUrl = this.stripTrailingSlash(
50249
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
50250
- );
50251
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
50252
- const authorizationToken = await this.resolveAuthorizationToken(opts);
50253
- return apiGetReferralEarnings({ baseApiUrl, timeoutMs, authorizationToken });
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);
50254
50529
  }
50255
50530
  /**
50256
- * Apply another user's referral code to the authenticated account.
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.
50257
50544
  */
50258
50545
  async redeemReferralCode(code, opts) {
50259
- const baseApiUrl = this.stripTrailingSlash(
50260
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
50261
- );
50262
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
50263
- const authorizationToken = await this.resolveAuthorizationToken(opts);
50264
- return apiRedeemReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
50546
+ return this._referralOps.redeemReferralCode(code, opts);
50265
50547
  }
50266
50548
  /**
50267
- * Customize the authenticated user's own referral code.
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.
50268
50558
  */
50269
50559
  async updateReferralCode(code, opts) {
50270
- const baseApiUrl = this.stripTrailingSlash(
50271
- opts?.baseApiUrl ?? this.baseApiUrl ?? DEFAULT_BASE_API_URL
50272
- );
50273
- const timeoutMs = opts?.timeoutMs ?? this.apiTimeoutMs;
50274
- const authorizationToken = await this.resolveAuthorizationToken(opts);
50275
- return apiUpdateReferralCode({ code }, { baseApiUrl, timeoutMs, authorizationToken });
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);
50276
50567
  }
50277
50568
  /**
50278
50569
  * The signed `credentialValidatedAt` field is an upload-time freshness witness minted by
@@ -50294,44 +50585,14 @@ var Zkp2pClient = class {
50294
50585
  const attestationServiceUrl = this.stripTrailingSlash(
50295
50586
  opts?.attestationServiceUrl ?? this.defaultAttestationServiceForBaseApiUrl(baseApiUrl)
50296
50587
  );
50297
- const createBundle = (uploadPayload) => {
50298
- const requestOptions = opts?.attestationServiceFallbackUrls ? { fallbackUrls: opts.attestationServiceFallbackUrls } : void 0;
50299
- if (opts?.attestationRuntime && requestOptions) {
50300
- return apiCreateSellerCredentialBundle(
50301
- uploadPayload,
50302
- attestationServiceUrl,
50303
- params.platform,
50304
- timeoutMs,
50305
- opts.attestationRuntime,
50306
- requestOptions
50307
- );
50308
- }
50309
- if (opts?.attestationRuntime) {
50310
- return apiCreateSellerCredentialBundle(
50311
- uploadPayload,
50312
- attestationServiceUrl,
50313
- params.platform,
50314
- timeoutMs,
50315
- opts.attestationRuntime
50316
- );
50317
- }
50318
- if (requestOptions) {
50319
- return apiCreateSellerCredentialBundle(
50320
- uploadPayload,
50321
- attestationServiceUrl,
50322
- params.platform,
50323
- timeoutMs,
50324
- void 0,
50325
- requestOptions
50326
- );
50327
- }
50328
- return apiCreateSellerCredentialBundle(
50329
- uploadPayload,
50330
- attestationServiceUrl,
50331
- params.platform,
50332
- timeoutMs
50333
- );
50334
- };
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
+ );
50335
50596
  if (params.platform === "wise") {
50336
50597
  const bundleResponse2 = await createBundle({
50337
50598
  sessionMaterial: params.sessionMaterial
@@ -50477,19 +50738,6 @@ var Zkp2pClient = class {
50477
50738
  protocolViewerFunctionInputCount(functionName) {
50478
50739
  return this._pvReader.protocolViewerFunctionInputCount(functionName);
50479
50740
  }
50480
- /**
50481
- * Returns the input count for a function on a specific PV entry's ABI.
50482
- * Used to branch between 1-input (V1) and 2-input (V2) PV call signatures.
50483
- */
50484
- pvEntryFunctionInputCount(entry, functionName) {
50485
- return this._pvReader.pvEntryFunctionInputCount(entry, functionName);
50486
- }
50487
- isZeroAddressValue(value) {
50488
- return this._pvReader.isZeroAddressValue(value);
50489
- }
50490
- toBigIntOrZero(value, fieldName = "numeric field") {
50491
- return this._pvReader.toBigIntOrZero(value, fieldName);
50492
- }
50493
50741
  buildProtocolViewerContexts(options) {
50494
50742
  return this._pvReader.buildProtocolViewerContexts(options);
50495
50743
  }
@@ -50502,9 +50750,6 @@ var Zkp2pClient = class {
50502
50750
  buildDepositViewFromEscrowDeposit(rawDeposit, depositId) {
50503
50751
  return this._pvReader.buildDepositViewFromEscrowDeposit(rawDeposit, depositId);
50504
50752
  }
50505
- convertIndexerDepositToPvView(deposit) {
50506
- return this._pvReader.convertIndexerDepositToPvView(deposit);
50507
- }
50508
50753
  async getPvAccountDepositsFromIndexer(owner) {
50509
50754
  return this._pvReader.getPvAccountDepositsFromIndexer(owner);
50510
50755
  }
@@ -50751,6 +50996,8 @@ exports.PLATFORM_METADATA = PLATFORM_METADATA;
50751
50996
  exports.PYTH_CONTRACT_BASE = PYTH_CONTRACT_BASE;
50752
50997
  exports.PYTH_ORACLE_ADAPTER = PYTH_ORACLE_ADAPTER;
50753
50998
  exports.PYTH_ORACLE_FEEDS = PYTH_ORACLE_FEEDS;
50999
+ exports.REFERRAL_SIGNATURE_DOMAIN = REFERRAL_SIGNATURE_DOMAIN;
51000
+ exports.REFERRAL_SIGNATURE_TYPES = REFERRAL_SIGNATURE_TYPES;
50754
51001
  exports.SPREAD_ORACLE_FEEDS = SPREAD_ORACLE_FEEDS;
50755
51002
  exports.SUPPORTED_CHAIN_IDS = SUPPORTED_CHAIN_IDS;
50756
51003
  exports.TAKER_TIER_CAPS = TAKER_TIER_CAPS;
@@ -50762,6 +51009,7 @@ exports.ZERO_RATE_MANAGER_ID = ZERO_RATE_MANAGER_ID;
50762
51009
  exports.ZKP2P_ANDROID_REFERRER = ZKP2P_ANDROID_REFERRER;
50763
51010
  exports.ZKP2P_IOS_REFERRER = ZKP2P_IOS_REFERRER;
50764
51011
  exports.Zkp2pClient = Zkp2pClient;
51012
+ exports.apiCreateReferralCode = apiCreateReferralCode;
50765
51013
  exports.apiCreateSellerCredentialBundle = apiCreateSellerCredentialBundle;
50766
51014
  exports.apiGetDepositBundle = apiGetDepositBundle;
50767
51015
  exports.apiGetOrderbook = apiGetOrderbook;
@@ -50771,6 +51019,7 @@ exports.apiGetQuotesBestByPlatform = apiGetQuotesBestByPlatform;
50771
51019
  exports.apiGetReferralDashboard = apiGetReferralDashboard;
50772
51020
  exports.apiGetReferralEarnings = apiGetReferralEarnings;
50773
51021
  exports.apiGetTakerTier = apiGetTakerTier;
51022
+ exports.apiLookupReferralCode = apiLookupReferralCode;
50774
51023
  exports.apiPostDepositDetails = apiPostDepositDetails;
50775
51024
  exports.apiRedeemReferralCode = apiRedeemReferralCode;
50776
51025
  exports.apiRequestIdentityAttestation = apiRequestIdentityAttestation;