@provex/indexer-client 1.11.0 → 2.0.0

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.js CHANGED
@@ -2472,6 +2472,63 @@ var require_partition = __commonJS({
2472
2472
  }
2473
2473
  });
2474
2474
 
2475
+ // ../../node_modules/lodash/_defineProperty.js
2476
+ var require_defineProperty = __commonJS({
2477
+ "../../node_modules/lodash/_defineProperty.js"(exports, module) {
2478
+ "use strict";
2479
+ var getNative = require_getNative();
2480
+ var defineProperty = function() {
2481
+ try {
2482
+ var func = getNative(Object, "defineProperty");
2483
+ func({}, "", {});
2484
+ return func;
2485
+ } catch (e) {
2486
+ }
2487
+ }();
2488
+ module.exports = defineProperty;
2489
+ }
2490
+ });
2491
+
2492
+ // ../../node_modules/lodash/_baseAssignValue.js
2493
+ var require_baseAssignValue = __commonJS({
2494
+ "../../node_modules/lodash/_baseAssignValue.js"(exports, module) {
2495
+ "use strict";
2496
+ var defineProperty = require_defineProperty();
2497
+ function baseAssignValue(object, key, value) {
2498
+ if (key == "__proto__" && defineProperty) {
2499
+ defineProperty(object, key, {
2500
+ "configurable": true,
2501
+ "enumerable": true,
2502
+ "value": value,
2503
+ "writable": true
2504
+ });
2505
+ } else {
2506
+ object[key] = value;
2507
+ }
2508
+ }
2509
+ module.exports = baseAssignValue;
2510
+ }
2511
+ });
2512
+
2513
+ // ../../node_modules/lodash/groupBy.js
2514
+ var require_groupBy = __commonJS({
2515
+ "../../node_modules/lodash/groupBy.js"(exports, module) {
2516
+ "use strict";
2517
+ var baseAssignValue = require_baseAssignValue();
2518
+ var createAggregator = require_createAggregator();
2519
+ var objectProto = Object.prototype;
2520
+ var hasOwnProperty = objectProto.hasOwnProperty;
2521
+ var groupBy2 = createAggregator(function(result, value, key) {
2522
+ if (hasOwnProperty.call(result, key)) {
2523
+ result[key].push(value);
2524
+ } else {
2525
+ baseAssignValue(result, key, [value]);
2526
+ }
2527
+ });
2528
+ module.exports = groupBy2;
2529
+ }
2530
+ });
2531
+
2475
2532
  // ../../node_modules/lodash/isEqual.js
