@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.cjs CHANGED
@@ -2498,6 +2498,63 @@ var require_partition = __commonJS({
2498
2498
  }
2499
2499
  });
2500
2500
 
2501
+ // ../../node_modules/lodash/_defineProperty.js
2502
+ var require_defineProperty = __commonJS({
2503
+ "../../node_modules/lodash/_defineProperty.js"(exports2, module2) {
2504
+ "use strict";
2505
+ var getNative = require_getNative();
2506
+ var defineProperty = function() {
2507
+ try {
2508
+ var func = getNative(Object, "defineProperty");
2509
+ func({}, "", {});
2510
+ return func;
2511
+ } catch (e) {
2512
+ }
2513
+ }();
2514
+ module2.exports = defineProperty;
2515
+ }
2516
+ });
2517
+
2518
+ // ../../node_modules/lodash/_baseAssignValue.js
2519
+ var require_baseAssignValue = __commonJS({
2520
+ "../../node_modules/lodash/_baseAssignValue.js"(exports2, module2) {
2521
+ "use strict";
2522
+ var defineProperty = require_defineProperty();
2523
+ function baseAssignValue(object, key, value) {
2524
+ if (key == "__proto__" && defineProperty) {
2525
+ defineProperty(object, key, {
2526
+ "configurable": true,
2527
+ "enumerable": true,
2528
+ "value": value,
2529
+ "writable": true
2530
+ });
2531
+ } else {
2532
+ object[key] = value;
2533
+ }
2534
+ }
2535
+ module2.exports = baseAssignValue;
2536
+ }
2537
+ });
2538
+
2539
+ // ../../node_modules/lodash/groupBy.js
2540
+ var require_groupBy = __commonJS({
2541
+ "../../node_modules/lodash/groupBy.js"(exports2, module2) {
2542
+ "use strict";
2543
+ var baseAssignValue = require_baseAssignValue();
2544
+ var createAggregator = require_createAggregator();
2545
+ var objectProto = Object.prototype;
2546
+ var hasOwnProperty = objectProto.hasOwnProperty;
2547
+ var groupBy2 = createAggregator(function(result, value, key) {
2548
+ if (hasOwnProperty.call(result, key)) {
2549
+ result[key].push(value);
2550
+ } else {
2551
+ baseAssignValue(result, key, [value]);
2552
+ }
2553
+ });
2554
+ module2.exports = groupBy2;
2555
+ }
2556
+ });
2557
+
2501
2558
  // ../../node_modules/lodash/isEqual.js