2476
2533
  var require_isEqual = __commonJS({
2477
2534
  "../../node_modules/lodash/isEqual.js"(exports, module) {
@@ -9151,13 +9208,10 @@ var intentExpiryExtendedReferences = relations(intentExpiryExtended, ({ one }) =
9151
9208
 
9152
9209
  // src/lib/env.ts
9153
9210
  function readEnvVar(name) {
9154
- try {
9155
- const value = import.meta.env?.[name];
9156
- if (value) return value;
9157
- } catch {
9158
- }
9159
- if (typeof process !== "undefined" && process.env?.[name]) return process.env[name];
9160
- return void 0;
9211
+ const viteValue = import.meta.env?.[name];
9212
+ if (viteValue) return viteValue;
9213
+ if (typeof process === "undefined") return void 0;
9214
+ return process.env[name] || void 0;
9161
9215
  }
9162
9216
 
9163
9217
  // ../token-indexer/ponder.schema.ts
@@ -9793,8 +9847,7 @@ var Deposit = class {
9793
9847
  get lowestUsdConversionRate() {
9794
9848
  const usdRates = this.usdConversionRates;
9795
9849
  let currentRate = null;
9796
- for (const [, rate] of usdRates.entries()) {
9797
- if (!rate) continue;
9850
+ for (const rate of usdRates.values()) {
9798
9851
  if (!rate.value) continue;
9799
9852
  if (!currentRate || BigInt(currentRate.value) < BigInt(rate.value)) {
9800
9853
  currentRate = rate;
@@ -9807,12 +9860,8 @@ var Deposit = class {
9807
9860
  if (lowestUsdRate) {
9808
9861
  return lowestUsdRate;
9809
9862
  }
9810
- for (const currencyMap of this.currentConversionRates.values()) {
9811
- for (const rate of currencyMap.values()) {
9812
- return rate;
9813
- }
9814
- }
9815
- return null;
9863
+ const [firstProviderRates] = this.currentConversionRates.values();
9864
+ return firstProviderRates?.values().next().value ?? null;
9816
9865
  }
9817
9866
  /**
9818
9867
  * Set of lowercased `paymentMethodId` hex hashes for every payment method
@@ -9971,35 +10020,33 @@ var Deposit = class {
9971
10020
  * UI that wants to render inactive provider cards with a muted treatment.
9972
10021
  */
9973
10022
  isProviderActive(key) {
9974
- const chainId = this.chainId;
9975
- const expectedContractId = providerKeyToContractId(key).toLowerCase();
9976
- const row = this.depositVerifierAddeds.find((added) => {
9977
- const v2Match = verifierGetsKey(chainId, added.verifier) === key;
9978
- if (v2Match) return true;
9979
- if ("paymentMethodId" in added && added.paymentMethodId) {
9980
- if (added.paymentMethodId.toLowerCase() === expectedContractId) return true;
9981
- if (verifierGetsKey(chainId, added.paymentMethodId) === key) return true;
9982
- }
9983
- return false;
9984
- });
10023
+ const row = this.depositVerifierAddeds.find((added) => this.verifierRowMatchesProvider(added, key));
9985
10024
  if (!row) return false;
9986
10025
  return !("active" in row) || row.active !== false;
9987
10026
  }
9988
- getVerifier(key) {
10027
+ /**
10028
+ * Whether a `depositVerifierAdded` row belongs to a provider. A V2 row
10029
+ * matches by its verifier address. A V3 row matches by the provider's contract
10030
+ * id in `paymentMethodId`, or by a `paymentMethodId` that `verifierGetsKey`
10031
+ * resolves to the provider (for example a V2 verifier address).
10032
+ */
10033
+ verifierRowMatchesProvider(added, key) {
9989
10034
  const chainId = this.chainId;
9990
- const expectedContractId = providerKeyToContractId(key).toLowerCase();
9991
- return this.depositVerifierAddeds.find((added) => {
9992
- if ("active" in added && added.active === false) return false;
9993
- const v2Match = verifierGetsKey(chainId, added.verifier) === key;
9994
- if (v2Match) return true;
9995
- if ("paymentMethodId" in added && added.paymentMethodId) {
9996
- const directMatch = added.paymentMethodId.toLowerCase() === expectedContractId;
9997
- if (directMatch) return true;
9998
- const reverseMatch = verifierGetsKey(chainId, added.paymentMethodId) === key;
9999
- if (reverseMatch) return true;
10000
- }
10001
- return false;
10002
- }) ?? null;
10035
+ if (verifierGetsKey(chainId, added.verifier) === key) return true;
10036
+ if (!("paymentMethodId" in added) || !added.paymentMethodId) return false;
10037
+ if (added.paymentMethodId.toLowerCase() === providerKeyToContractId(key).toLowerCase()) return true;
10038
+ return verifierGetsKey(chainId, added.paymentMethodId) === key;
10039
+ }
10040
+ /**
10041
+ * The ACTIVE verifier row for a provider, or null. A row the maker switched
10042
+ * off with `setPaymentMethodActive(false)` is skipped. Rows from before the
10043
+ * `active` field existed have no such property and count as active, so older
10044
+ * data stays visible.
10045
+ */
10046
+ getVerifier(key) {
10047
+ return this.depositVerifierAddeds.find(
10048
+ (added) => !("active" in added && added.active === false) && this.verifierRowMatchesProvider(added, key)
10049
+ ) ?? null;
10003
10050
  }
10004
10051
  providerByIntentHash(hash) {
10005
10052
  const signal = this.intentSignaleds.find((intent) => intent.intentHash === hash);
@@ -11165,6 +11212,7 @@ async function searchEasAttestationsByHandle(args) {
11165
11212
  }
11166
11213
 
11167
11214
  // src/hooks/useMatchableDeposits.ts
11215
+ var import_groupBy = __toESM(require_groupBy(), 1);
11168
11216
  import { useMemo, useCallback } from "react";
11169
11217
  import { useQuery } from "@tanstack/react-query";
11170
11218
  import { and as and9, eq as eq11, desc as desc8, sql as sql7 } from "@ponder/client";
@@ -11195,13 +11243,11 @@ var getRate = ({
11195
11243
  const value = deposit2.currentConversionRates.get(paymentMethod2)?.get(currency.contractId)?.value;
11196
11244
  return value ? BigInt(value) : 0n;
11197
11245
  };
11198
- var compareRatedDeposits = (a, b) => {
11199
- if (a.rate < b.rate) return -1;
11200
- if (a.rate > b.rate) return 1;
11201
- if (a.deposit.depositId < b.deposit.depositId) return -1;
11202
- if (a.deposit.depositId > b.deposit.depositId) return 1;
11203
- return 0;
11246
+ var compareAscending = (a, b) => {
11247
+ if (a < b) return -1;
11248
+ return a > b ? 1 : 0;
11204
11249
  };
11250
+ var compareRatedDeposits = (a, b) => compareAscending(a.rate, b.rate) || compareAscending(a.deposit.depositId, b.deposit.depositId);
11205
11251
  function rankDepositsThatFillAmount({
11206
11252
  deposits,
11207
11253
  providerKey,
@@ -11238,7 +11284,6 @@ function fillableRangeOf({
11238
11284
  const minimumAmountInCurrency = minimumCurrencyAmountForTokenAmount({ token: token2, currency, tokenAmount: tokenMinimum, rate });
11239
11285
  const maximumAmountInCurrency = maximumCurrencyAmountForTokenAmount({ token: token2, currency, tokenAmount: tokenMaximum, rate });
11240
11286
  if (minimumAmountInCurrency === null || maximumAmountInCurrency === null) return null;
11241
- if (minimumAmountInCurrency <= 0n) return null;
11242
11287
  if (maximumAmountInCurrency < minimumAmountInCurrency) return null;
11243
11288
  return { deposit: deposit2, rate, minimumAmountInCurrency, maximumAmountInCurrency };
11244
11289
  }
@@ -11275,20 +11320,12 @@ function summarizeEscrowedAmountByProvider({
11275
11320
  }) {
11276
11321
  const totals = /* @__PURE__ */ new Map();
11277
11322
  for (const summary of summaries) {
11278
- const total = summary.fillableRanges.reduce((sum2, range) => {
11279
- const availableFunds = range.deposit.availableFunds;
11280
- return availableFunds > 0n ? sum2 + availableFunds : sum2;
11281
- }, 0n);
11323
+ const total = summary.fillableRanges.reduce((sum2, range) => sum2 + range.deposit.availableFunds, 0n);
11282
11324
  totals.set(summary.providerKey, total);
11283
11325
  }
11284
11326
  return totals;
11285
11327
  }
11286
- var compareBounds = (a, b) => {
11287
- if (a.distance !== b.distance) return a.distance < b.distance ? -1 : 1;
11288
- if (a.rate !== b.rate) return a.rate < b.rate ? -1 : 1;
11289
- if (a.providerKey !== b.providerKey) return a.providerKey < b.providerKey ? -1 : 1;
11290
- return 0;
11291
- };
11328
+ var compareBounds = (a, b) => compareAscending(a.distance, b.distance) || compareAscending(a.rate, b.rate) || compareAscending(a.providerKey, b.providerKey);
11292
11329
  function sellerLimitReason(deposit2) {
11293
11330
  return deposit2.availableFunds < deposit2.maxAmount ? "sellerFunds" : "sellerOrderMaximum";
11294
11331
  }
@@ -11368,13 +11405,9 @@ function findNearestWorkableAmount(summaries, amountInCurrency, options = {}) {
11368
11405
  return { direction: "lower", reason: nearest.reason, amountInCurrency: nearest.amountInCurrency, providerKey: nearest.providerKey };
11369
11406
  }
11370
11407
  function listProvidersWithLiquidity(summaries) {
11371
- return summaries.filter((summary) => summary.hasLiquidity).sort((a, b) => {
11372
- const bestRateA = a.fillableRanges[0].rate;
11373
- const bestRateB = b.fillableRanges[0].rate;
11374
- if (bestRateA !== bestRateB) return bestRateA < bestRateB ? -1 : 1;
11375
- if (a.providerKey !== b.providerKey) return a.providerKey < b.providerKey ? -1 : 1;
11376
- return 0;
11377
- }).map((summary) => summary.providerKey);
11408
+ return summaries.filter((summary) => summary.hasLiquidity).sort(
11409
+ (a, b) => compareAscending(a.fillableRanges[0].rate, b.fillableRanges[0].rate) || compareAscending(a.providerKey, b.providerKey)
11410
+ ).map((summary) => summary.providerKey);
11378
11411
  }
11379
11412
 
11380
11413
  // src/hooks/useMatchableDeposits.ts
@@ -11505,27 +11538,8 @@ async function fetchMatchableDepositsForProviders({
11505
11538
  if (filteredDepositsData.length === 0) {
11506
11539
  return [];
11507
11540
  }
11508
- const ratesByDeposit = /* @__PURE__ */ new Map();
11509
- const verifiersByDeposit = /* @__PURE__ */ new Map();
11510
- for (const d of filteredDepositsData) {
11511
- const key = `${d.escrow}-${d.localId}-${d.chainId}`;
11512
- ratesByDeposit.set(key, []);
11513
- verifiersByDeposit.set(key, []);
11514
- }
11515
- for (const rate of allConversionRates) {
11516
- const key = `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`;
11517
- const existing = ratesByDeposit.get(key);
11518
- if (existing) {
11519
- existing.push(rate);
11520
- }
11521
- }
11522
- for (const verifier2 of allVerifiers) {
11523
- const key = `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`;
11524
- const existing = verifiersByDeposit.get(key);
11525
- if (existing) {
11526
- existing.push(verifier2);
11527
- }
11528
- }
11541
+ const ratesByDeposit = (0, import_groupBy.default)(allConversionRates, (rate) => `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`);
11542
+ const verifiersByDeposit = (0, import_groupBy.default)(allVerifiers, (verifier2) => `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`);
11529
11543
  const resolvedIntentHashes = /* @__PURE__ */ new Set([
11530
11544
  ...allUnlocked.map((u) => u.intentHash),
11531
11545
  ...allTransferred.map((t) => t.intentHash)
@@ -11546,8 +11560,8 @@ async function fetchMatchableDepositsForProviders({
11546
11560
  }
11547
11561
  return filteredDepositsData.map((deposit2) => {
11548
11562
  const key = `${deposit2.escrow}-${deposit2.localId}-${deposit2.chainId}`;
11549
- const rates = ratesByDeposit.get(key) ?? [];
11550
- const verifiers = verifiersByDeposit.get(key) ?? [];
11563
+ const rates = ratesByDeposit[key] ?? [];
11564
+ const verifiers = verifiersByDeposit[key] ?? [];
11551
11565
  const depositId = orderId3.deposit.serialize({
11552
11566
  escrow: deposit2.escrow,
11553
11567
  chainId: deposit2.chainId,
@@ -11665,7 +11679,7 @@ function useMatchableDeposits(options) {
11665
11679
  return allDeposits.filter((deposit2) => hasActiveVerifierFor(deposit2, ids));
11666
11680
  }, [allDeposits, token2.chainId, paymentMethod2]);
11667
11681
  const filterDepositsByAmount = useCallback((amountInInt) => {
11668
- if (!amountInInt || !currency) return [];
11682
+ if (!amountInInt) return [];
11669
11683
  return rankDepositsThatFillAmount({
11670
11684
  deposits,
11671
11685
  providerKey: paymentMethod2,
@@ -11689,7 +11703,7 @@ function useMatchableDeposits(options) {
11689
11703
  // eslint-disable-next-line react-hooks/exhaustive-deps
11690
11704
  getMatchableDeposits: useCallback((amountInInt) => {
11691
11705
  if (typeof amountInInt === "string") {
11692
- amountInInt = parseUnits(amountInInt, { decimals: currency?.decimals || 2 });
11706
+ amountInInt = parseUnits(amountInInt, { decimals: currency.decimals });
11693
11707
  }
11694
11708
  if (!amountInInt) return [];
11695
11709
  return filterDepositsByAmount(amountInInt);
@@ -11949,11 +11963,19 @@ import { and as and11, desc as desc10, inArray as inArray4, eq as eq13 } from "@
11949
11963
  import { getLatestContract } from "@provex/utils/contracts";
11950
11964
  import { chains } from "@provex/utils/chain";
11951
11965
  import { interval as interval2 } from "@provex/utils/time";
11952
- import { statAction, isStatAction } from "@provex/utils/stats";
11966
+ import { statAction } from "@provex/utils/stats";
11953
11967
  var statsRequestCache = /* @__PURE__ */ new Map();
11954
11968
  var monthlyStatsCache = /* @__PURE__ */ new Map();
11955
11969
  var liquidityBaselineCache = /* @__PURE__ */ new Map();
11956
11970
  var CACHE_EXPIRATION_MS = interval2.second * 10;
11971
+ var liquidityActions = /* @__PURE__ */ new Set([
11972
+ statAction.deposit,
11973
+ statAction.withdrawal,
11974
+ statAction.exchange,
11975
+ statAction.fee,
11976
+ statAction.dust
11977
+ ]);
11978
+ var isLiquidityAction = (action) => liquidityActions.has(action);
11957
11979
  function generateStatsRequestCacheKey({
11958
11980
  chainIds,
11959
11981
  after,
@@ -11961,7 +11983,7 @@ function generateStatsRequestCacheKey({
11961
11983
  lowerBoundTimestamp,
11962
11984
  upperBoundTimestamp
11963
11985
  }) {
11964
- const chainKey = chainIds.length === 0 ? "all-chains" : chainIds.slice().sort((a, b) => a - b).join(",");
11986
+ const chainKey = chainIds.slice().sort((a, b) => a - b).join(",");
11965
11987
  const timeRange = upperBoundTimestamp ? `${lowerBoundTimestamp}-${upperBoundTimestamp}` : `${lowerBoundTimestamp}-end`;
11966
11988
  return `${chainKey}:${resolution}:${timeRange}:${after || "start"}`;
11967
11989
  }
@@ -11992,18 +12014,7 @@ var fetchStats = async ({
11992
12014
  after,
11993
12015
  resolution = "month"
11994
12016
  }) => {
11995
- const whereClause = {
11996
- type: resolution,
11997
- timestamp_gte: lowerBoundTimestamp / 1e3
11998
- };
11999
- if (upperBoundTimestamp) {
12000
- whereClause.timestamp_lt = upperBoundTimestamp / 1e3;
12001
- }
12002
12017
  const cIds = chainIds.length > 0 ? chainIds : chains.map((c) => c.id);
12003
- whereClause.OR = cIds.map((chainId) => ({
12004
- chainId,
12005
- token: getLatestContract(chainId, "usdc").toLowerCase()
12006
- }));
12007
12018
  const cacheKey = generateStatsRequestCacheKey({
12008
12019
  chainIds: cIds,
12009
12020
  after,
@@ -12025,10 +12036,8 @@ var fetchStats = async ({
12025
12036
  if (chainIds.length > 0) {
12026
12037
  conditions.push(inArray4(ponder_schema_exports.stat.chainId, chainIds.map((id) => BigInt(id))));
12027
12038
  }
12028
- if (tokenAddresses.length > 0) {
12029
- conditions.push(inArray4(ponder_schema_exports.stat.token, tokenAddresses));
12030
- }
12031
- const statsData = await db.select().from(ponder_schema_exports.stat).where(conditions.length > 0 ? and11(...conditions) : void 0).orderBy(desc10(ponder_schema_exports.stat.orderId)).limit(1e3);
12039
+ conditions.push(inArray4(ponder_schema_exports.stat.token, tokenAddresses));
12040
+ const statsData = await db.select().from(ponder_schema_exports.stat).where(and11(...conditions)).orderBy(desc10(ponder_schema_exports.stat.orderId)).limit(1e3);
12032
12041
  const mappedStats = statsData.map((stat2) => ({
12033
12042
  ...stat2,
12034
12043
  action: stat2.event
@@ -12050,6 +12059,12 @@ var fetchStats = async ({
12050
12059
  });
12051
12060
  return data;
12052
12061
  };
12062
+ var rankDescending = (items, selectAmount) => Array.from(items).sort((a, b) => {
12063
+ const amountA = selectAmount(a);
12064
+ const amountB = selectAmount(b);
12065
+ if (amountA === amountB) return 0;
12066
+ return amountB > amountA ? 1 : -1;
12067
+ });
12053
12068
  var orderIdToTimestamp = (id) => Number(orderId4.stat.parse(id).timestamp * 1000n);
12054
12069
  var groupStatsByTime = (stats) => {
12055
12070
  const timeAggregationMap = /* @__PURE__ */ new Map();
@@ -12107,8 +12122,7 @@ var fetchLiquidityBaseline = async ({
12107
12122
  }) => {
12108
12123
  const cIds = chainIds.length > 0 ? chainIds : chains.map((c) => c.id);
12109
12124
  const targetDate = new Date(targetTimestamp);
12110
- const monthStart = new Date(targetDate.getUTCFullYear(), targetDate.getUTCMonth(), 1);
12111
- const monthStartTimestamp = (/* @__PURE__ */ new Date(`${monthStart.getUTCFullYear()}-${(monthStart.getUTCMonth() + 1).toString().padStart(2, "0")}-01T00:00:00.000Z`)).getTime();
12125
+ const monthStartTimestamp = Date.UTC(targetDate.getUTCFullYear(), targetDate.getUTCMonth(), 1);
12112
12126
  const cacheKey = generateLiquidityBaselineCacheKey({
12113
12127
  chainIds: cIds,
12114
12128
  targetTimestamp,
@@ -12130,7 +12144,7 @@ var fetchLiquidityBaseline = async ({
12130
12144
  upperBoundTimestamp: monthStartTimestamp
12131
12145
  });
12132
12146
  const allStatsForTimeGrouping = monthlyData.stats.items.filter((stat2) => {
12133
- return Number(stat2.timestamp) * 1e3 < monthStartTimestamp && isStatAction(stat2.action);
12147
+ return Number(stat2.timestamp) * 1e3 < monthStartTimestamp && isLiquidityAction(stat2.action);
12134
12148
  });
12135
12149
  const baseline = allStatsForTimeGrouping.reduce((acc, stat2) => {
12136
12150
  let amount = stat2.amount;
@@ -12139,44 +12153,13 @@ var fetchLiquidityBaseline = async ({
12139
12153
  }
12140
12154
  return acc + amount;
12141
12155
  }, 0n);
12142
- const currentPeriodStats = [];
12143
- let hasNextPage = true;
12144
- let after = void 0;
12145
- let iterations = 0;
12146
- const maxIterations = 50;
12147
- let previousCursor = void 0;
12148
- const seenCursors = /* @__PURE__ */ new Set();
12149
- while (hasNextPage && iterations < maxIterations) {
12150
- iterations++;
12151
- const detailedData = await fetchStats({
12152
- lowerBoundTimestamp: monthStartTimestamp,
12153
- chainIds: cIds,
12154
- after,
12155
- resolution
12156
- });
12157
- const batch = detailedData.stats.items;
12158
- if (batch.length === 0) break;
12159
- const relevantStats = batch.filter((stat2) => {
12160
- const statTimestamp = orderIdToTimestamp(stat2.orderId);
12161
- return statTimestamp >= monthStartTimestamp && isStatAction(stat2.action);
12162
- });
12163
- currentPeriodStats.push(...relevantStats);
12164
- const oldestInBatch = batch[batch.length - 1];
12165
- if (oldestInBatch && orderIdToTimestamp(oldestInBatch.orderId) < monthStartTimestamp) {
12166
- break;
12167
- }
12168
- hasNextPage = detailedData.stats.pageInfo.hasNextPage;
12169
- const newCursor = detailedData.stats.pageInfo.endCursor || void 0;
12170
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12171
- console.warn("Liquidity baseline pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12172
- break;
12173
- }
12174
- if (newCursor) {
12175
- seenCursors.add(newCursor);
12176
- }
12177
- previousCursor = after;
12178
- after = newCursor;
12179
- }
12156
+ const detailedData = await fetchStats({
12157
+ lowerBoundTimestamp: monthStartTimestamp,
12158
+ chainIds: cIds,
12159
+ after: void 0,
12160
+ resolution
12161
+ });
12162
+ const currentPeriodStats = detailedData.stats.items.filter((stat2) => orderIdToTimestamp(stat2.orderId) >= monthStartTimestamp && isLiquidityAction(stat2.action));
12180
12163
  const result = {
12181
12164
  baseline,
12182
12165
  currentPeriodStats,
@@ -12210,45 +12193,13 @@ var fetchComprehensiveStats = async ({
12210
12193
  const allStats = [...currentPeriodStats];
12211
12194
  const needsAdditionalStats = currentPeriodStats.length === 0 || currentPeriodStats.some((stat2) => orderIdToTimestamp(stat2.orderId) < lowerBoundTimestamp);
12212
12195
  if (needsAdditionalStats) {
12213
- let hasNextPage = true;
12214
- let after = void 0;
12215
- let iterations = 0;
12216
- const maxIterations = 50;
12217
- let previousCursor = void 0;
12218
- const seenCursors = /* @__PURE__ */ new Set();
12219
- while (hasNextPage && iterations < maxIterations) {
12220
- iterations++;
12221
- const data = await fetchStats({
12222
- chainIds: cIds,
12223
- after,
12224
- resolution,
12225
- lowerBoundTimestamp
12226
- });
12227
- const batch = data.stats.items;
12228
- if (batch.length === 0) break;
12229
- const windowStats = batch.filter((stat2) => {
12230
- const timestamp2 = orderIdToTimestamp(stat2.orderId);
12231
- return timestamp2 >= lowerBoundTimestamp;
12232
- });
12233
- allStats.push(...windowStats);
12234
- if (batch.length > 0) {
12235
- const item = batch[batch.length - 1];
12236
- if (item && orderIdToTimestamp(item.orderId) < lowerBoundTimestamp) {
12237
- break;
12238
- }
12239
- }
12240
- hasNextPage = data.stats.pageInfo.hasNextPage;
12241
- const newCursor = data.stats.pageInfo.endCursor || void 0;
12242
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12243
- console.warn("Comprehensive stats pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12244
- break;
12245
- }
12246
- if (newCursor) {
12247
- seenCursors.add(newCursor);
12248
- }
12249
- previousCursor = after;
12250
- after = newCursor;
12251
- }
12196
+ const data = await fetchStats({
12197
+ chainIds: cIds,
12198
+ after: void 0,
12199
+ resolution,
12200
+ lowerBoundTimestamp
12201
+ });
12202
+ allStats.push(...data.stats.items.filter((stat2) => orderIdToTimestamp(stat2.orderId) >= lowerBoundTimestamp));
12252
12203
  }
12253
12204
  const uniqueStats = Array.from(
12254
12205
  new Map(allStats.map((stat2) => [stat2.orderId, stat2])).values()
@@ -12296,45 +12247,13 @@ function useMonthlyStats({
12296
12247
  setOrderedLists(cachedMonthlyStats.orderedLists);
12297
12248
  return;
12298
12249
  }
12299
- const allStats = [];
12300
- let hasNextPage = true;
12301
- let after = void 0;
12302
- let currentIteration = 0;
12303
- const maxIterations = 100;
12304
- let previousCursor = void 0;
12305
- const seenCursors = /* @__PURE__ */ new Set();
12306
- while (hasNextPage && currentIteration < maxIterations) {
12307
- currentIteration++;
12308
- const data = await fetchStats({
12309
- chainIds: chainIds2,
12310
- after,
12311
- resolution: "month",
12312
- lowerBoundTimestamp: 0
12313
- // Get all monthly data from the beginning
12314
- });
12315
- const batch = data.stats.items;
12316
- if (batch.length === 0) {
12317
- break;
12318
- }
12319
- allStats.push(...batch);
12320
- hasNextPage = data.stats.pageInfo.hasNextPage;
12321
- const newCursor = data.stats.pageInfo.endCursor || void 0;
12322
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12323
- console.warn("Pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12324
- break;
12325
- }
12326
- if (newCursor) {
12327
- seenCursors.add(newCursor);
12328
- }
12329
- previousCursor = after;
12330
- after = newCursor;
12331
- if (!hasNextPage) {
12332
- break;
12333
- }
12334
- }
12335
- if (currentIteration >= maxIterations) {
12336
- console.warn(`Monthly stats pagination hit max iterations (${maxIterations}), there may be a pagination issue`);
12337
- }
12250
+ const { stats: { items: allStats } } = await fetchStats({
12251
+ chainIds: chainIds2,
12252
+ after: void 0,
12253
+ resolution: "month",
12254
+ lowerBoundTimestamp: 0
12255
+ // Get all monthly data from the beginning
12256
+ });
12338
12257
  const aggregationMap = /* @__PURE__ */ new Map();
12339
12258
  allStats.forEach((stat2) => {
12340
12259
  const { currency, token: token2, verifier: verifier2, action, amount } = stat2;
@@ -12346,7 +12265,7 @@ function useMonthlyStats({
12346
12265
  currency: currency || void 0,
12347
12266
  token: token2,
12348
12267
  verifier: verifier2,
12349
- verifierName: getPaymentMethodName(null, verifier2) || "Unknown",
12268
+ verifierName: getPaymentMethodName(null, verifier2),
12350
12269
  totalDeposits: 0n,
12351
12270
  totalWithdrawals: 0n,
12352
12271
  totalExchanges: 0n,
@@ -12442,12 +12361,12 @@ function useMonthlyStats({
12442
12361
  verifierEntry.netAmount += entry.netAmount;
12443
12362
  });
12444
12363
  const newOrderedLists = {
12445
- currenciesByVolume: Array.from(currencyAggregation.values()).sort((a, b) => b.totalVolume > a.totalVolume ? 1 : -1),
12446
- currenciesByNetLiquidity: Array.from(currencyAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1),
12447
- tokensByVolume: Array.from(tokenAggregation.values()).sort((a, b) => b.totalExchanges > a.totalExchanges ? 1 : -1),
12448
- tokensByNetLiquidity: Array.from(tokenAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1),
12449
- verifiersByVolume: Array.from(verifierAggregation.values()).sort((a, b) => b.totalExchanges > a.totalExchanges ? 1 : -1),
12450
- verifiersByNetLiquidity: Array.from(verifierAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1)
12364
+ currenciesByVolume: rankDescending(currencyAggregation.values(), (entry) => entry.totalVolume),
12365
+ currenciesByNetLiquidity: rankDescending(currencyAggregation.values(), (entry) => entry.netAmount),
12366
+ tokensByVolume: rankDescending(tokenAggregation.values(), (entry) => entry.totalExchanges),
12367
+ tokensByNetLiquidity: rankDescending(tokenAggregation.values(), (entry) => entry.netAmount),
12368
+ verifiersByVolume: rankDescending(verifierAggregation.values(), (entry) => entry.totalExchanges),
12369
+ verifiersByNetLiquidity: rankDescending(verifierAggregation.values(), (entry) => entry.netAmount)
12451
12370
  };
12452
12371
  monthlyStatsCache.set(monthlyStatsCacheKey, {
12453
12372
  monthlyStats: processedStats,
@@ -12522,6 +12441,14 @@ var fetchRecentReleases = (limit) => {
12522
12441
  // src/adapter.ts
12523
12442
  import { chains as chains2 } from "@provex/utils/chain";
12524
12443
  import { and as and12, eq as eq14, desc as desc11, sql as sql9 } from "@ponder/client";
12444
+ function appendToGroup(groups, key, row) {
12445
+ const group = groups.get(key);
12446
+ if (group) {
12447
+ group.push(row);
12448
+ return;
12449
+ }
12450
+ groups.set(key, [row]);
12451
+ }
12525
12452
  function createPonderAdapter() {
12526
12453
  return {
12527
12454
  // ─── Deposit Discovery ──────────────────────────────────
@@ -12628,18 +12555,13 @@ function createPonderAdapter() {
12628
12555
  const verifiersByDeposit = /* @__PURE__ */ new Map();
12629
12556
  const lockedByDeposit = /* @__PURE__ */ new Map();
12630
12557
  const reclaimableByDeposit = /* @__PURE__ */ new Map();
12631
- for (const d of page) {
12632
- const key = `${d.escrow}-${d.localId}-${d.chainId}`;
12633
- ratesByDeposit.set(key, []);
12634
- verifiersByDeposit.set(key, []);
12635
- }
12636
12558
  for (const rate of allRates) {
12637
12559
  const key = `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`;
12638
- ratesByDeposit.get(key)?.push(rate);
12560
+ appendToGroup(ratesByDeposit, key, rate);
12639
12561
  }
12640
12562
  for (const verifier2 of allVerifiers) {
12641
12563
  const key = `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`;
12642
- verifiersByDeposit.get(key)?.push(verifier2);
12564
+ appendToGroup(verifiersByDeposit, key, verifier2);
12643
12565
  }
12644
12566
  for (const lock of allLocked) {
12645
12567
  if (resolvedIntentHashes.has(lock.intentHash)) continue;
@@ -12695,7 +12617,7 @@ function createPonderAdapter() {
12695
12617
  };
12696
12618
  });
12697
12619
  const lastItem = page[page.length - 1];
12698
- const nextCursor = hasNextPage && lastItem ? lastItem.orderId : null;
12620
+ const nextCursor = hasNextPage ? lastItem.orderId : null;
12699
12621
  return { items, nextCursor };
12700
12622
  },
12701
12623
  // ─── Single Deposit ───────────────────────────────────
@@ -12757,18 +12679,16 @@ function createPonderAdapter() {
12757
12679
  let status2 = "signalled";
12758
12680
  let prunedAt = null;
12759
12681
  const fulfillTxHash = fulfilled[0]?.fulfillTxHash ?? null;
12682
+ const prunedRecord = pruned[0];
12760
12683
  if (fulfilled.length > 0) {
12761
12684
  status2 = "fulfilled";
12762
- } else if (pruned.length > 0) {
12685
+ } else if (prunedRecord) {
12763
12686
  status2 = "pruned";
12764
- const prunedRecord = pruned[0];
12765
- if (prunedRecord) {
12766
- const txResult = await db.select({ blockId: ponder_schema_exports.transaction.blockId }).from(ponder_schema_exports.transaction).where(eq14(ponder_schema_exports.transaction.orderId, prunedRecord.transactionId)).limit(1);
12767
- const txRecord = txResult[0];
12768
- if (txRecord) {
12769
- const blockResult = await db.select({ timestamp: ponder_schema_exports.block.timestamp }).from(ponder_schema_exports.block).where(eq14(ponder_schema_exports.block.orderId, txRecord.blockId)).limit(1);
12770
- prunedAt = blockResult[0]?.timestamp ?? null;
12771
- }
12687
+ const txResult = await db.select({ blockId: ponder_schema_exports.transaction.blockId }).from(ponder_schema_exports.transaction).where(eq14(ponder_schema_exports.transaction.orderId, prunedRecord.transactionId)).limit(1);
12688
+ const txRecord = txResult[0];
12689
+ if (txRecord) {
12690
+ const blockResult = await db.select({ timestamp: ponder_schema_exports.block.timestamp }).from(ponder_schema_exports.block).where(eq14(ponder_schema_exports.block.orderId, txRecord.blockId)).limit(1);
12691
+ prunedAt = blockResult[0]?.timestamp ?? null;
12772
12692
  }
12773
12693
  }
12774
12694
  return {