2502
2559
  var require_isEqual = __commonJS({
2503
2560
  "../../node_modules/lodash/isEqual.js"(exports2, module2) {
@@ -9250,13 +9307,10 @@ var intentExpiryExtendedReferences = (0, import_drizzle_orm12.relations)(intentE
9250
9307
  // src/lib/env.ts
9251
9308
  var import_meta = {};
9252
9309
  function readEnvVar(name) {
9253
- try {
9254
- const value = import_meta.env?.[name];
9255
- if (value) return value;
9256
- } catch {
9257
- }
9258
- if (typeof process !== "undefined" && process.env?.[name]) return process.env[name];
9259
- return void 0;
9310
+ const viteValue = import_meta.env?.[name];
9311
+ if (viteValue) return viteValue;
9312
+ if (typeof process === "undefined") return void 0;
9313
+ return process.env[name] || void 0;
9260
9314
  }
9261
9315
 
9262
9316
  // ../token-indexer/ponder.schema.ts
@@ -9892,8 +9946,7 @@ var Deposit = class {
9892
9946
  get lowestUsdConversionRate() {
9893
9947
  const usdRates = this.usdConversionRates;
9894
9948
  let currentRate = null;
9895
- for (const [, rate] of usdRates.entries()) {
9896
- if (!rate) continue;
9949
+ for (const rate of usdRates.values()) {
9897
9950
  if (!rate.value) continue;
9898
9951
  if (!currentRate || BigInt(currentRate.value) < BigInt(rate.value)) {
9899
9952
  currentRate = rate;
@@ -9906,12 +9959,8 @@ var Deposit = class {
9906
9959
  if (lowestUsdRate) {
9907
9960
  return lowestUsdRate;
9908
9961
  }
9909
- for (const currencyMap of this.currentConversionRates.values()) {
9910
- for (const rate of currencyMap.values()) {
9911
- return rate;
9912
- }
9913
- }
9914
- return null;
9962
+ const [firstProviderRates] = this.currentConversionRates.values();
9963
+ return firstProviderRates?.values().next().value ?? null;
9915
9964
  }
9916
9965
  /**
9917
9966
  * Set of lowercased `paymentMethodId` hex hashes for every payment method
@@ -10070,35 +10119,33 @@ var Deposit = class {
10070
10119
  * UI that wants to render inactive provider cards with a muted treatment.
10071
10120
  */
10072
10121
  isProviderActive(key) {
10073
- const chainId = this.chainId;
10074
- const expectedContractId = (0, import_payment.providerKeyToContractId)(key).toLowerCase();
10075
- const row = this.depositVerifierAddeds.find((added) => {
10076
- const v2Match = (0, import_payment.verifierGetsKey)(chainId, added.verifier) === key;
10077
- if (v2Match) return true;
10078
- if ("paymentMethodId" in added && added.paymentMethodId) {
10079
- if (added.paymentMethodId.toLowerCase() === expectedContractId) return true;
10080
- if ((0, import_payment.verifierGetsKey)(chainId, added.paymentMethodId) === key) return true;
10081
- }
10082
- return false;
10083
- });
10122
+ const row = this.depositVerifierAddeds.find((added) => this.verifierRowMatchesProvider(added, key));
10084
10123
  if (!row) return false;
10085
10124
  return !("active" in row) || row.active !== false;
10086
10125
  }
10087
- getVerifier(key) {
10126
+ /**
10127
+ * Whether a `depositVerifierAdded` row belongs to a provider. A V2 row
10128
+ * matches by its verifier address. A V3 row matches by the provider's contract
10129
+ * id in `paymentMethodId`, or by a `paymentMethodId` that `verifierGetsKey`
10130
+ * resolves to the provider (for example a V2 verifier address).
10131
+ */
10132
+ verifierRowMatchesProvider(added, key) {
10088
10133
  const chainId = this.chainId;
10089
- const expectedContractId = (0, import_payment.providerKeyToContractId)(key).toLowerCase();
10090
- return this.depositVerifierAddeds.find((added) => {
10091
- if ("active" in added && added.active === false) return false;
10092
- const v2Match = (0, import_payment.verifierGetsKey)(chainId, added.verifier) === key;
10093
- if (v2Match) return true;
10094
- if ("paymentMethodId" in added && added.paymentMethodId) {
10095
- const directMatch = added.paymentMethodId.toLowerCase() === expectedContractId;
10096
- if (directMatch) return true;
10097
- const reverseMatch = (0, import_payment.verifierGetsKey)(chainId, added.paymentMethodId) === key;
10098
- if (reverseMatch) return true;
10099
- }
10100
- return false;
10101
- }) ?? null;
10134
+ if ((0, import_payment.verifierGetsKey)(chainId, added.verifier) === key) return true;
10135
+ if (!("paymentMethodId" in added) || !added.paymentMethodId) return false;
10136
+ if (added.paymentMethodId.toLowerCase() === (0, import_payment.providerKeyToContractId)(key).toLowerCase()) return true;
10137
+ return (0, import_payment.verifierGetsKey)(chainId, added.paymentMethodId) === key;
10138
+ }
10139
+ /**
10140
+ * The ACTIVE verifier row for a provider, or null. A row the maker switched
10141
+ * off with `setPaymentMethodActive(false)` is skipped. Rows from before the
10142
+ * `active` field existed have no such property and count as active, so older
10143
+ * data stays visible.
10144
+ */
10145
+ getVerifier(key) {
10146
+ return this.depositVerifierAddeds.find(
10147
+ (added) => !("active" in added && added.active === false) && this.verifierRowMatchesProvider(added, key)
10148
+ ) ?? null;
10102
10149
  }
10103
10150
  providerByIntentHash(hash) {
10104
10151
  const signal = this.intentSignaleds.find((intent) => intent.intentHash === hash);
@@ -11266,6 +11313,7 @@ async function searchEasAttestationsByHandle(args) {
11266
11313
  // src/hooks/useMatchableDeposits.ts
11267
11314
  var import_react2 = require("react");
11268
11315
  var import_react_query = require("@tanstack/react-query");
11316
+ var import_groupBy = __toESM(require_groupBy(), 1);
11269
11317
  var import_client11 = require("@ponder/client");
11270
11318
  var import_currencies2 = require("@provex/utils/currencies");
11271
11319
  var import_units3 = require("@provex/utils/units");
@@ -11283,13 +11331,11 @@ var getRate = ({
11283
11331
  const value = deposit2.currentConversionRates.get(paymentMethod2)?.get(currency.contractId)?.value;
11284
11332
  return value ? BigInt(value) : 0n;
11285
11333
  };
11286
- var compareRatedDeposits = (a, b) => {
11287
- if (a.rate < b.rate) return -1;
11288
- if (a.rate > b.rate) return 1;
11289
- if (a.deposit.depositId < b.deposit.depositId) return -1;
11290
- if (a.deposit.depositId > b.deposit.depositId) return 1;
11291
- return 0;
11334
+ var compareAscending = (a, b) => {
11335
+ if (a < b) return -1;
11336
+ return a > b ? 1 : 0;
11292
11337
  };
11338
+ var compareRatedDeposits = (a, b) => compareAscending(a.rate, b.rate) || compareAscending(a.deposit.depositId, b.deposit.depositId);
11293
11339
  function rankDepositsThatFillAmount({
11294
11340
  deposits,
11295
11341
  providerKey,
@@ -11326,7 +11372,6 @@ function fillableRangeOf({
11326
11372
  const minimumAmountInCurrency = (0, import_conversionRates.minimumCurrencyAmountForTokenAmount)({ token: token2, currency, tokenAmount: tokenMinimum, rate });
11327
11373
  const maximumAmountInCurrency = (0, import_conversionRates.maximumCurrencyAmountForTokenAmount)({ token: token2, currency, tokenAmount: tokenMaximum, rate });
11328
11374
  if (minimumAmountInCurrency === null || maximumAmountInCurrency === null) return null;
11329
- if (minimumAmountInCurrency <= 0n) return null;
11330
11375
  if (maximumAmountInCurrency < minimumAmountInCurrency) return null;
11331
11376
  return { deposit: deposit2, rate, minimumAmountInCurrency, maximumAmountInCurrency };
11332
11377
  }
@@ -11363,20 +11408,12 @@ function summarizeEscrowedAmountByProvider({
11363
11408
  }) {
11364
11409
  const totals = /* @__PURE__ */ new Map();
11365
11410
  for (const summary of summaries) {
11366
- const total = summary.fillableRanges.reduce((sum2, range) => {
11367
- const availableFunds = range.deposit.availableFunds;
11368
- return availableFunds > 0n ? sum2 + availableFunds : sum2;
11369
- }, 0n);
11411
+ const total = summary.fillableRanges.reduce((sum2, range) => sum2 + range.deposit.availableFunds, 0n);
11370
11412
  totals.set(summary.providerKey, total);
11371
11413
  }
11372
11414
  return totals;
11373
11415
  }
11374
- var compareBounds = (a, b) => {
11375
- if (a.distance !== b.distance) return a.distance < b.distance ? -1 : 1;
11376
- if (a.rate !== b.rate) return a.rate < b.rate ? -1 : 1;
11377
- if (a.providerKey !== b.providerKey) return a.providerKey < b.providerKey ? -1 : 1;
11378
- return 0;
11379
- };
11416
+ var compareBounds = (a, b) => compareAscending(a.distance, b.distance) || compareAscending(a.rate, b.rate) || compareAscending(a.providerKey, b.providerKey);
11380
11417
  function sellerLimitReason(deposit2) {
11381
11418
  return deposit2.availableFunds < deposit2.maxAmount ? "sellerFunds" : "sellerOrderMaximum";
11382
11419
  }
@@ -11456,13 +11493,9 @@ function findNearestWorkableAmount(summaries, amountInCurrency, options = {}) {
11456
11493
  return { direction: "lower", reason: nearest.reason, amountInCurrency: nearest.amountInCurrency, providerKey: nearest.providerKey };
11457
11494
  }
11458
11495
  function listProvidersWithLiquidity(summaries) {
11459
- return summaries.filter((summary) => summary.hasLiquidity).sort((a, b) => {
11460
- const bestRateA = a.fillableRanges[0].rate;
11461
- const bestRateB = b.fillableRanges[0].rate;
11462
- if (bestRateA !== bestRateB) return bestRateA < bestRateB ? -1 : 1;
11463
- if (a.providerKey !== b.providerKey) return a.providerKey < b.providerKey ? -1 : 1;
11464
- return 0;
11465
- }).map((summary) => summary.providerKey);
11496
+ return summaries.filter((summary) => summary.hasLiquidity).sort(
11497
+ (a, b) => compareAscending(a.fillableRanges[0].rate, b.fillableRanges[0].rate) || compareAscending(a.providerKey, b.providerKey)
11498
+ ).map((summary) => summary.providerKey);
11466
11499
  }
11467
11500
 
11468
11501
  // src/hooks/useMatchableDeposits.ts
@@ -11593,27 +11626,8 @@ async function fetchMatchableDepositsForProviders({
11593
11626
  if (filteredDepositsData.length === 0) {
11594
11627
  return [];
11595
11628
  }
11596
- const ratesByDeposit = /* @__PURE__ */ new Map();
11597
- const verifiersByDeposit = /* @__PURE__ */ new Map();
11598
- for (const d of filteredDepositsData) {
11599
- const key = `${d.escrow}-${d.localId}-${d.chainId}`;
11600
- ratesByDeposit.set(key, []);
11601
- verifiersByDeposit.set(key, []);
11602
- }
11603
- for (const rate of allConversionRates) {
11604
- const key = `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`;
11605
- const existing = ratesByDeposit.get(key);
11606
- if (existing) {
11607
- existing.push(rate);
11608
- }
11609
- }
11610
- for (const verifier2 of allVerifiers) {
11611
- const key = `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`;
11612
- const existing = verifiersByDeposit.get(key);
11613
- if (existing) {
11614
- existing.push(verifier2);
11615
- }
11616
- }
11629
+ const ratesByDeposit = (0, import_groupBy.default)(allConversionRates, (rate) => `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`);
11630
+ const verifiersByDeposit = (0, import_groupBy.default)(allVerifiers, (verifier2) => `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`);
11617
11631
  const resolvedIntentHashes = /* @__PURE__ */ new Set([
11618
11632
  ...allUnlocked.map((u) => u.intentHash),
11619
11633
  ...allTransferred.map((t) => t.intentHash)
@@ -11634,8 +11648,8 @@ async function fetchMatchableDepositsForProviders({
11634
11648
  }
11635
11649
  return filteredDepositsData.map((deposit2) => {
11636
11650
  const key = `${deposit2.escrow}-${deposit2.localId}-${deposit2.chainId}`;
11637
- const rates = ratesByDeposit.get(key) ?? [];
11638
- const verifiers = verifiersByDeposit.get(key) ?? [];
11651
+ const rates = ratesByDeposit[key] ?? [];
11652
+ const verifiers = verifiersByDeposit[key] ?? [];
11639
11653
  const depositId = import_ids3.orderId.deposit.serialize({
11640
11654
  escrow: deposit2.escrow,
11641
11655
  chainId: deposit2.chainId,
@@ -11753,7 +11767,7 @@ function useMatchableDeposits(options) {
11753
11767
  return allDeposits.filter((deposit2) => hasActiveVerifierFor(deposit2, ids));
11754
11768
  }, [allDeposits, token2.chainId, paymentMethod2]);
11755
11769
  const filterDepositsByAmount = (0, import_react2.useCallback)((amountInInt) => {
11756
- if (!amountInInt || !currency) return [];
11770
+ if (!amountInInt) return [];
11757
11771
  return rankDepositsThatFillAmount({
11758
11772
  deposits,
11759
11773
  providerKey: paymentMethod2,
@@ -11777,7 +11791,7 @@ function useMatchableDeposits(options) {
11777
11791
  // eslint-disable-next-line react-hooks/exhaustive-deps
11778
11792
  getMatchableDeposits: (0, import_react2.useCallback)((amountInInt) => {
11779
11793
  if (typeof amountInInt === "string") {
11780
- amountInInt = (0, import_units3.parseUnits)(amountInInt, { decimals: currency?.decimals || 2 });
11794
+ amountInInt = (0, import_units3.parseUnits)(amountInInt, { decimals: currency.decimals });
11781
11795
  }
11782
11796
  if (!amountInInt) return [];
11783
11797
  return filterDepositsByAmount(amountInInt);
@@ -12042,6 +12056,14 @@ var statsRequestCache = /* @__PURE__ */ new Map();
12042
12056
  var monthlyStatsCache = /* @__PURE__ */ new Map();
12043
12057
  var liquidityBaselineCache = /* @__PURE__ */ new Map();
12044
12058
  var CACHE_EXPIRATION_MS = import_time.interval.second * 10;
12059
+ var liquidityActions = /* @__PURE__ */ new Set([
12060
+ import_stats.statAction.deposit,
12061
+ import_stats.statAction.withdrawal,
12062
+ import_stats.statAction.exchange,
12063
+ import_stats.statAction.fee,
12064
+ import_stats.statAction.dust
12065
+ ]);
12066
+ var isLiquidityAction = (action) => liquidityActions.has(action);
12045
12067
  function generateStatsRequestCacheKey({
12046
12068
  chainIds,
12047
12069
  after,
@@ -12049,7 +12071,7 @@ function generateStatsRequestCacheKey({
12049
12071
  lowerBoundTimestamp,
12050
12072
  upperBoundTimestamp
12051
12073
  }) {
12052
- const chainKey = chainIds.length === 0 ? "all-chains" : chainIds.slice().sort((a, b) => a - b).join(",");
12074
+ const chainKey = chainIds.slice().sort((a, b) => a - b).join(",");
12053
12075
  const timeRange = upperBoundTimestamp ? `${lowerBoundTimestamp}-${upperBoundTimestamp}` : `${lowerBoundTimestamp}-end`;
12054
12076
  return `${chainKey}:${resolution}:${timeRange}:${after || "start"}`;
12055
12077
  }
@@ -12080,18 +12102,7 @@ var fetchStats = async ({
12080
12102
  after,
12081
12103
  resolution = "month"
12082
12104
  }) => {
12083
- const whereClause = {
12084
- type: resolution,
12085
- timestamp_gte: lowerBoundTimestamp / 1e3
12086
- };
12087
- if (upperBoundTimestamp) {
12088
- whereClause.timestamp_lt = upperBoundTimestamp / 1e3;
12089
- }
12090
12105
  const cIds = chainIds.length > 0 ? chainIds : import_chain.chains.map((c) => c.id);
12091
- whereClause.OR = cIds.map((chainId) => ({
12092
- chainId,
12093
- token: (0, import_contracts2.getLatestContract)(chainId, "usdc").toLowerCase()
12094
- }));
12095
12106
  const cacheKey = generateStatsRequestCacheKey({
12096
12107
  chainIds: cIds,
12097
12108
  after,
@@ -12113,10 +12124,8 @@ var fetchStats = async ({
12113
12124
  if (chainIds.length > 0) {
12114
12125
  conditions.push((0, import_client13.inArray)(ponder_schema_exports.stat.chainId, chainIds.map((id) => BigInt(id))));
12115
12126
  }
12116
- if (tokenAddresses.length > 0) {
12117
- conditions.push((0, import_client13.inArray)(ponder_schema_exports.stat.token, tokenAddresses));
12118
- }
12119
- const statsData = await db.select().from(ponder_schema_exports.stat).where(conditions.length > 0 ? (0, import_client13.and)(...conditions) : void 0).orderBy((0, import_client13.desc)(ponder_schema_exports.stat.orderId)).limit(1e3);
12127
+ conditions.push((0, import_client13.inArray)(ponder_schema_exports.stat.token, tokenAddresses));
12128
+ const statsData = await db.select().from(ponder_schema_exports.stat).where((0, import_client13.and)(...conditions)).orderBy((0, import_client13.desc)(ponder_schema_exports.stat.orderId)).limit(1e3);
12120
12129
  const mappedStats = statsData.map((stat2) => ({
12121
12130
  ...stat2,
12122
12131
  action: stat2.event
@@ -12138,6 +12147,12 @@ var fetchStats = async ({
12138
12147
  });
12139
12148
  return data;
12140
12149
  };
12150
+ var rankDescending = (items, selectAmount) => Array.from(items).sort((a, b) => {
12151
+ const amountA = selectAmount(a);
12152
+ const amountB = selectAmount(b);
12153
+ if (amountA === amountB) return 0;
12154
+ return amountB > amountA ? 1 : -1;
12155
+ });
12141
12156
  var orderIdToTimestamp = (id) => Number(import_ids4.orderId.stat.parse(id).timestamp * 1000n);
12142
12157
  var groupStatsByTime = (stats) => {
12143
12158
  const timeAggregationMap = /* @__PURE__ */ new Map();
@@ -12195,8 +12210,7 @@ var fetchLiquidityBaseline = async ({
12195
12210
  }) => {
12196
12211
  const cIds = chainIds.length > 0 ? chainIds : import_chain.chains.map((c) => c.id);
12197
12212
  const targetDate = new Date(targetTimestamp);
12198
- const monthStart = new Date(targetDate.getUTCFullYear(), targetDate.getUTCMonth(), 1);
12199
- const monthStartTimestamp = (/* @__PURE__ */ new Date(`${monthStart.getUTCFullYear()}-${(monthStart.getUTCMonth() + 1).toString().padStart(2, "0")}-01T00:00:00.000Z`)).getTime();
12213
+ const monthStartTimestamp = Date.UTC(targetDate.getUTCFullYear(), targetDate.getUTCMonth(), 1);
12200
12214
  const cacheKey = generateLiquidityBaselineCacheKey({
12201
12215
  chainIds: cIds,
12202
12216
  targetTimestamp,
@@ -12218,7 +12232,7 @@ var fetchLiquidityBaseline = async ({
12218
12232
  upperBoundTimestamp: monthStartTimestamp
12219
12233
  });
12220
12234
  const allStatsForTimeGrouping = monthlyData.stats.items.filter((stat2) => {
12221
- return Number(stat2.timestamp) * 1e3 < monthStartTimestamp && (0, import_stats.isStatAction)(stat2.action);
12235
+ return Number(stat2.timestamp) * 1e3 < monthStartTimestamp && isLiquidityAction(stat2.action);
12222
12236
  });
12223
12237
  const baseline = allStatsForTimeGrouping.reduce((acc, stat2) => {
12224
12238
  let amount = stat2.amount;
@@ -12227,44 +12241,13 @@ var fetchLiquidityBaseline = async ({
12227
12241
  }
12228
12242
  return acc + amount;
12229
12243
  }, 0n);
12230
- const currentPeriodStats = [];
12231
- let hasNextPage = true;
12232
- let after = void 0;
12233
- let iterations = 0;
12234
- const maxIterations = 50;
12235
- let previousCursor = void 0;
12236
- const seenCursors = /* @__PURE__ */ new Set();
12237
- while (hasNextPage && iterations < maxIterations) {
12238
- iterations++;
12239
- const detailedData = await fetchStats({
12240
- lowerBoundTimestamp: monthStartTimestamp,
12241
- chainIds: cIds,
12242
- after,
12243
- resolution
12244
- });
12245
- const batch = detailedData.stats.items;
12246
- if (batch.length === 0) break;
12247
- const relevantStats = batch.filter((stat2) => {
12248
- const statTimestamp = orderIdToTimestamp(stat2.orderId);
12249
- return statTimestamp >= monthStartTimestamp && (0, import_stats.isStatAction)(stat2.action);
12250
- });
12251
- currentPeriodStats.push(...relevantStats);
12252
- const oldestInBatch = batch[batch.length - 1];
12253
- if (oldestInBatch && orderIdToTimestamp(oldestInBatch.orderId) < monthStartTimestamp) {
12254
- break;
12255
- }
12256
- hasNextPage = detailedData.stats.pageInfo.hasNextPage;
12257
- const newCursor = detailedData.stats.pageInfo.endCursor || void 0;
12258
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12259
- console.warn("Liquidity baseline pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12260
- break;
12261
- }
12262
- if (newCursor) {
12263
- seenCursors.add(newCursor);
12264
- }
12265
- previousCursor = after;
12266
- after = newCursor;
12267
- }
12244
+ const detailedData = await fetchStats({
12245
+ lowerBoundTimestamp: monthStartTimestamp,
12246
+ chainIds: cIds,
12247
+ after: void 0,
12248
+ resolution
12249
+ });
12250
+ const currentPeriodStats = detailedData.stats.items.filter((stat2) => orderIdToTimestamp(stat2.orderId) >= monthStartTimestamp && isLiquidityAction(stat2.action));
12268
12251
  const result = {
12269
12252
  baseline,
12270
12253
  currentPeriodStats,
@@ -12298,45 +12281,13 @@ var fetchComprehensiveStats = async ({
12298
12281
  const allStats = [...currentPeriodStats];
12299
12282
  const needsAdditionalStats = currentPeriodStats.length === 0 || currentPeriodStats.some((stat2) => orderIdToTimestamp(stat2.orderId) < lowerBoundTimestamp);
12300
12283
  if (needsAdditionalStats) {
12301
- let hasNextPage = true;
12302
- let after = void 0;
12303
- let iterations = 0;
12304
- const maxIterations = 50;
12305
- let previousCursor = void 0;
12306
- const seenCursors = /* @__PURE__ */ new Set();
12307
- while (hasNextPage && iterations < maxIterations) {
12308
- iterations++;
12309
- const data = await fetchStats({
12310
- chainIds: cIds,
12311
- after,
12312
- resolution,
12313
- lowerBoundTimestamp
12314
- });
12315
- const batch = data.stats.items;
12316
- if (batch.length === 0) break;
12317
- const windowStats = batch.filter((stat2) => {
12318
- const timestamp2 = orderIdToTimestamp(stat2.orderId);
12319
- return timestamp2 >= lowerBoundTimestamp;
12320
- });
12321
- allStats.push(...windowStats);
12322
- if (batch.length > 0) {
12323
- const item = batch[batch.length - 1];
12324
- if (item && orderIdToTimestamp(item.orderId) < lowerBoundTimestamp) {
12325
- break;
12326
- }
12327
- }
12328
- hasNextPage = data.stats.pageInfo.hasNextPage;
12329
- const newCursor = data.stats.pageInfo.endCursor || void 0;
12330
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12331
- console.warn("Comprehensive stats pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12332
- break;
12333
- }
12334
- if (newCursor) {
12335
- seenCursors.add(newCursor);
12336
- }
12337
- previousCursor = after;
12338
- after = newCursor;
12339
- }
12284
+ const data = await fetchStats({
12285
+ chainIds: cIds,
12286
+ after: void 0,
12287
+ resolution,
12288
+ lowerBoundTimestamp
12289
+ });
12290
+ allStats.push(...data.stats.items.filter((stat2) => orderIdToTimestamp(stat2.orderId) >= lowerBoundTimestamp));
12340
12291
  }
12341
12292
  const uniqueStats = Array.from(
12342
12293
  new Map(allStats.map((stat2) => [stat2.orderId, stat2])).values()
@@ -12384,45 +12335,13 @@ function useMonthlyStats({
12384
12335
  setOrderedLists(cachedMonthlyStats.orderedLists);
12385
12336
  return;
12386
12337
  }
12387
- const allStats = [];
12388
- let hasNextPage = true;
12389
- let after = void 0;
12390
- let currentIteration = 0;
12391
- const maxIterations = 100;
12392
- let previousCursor = void 0;
12393
- const seenCursors = /* @__PURE__ */ new Set();
12394
- while (hasNextPage && currentIteration < maxIterations) {
12395
- currentIteration++;
12396
- const data = await fetchStats({
12397
- chainIds: chainIds2,
12398
- after,
12399
- resolution: "month",
12400
- lowerBoundTimestamp: 0
12401
- // Get all monthly data from the beginning
12402
- });
12403
- const batch = data.stats.items;
12404
- if (batch.length === 0) {
12405
- break;
12406
- }
12407
- allStats.push(...batch);
12408
- hasNextPage = data.stats.pageInfo.hasNextPage;
12409
- const newCursor = data.stats.pageInfo.endCursor || void 0;
12410
- if (hasNextPage && (newCursor === previousCursor || newCursor && seenCursors.has(newCursor))) {
12411
- console.warn("Pagination cursor not advancing or repeating, breaking pagination loop to prevent infinite loop");
12412
- break;
12413
- }
12414
- if (newCursor) {
12415
- seenCursors.add(newCursor);
12416
- }
12417
- previousCursor = after;
12418
- after = newCursor;
12419
- if (!hasNextPage) {
12420
- break;
12421
- }
12422
- }
12423
- if (currentIteration >= maxIterations) {
12424
- console.warn(`Monthly stats pagination hit max iterations (${maxIterations}), there may be a pagination issue`);
12425
- }
12338
+ const { stats: { items: allStats } } = await fetchStats({
12339
+ chainIds: chainIds2,
12340
+ after: void 0,
12341
+ resolution: "month",
12342
+ lowerBoundTimestamp: 0
12343
+ // Get all monthly data from the beginning
12344
+ });
12426
12345
  const aggregationMap = /* @__PURE__ */ new Map();
12427
12346
  allStats.forEach((stat2) => {
12428
12347
  const { currency, token: token2, verifier: verifier2, action, amount } = stat2;
@@ -12434,7 +12353,7 @@ function useMonthlyStats({
12434
12353
  currency: currency || void 0,
12435
12354
  token: token2,
12436
12355
  verifier: verifier2,
12437
- verifierName: (0, import_payment4.getPaymentMethodName)(null, verifier2) || "Unknown",
12356
+ verifierName: (0, import_payment4.getPaymentMethodName)(null, verifier2),
12438
12357
  totalDeposits: 0n,
12439
12358
  totalWithdrawals: 0n,
12440
12359
  totalExchanges: 0n,
@@ -12530,12 +12449,12 @@ function useMonthlyStats({
12530
12449
  verifierEntry.netAmount += entry.netAmount;
12531
12450
  });
12532
12451
  const newOrderedLists = {
12533
- currenciesByVolume: Array.from(currencyAggregation.values()).sort((a, b) => b.totalVolume > a.totalVolume ? 1 : -1),
12534
- currenciesByNetLiquidity: Array.from(currencyAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1),
12535
- tokensByVolume: Array.from(tokenAggregation.values()).sort((a, b) => b.totalExchanges > a.totalExchanges ? 1 : -1),
12536
- tokensByNetLiquidity: Array.from(tokenAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1),
12537
- verifiersByVolume: Array.from(verifierAggregation.values()).sort((a, b) => b.totalExchanges > a.totalExchanges ? 1 : -1),
12538
- verifiersByNetLiquidity: Array.from(verifierAggregation.values()).sort((a, b) => b.netAmount > a.netAmount ? 1 : -1)
12452
+ currenciesByVolume: rankDescending(currencyAggregation.values(), (entry) => entry.totalVolume),
12453
+ currenciesByNetLiquidity: rankDescending(currencyAggregation.values(), (entry) => entry.netAmount),
12454
+ tokensByVolume: rankDescending(tokenAggregation.values(), (entry) => entry.totalExchanges),
12455
+ tokensByNetLiquidity: rankDescending(tokenAggregation.values(), (entry) => entry.netAmount),
12456
+ verifiersByVolume: rankDescending(verifierAggregation.values(), (entry) => entry.totalExchanges),
12457
+ verifiersByNetLiquidity: rankDescending(verifierAggregation.values(), (entry) => entry.netAmount)
12539
12458
  };
12540
12459
  monthlyStatsCache.set(monthlyStatsCacheKey, {
12541
12460
  monthlyStats: processedStats,
@@ -12610,6 +12529,14 @@ var fetchRecentReleases = (limit) => {
12610
12529
  // src/adapter.ts
12611
12530
  var import_chain2 = require("@provex/utils/chain");
12612
12531
  var import_client14 = require("@ponder/client");
12532
+ function appendToGroup(groups, key, row) {
12533
+ const group = groups.get(key);
12534
+ if (group) {
12535
+ group.push(row);
12536
+ return;
12537
+ }
12538
+ groups.set(key, [row]);
12539
+ }
12613
12540
  function createPonderAdapter() {
12614
12541
  return {
12615
12542
  // ─── Deposit Discovery ──────────────────────────────────
@@ -12716,18 +12643,13 @@ function createPonderAdapter() {
12716
12643
  const verifiersByDeposit = /* @__PURE__ */ new Map();
12717
12644
  const lockedByDeposit = /* @__PURE__ */ new Map();
12718
12645
  const reclaimableByDeposit = /* @__PURE__ */ new Map();
12719
- for (const d of page) {
12720
- const key = `${d.escrow}-${d.localId}-${d.chainId}`;
12721
- ratesByDeposit.set(key, []);
12722
- verifiersByDeposit.set(key, []);
12723
- }
12724
12646
  for (const rate of allRates) {
12725
12647
  const key = `${rate.depositEscrow}-${rate.depositLocalId}-${rate.depositChainId}`;
12726
- ratesByDeposit.get(key)?.push(rate);
12648
+ appendToGroup(ratesByDeposit, key, rate);
12727
12649
  }
12728
12650
  for (const verifier2 of allVerifiers) {
12729
12651
  const key = `${verifier2.depositEscrow}-${verifier2.depositLocalId}-${verifier2.depositChainId}`;
12730
- verifiersByDeposit.get(key)?.push(verifier2);
12652
+ appendToGroup(verifiersByDeposit, key, verifier2);
12731
12653
  }
12732
12654
  for (const lock of allLocked) {
12733
12655
  if (resolvedIntentHashes.has(lock.intentHash)) continue;
@@ -12783,7 +12705,7 @@ function createPonderAdapter() {
12783
12705
  };
12784
12706
  });
12785
12707
  const lastItem = page[page.length - 1];
12786
- const nextCursor = hasNextPage && lastItem ? lastItem.orderId : null;
12708
+ const nextCursor = hasNextPage ? lastItem.orderId : null;
12787
12709
  return { items, nextCursor };
12788
12710
  },
12789
12711
  // ─── Single Deposit ───────────────────────────────────
@@ -12845,18 +12767,16 @@ function createPonderAdapter() {
12845
12767
  let status2 = "signalled";
12846
12768
  let prunedAt = null;
12847
12769
  const fulfillTxHash = fulfilled[0]?.fulfillTxHash ?? null;
12770
+ const prunedRecord = pruned[0];
12848
12771
  if (fulfilled.length > 0) {
12849
12772
  status2 = "fulfilled";
12850
- } else if (pruned.length > 0) {
12773
+ } else if (prunedRecord) {
12851
12774
  status2 = "pruned";
12852
- const prunedRecord = pruned[0];
12853
- if (prunedRecord) {
12854
- const txResult = await db.select({ blockId: ponder_schema_exports.transaction.blockId }).from(ponder_schema_exports.transaction).where((0, import_client14.eq)(ponder_schema_exports.transaction.orderId, prunedRecord.transactionId)).limit(1);
12855
- const txRecord = txResult[0];
12856
- if (txRecord) {
12857
- const blockResult = await db.select({ timestamp: ponder_schema_exports.block.timestamp }).from(ponder_schema_exports.block).where((0, import_client14.eq)(ponder_schema_exports.block.orderId, txRecord.blockId)).limit(1);
12858
- prunedAt = blockResult[0]?.timestamp ?? null;
12859
- }
12775
+ const txResult = await db.select({ blockId: ponder_schema_exports.transaction.blockId }).from(ponder_schema_exports.transaction).where((0, import_client14.eq)(ponder_schema_exports.transaction.orderId, prunedRecord.transactionId)).limit(1);
12776
+ const txRecord = txResult[0];
12777
+ if (txRecord) {
12778
+ const blockResult = await db.select({ timestamp: ponder_schema_exports.block.timestamp }).from(ponder_schema_exports.block).where((0, import_client14.eq)(ponder_schema_exports.block.orderId, txRecord.blockId)).limit(1);
12779
+ prunedAt = blockResult[0]?.timestamp ?? null;
12860
12780
  }
12861
12781
  }
12862
12782
  return {