@1delta/margin-fetcher 0.0.403 → 0.0.405

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
@@ -1,12 +1,12 @@
1
- import { parseAbi, keccak256, encodeAbiParameters, formatEther, BaseError, encodeFunctionData, formatUnits, isAddress, getAddress, decodeFunctionResult, decodeAbiParameters, AbiEncodingLengthMismatchError, concatHex, pad, InvalidAddressError, stringToHex, boolToHex, integerRegex, numberToHex, bytesRegex, BytesSizeMismatchError, arrayRegex, UnsupportedPackedAbiType } from './chunk-Z3MGRQJR.js';
1
+ import { parseAbi, keccak256, encodeAbiParameters, formatEther, BaseError, pad, encodeFunctionData, formatUnits, isAddress, getAddress, decodeFunctionResult, decodeAbiParameters, concat, AbiEncodingLengthMismatchError, concatHex, toBytes, slice, InvalidAddressError, stringToHex, boolToHex, integerRegex, numberToHex, bytesRegex, BytesSizeMismatchError, arrayRegex, UnsupportedPackedAbiType } from './chunk-SRWUFRRR.js';
2
2
  import './chunk-BYTNVMX7.js';
3
3
  import './chunk-PR4QN5HX.js';
4
- import { Lender, LIQUITY_FAMILY_LENDERS, isAaveType, isCompoundV3, isMultiMarket, isSiloV2Type, isSiloV3Type, isDolomite, isMidnight, isTerm, isExactly, isLiquityFamily, isRiver, isTeller, isEulerType, isAaveV4Type, isInit, isMorphoType, isCompoundV2Type, isVenusType, isSumerType, AAVE_V3_LENDERS, AAVE_V2_LENDERS, isAaveV2Type, isAaveV32Type, isAaveV3Type, isFluid, isGearboxV3, isYLDR, isCompoundV3Type, isLista, isTectonicType, isKineticType, isBenqiType } from '@1delta/lender-registry';
4
+ import { Lender, LIQUITY_FAMILY_LENDERS, isAaveType, isCompoundV3, isMultiMarket, isSiloV2Type, isSiloV3Type, isDolomite, isMidnight, isTerm, isExactly, isLiquityFamily, isRiver, isTeller, isEulerType, isAaveV4Type, isInit, isMorphoType, isCompoundV2Type, isVenusType, isSumerType, AAVE_V3_LENDERS, AAVE_V2_LENDERS, isAaveV2Type, isAaveV32Type, isAaveV3Type, isFluid, isGearboxV3, isInverse, isTermMax, isYLDR, isCompoundV3Type, isLista, isTectonicType, isKineticType, isBenqiType } from '@1delta/lender-registry';
5
5
  export { isAaveType, isAaveV2Type, isAaveV32Type, isAaveV3Type, isCompoundV3, isCompoundV3Type, isInit, isMorphoType, isMultiMarket, isYLDR } from '@1delta/lender-registry';
6
- import { fetchTokenLists, fetchTokenList, aavePools, compoundV3Pools, initConfig, morphoPools, compoundV2Pools, eulerVaults, siloMarkets, siloV2LenderKey, siloMarketsV3, siloV3LenderKey, aaveV4Spokes, aaveV4SpokeLenderKey, fluidResolvers, gearboxResolvers, dolomiteConfigs, midnightConfig, termConfig, termMarketsByChain, exactlyConfig, liquityLendersByChain, riverLendersByChain, tellerConfigByChain, tellerPoolsByChain, aaveReserves, compoundV3Reserves, liquityConfigFor, liquityBranchesByChain, riverConfigFor, riverChainData, aaveOracles, morphoTypeMarkets, resolveMidnightApiBase, resolveTermApiBase, getSiloV2MarketEntry, getSiloV3MarketEntry, dolomiteEmode, aaveTokens, morphoTypeVaults, eulerConfigs, gearboxMarketCompressor, gearboxMarketConfigurators, gearboxV3LenderKey, midnightMarketsByChain, parseAaveV4SpokeLenderKey, gearboxAccountCompressor, compoundV2Tokens, exactlyMarketsByChain, aaveOraclesConfig, compoundV2Oracles, compoundV2TokenArray, compoundV2OraclesConfig, compoundV3OraclesData, compoundV3BaseData, compoundV2Reserves, aaveV4Oracles } from '@1delta/data-sdk';
6
+ import { fetchTokenLists, fetchTokenList, aavePools, compoundV3Pools, initConfig, morphoPools, compoundV2Pools, eulerVaults, siloMarkets, siloV2LenderKey, siloMarketsV3, siloV3LenderKey, aaveV4Spokes, aaveV4SpokeLenderKey, fluidResolvers, gearboxResolvers, dolomiteConfigs, midnightConfig, termConfig, termMarketsByChain, exactlyConfig, liquityLendersByChain, riverLendersByChain, inverseLendersByChain, tellerConfigByChain, tellerPoolsByChain, aaveReserves, compoundV3Reserves, liquityConfigFor, liquityBranchesByChain, riverConfigFor, riverChainData, termMaxApiBaseUrl, termMaxConfigByChain, termMaxLenderKey, inverseConfigFor, inverseChainData, aaveOracles, morphoTypeMarkets, resolveMidnightApiBase, resolveTermApiBase, getSiloV2MarketEntry, getSiloV3MarketEntry, dolomiteEmode, aaveTokens, morphoTypeVaults, eulerConfigs, gearboxMarketCompressor, gearboxMarketConfigurators, gearboxV3LenderKey, midnightMarketsByChain, parseAaveV4SpokeLenderKey, gearboxAccountCompressor, compoundV2Tokens, exactlyMarketsByChain, aaveOraclesConfig, compoundV2Oracles, compoundV2TokenArray, compoundV2OraclesConfig, compoundV3OraclesData, compoundV3BaseData, compoundV2Reserves, aaveV4Oracles } from '@1delta/data-sdk';
7
7
  import lodash from 'lodash';
8
8
  import { multicallRetryUniversal, getEvmClient, getEvmChain, getEvmClientUniversal } from '@1delta/providers';
9
- import { LiquityTroveManagerAbi, LiquityActivePoolAbi, LiquityStabilityPoolAbi, LiquityPriceFeedAbi, LiquitySortedTrovesAbi, RiverTroveManagerAbi, RiverStabilityPoolAbi, TellerMarketRegistryAbi, TellerV2Abi, MetaMorphoAbi, ExactlyPreviewerAbi, ExactlyAuditorAbi, LenderCommitmentGroupAbi, FluidLendingResolverAbi, FluidVaultResolverAbi, FluidLiquidityResolverAbi, MoolahVaultAbi, MorphoLensAbi, AaveV4SpokeAbi, AaveV4OracleAbi, AaveV4HubAbi, DolomiteMarginAbi, GearboxMarketCompressorV310Abi, MorphoBlueAbi, MidnightAbi, TermRepoTokenAbi, TermRepoServicerAbi, TermRepoCollateralManagerAbi, LiquityTroveNFTAbi, LiquityCollSurplusPoolAbi, TellerCollateralManagerAbi, GearboxCreditAccountCompressorV310Abi, TermPriceConsumerAbi } from '@1delta/abis';
9
+ import { LiquityTroveManagerAbi, LiquityActivePoolAbi, LiquityStabilityPoolAbi, LiquityPriceFeedAbi, LiquitySortedTrovesAbi, RiverTroveManagerAbi, RiverStabilityPoolAbi, TellerMarketRegistryAbi, TellerV2Abi, InverseMarketAbi, InverseOracleAbi, InverseDbrAbi, Erc20Abi, MetaMorphoAbi, ExactlyPreviewerAbi, ExactlyAuditorAbi, LenderCommitmentGroupAbi, FluidLendingResolverAbi, FluidVaultResolverAbi, FluidLiquidityResolverAbi, MoolahVaultAbi, MorphoLensAbi, AaveV4SpokeAbi, AaveV4OracleAbi, AaveV4HubAbi, DolomiteMarginAbi, GearboxMarketCompressorV310Abi, MorphoBlueAbi, MidnightAbi, TermRepoTokenAbi, TermRepoServicerAbi, TermRepoCollateralManagerAbi, LiquityTroveNFTAbi, LiquityCollSurplusPoolAbi, TellerCollateralManagerAbi, InverseEscrowAbi, GearboxCreditAccountCompressorV310Abi, TermPriceConsumerAbi, TermMaxOracleAggregatorV2Abi } from '@1delta/abis';
10
10
  export { MorphoLensAbi } from '@1delta/abis';
11
11
  import { prepareDebitDataMulticall, prepareLenderDebitMulticall, parseDebitDataResult, parseLenderDebitResult, getPermit2ContractAddress, getCompoundV3CometAddress as getCompoundV3CometAddress$1, getMorphoAddress, getAaveCollateralTokenAddress, getSiloHalfForUnderlying, InitMarginAddresses, getLstAcceptedInputs } from '@1delta/calldata-sdk';
12
12
  import { proxyNativeFetch } from '@1delta/proxy-fetch';
@@ -7516,6 +7516,9 @@ var getLendersForChain = (c) => {
7516
7516
  for (const l of riverLendersByChain(c)) {
7517
7517
  lenders.push(l);
7518
7518
  }
7519
+ for (const l of inverseLendersByChain(c)) {
7520
+ lenders.push(l);
7521
+ }
7519
7522
  if (tellerConfigByChain(c)?.tellerV2 && tellerPoolsByChain(c).length > 0) {
7520
7523
  lenders.push(Lender.TELLER);
7521
7524
  }
@@ -8002,6 +8005,37 @@ function encode(type, value, isArray2 = false) {
8002
8005
  throw new UnsupportedPackedAbiType(type);
8003
8006
  }
8004
8007
 
8008
+ // ../../node_modules/.pnpm/viem@2.45.3_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@6.0.6_zod@4.3.6/node_modules/viem/_esm/utils/data/isBytes.js
8009
+ function isBytes(value) {
8010
+ if (!value)
8011
+ return false;
8012
+ if (typeof value !== "object")
8013
+ return false;
8014
+ if (!("BYTES_PER_ELEMENT" in value))
8015
+ return false;
8016
+ return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array";
8017
+ }
8018
+
8019
+ // ../../node_modules/.pnpm/viem@2.45.3_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@6.0.6_zod@4.3.6/node_modules/viem/_esm/utils/address/getContractAddress.js
8020
+ function getContractAddress(opts) {
8021
+ return getCreate2Address(opts);
8022
+ }
8023
+ function getCreate2Address(opts) {
8024
+ const from = toBytes(getAddress(opts.from));
8025
+ const salt = pad(isBytes(opts.salt) ? opts.salt : toBytes(opts.salt), {
8026
+ size: 32
8027
+ });
8028
+ const bytecodeHash = (() => {
8029
+ if ("bytecodeHash" in opts) {
8030
+ if (isBytes(opts.bytecodeHash))
8031
+ return opts.bytecodeHash;
8032
+ return toBytes(opts.bytecodeHash);
8033
+ }
8034
+ return keccak256(opts.bytecode, "bytes");
8035
+ })();
8036
+ return getAddress(slice(keccak256(concat([toBytes("0xff"), from, salt, bytecodeHash])), 12));
8037
+ }
8038
+
8005
8039
  // ../../node_modules/.pnpm/viem@2.45.3_bufferutil@4.1.0_typescript@5.9.3_utf-8-validate@6.0.6_zod@4.3.6/node_modules/viem/_esm/constants/bytes.js
8006
8040
  var zeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000";
8007
8041
 
@@ -11112,8 +11146,8 @@ async function resolveListaBrokers(chainId, marketKeys, getClient = getEvmClient
11112
11146
  });
11113
11147
  results.forEach((r, i) => {
11114
11148
  const id = missing[i];
11115
- const addr = r.status === "success" && r.result ? r.result : zeroAddress;
11116
- cache[id] = addr.toLowerCase();
11149
+ const addr2 = r.status === "success" && r.result ? r.result : zeroAddress;
11150
+ cache[id] = addr2.toLowerCase();
11117
11151
  });
11118
11152
  } catch {
11119
11153
  }
@@ -11161,15 +11195,15 @@ async function fetchListaFixedTerms(chainId, marketKeys) {
11161
11195
  }
11162
11196
  return out;
11163
11197
  }
11164
- function getCachedListaFixedTerms(chainId, marketKey) {
11165
- return FIXED_TERMS_CACHE[chainId]?.[toBytes32MarketId(marketKey)];
11198
+ function getCachedListaFixedTerms(chainId, marketKey2) {
11199
+ return FIXED_TERMS_CACHE[chainId]?.[toBytes32MarketId(marketKey2)];
11166
11200
  }
11167
11201
  async function fetchListaBrokerUserData(chainId, account, marketKeys, nowSecs = Math.floor(Date.now() / 1e3), getClient = getEvmClient) {
11168
11202
  const brokers = await resolveListaBrokers(chainId, marketKeys, getClient);
11169
11203
  const ids = Object.keys(brokers);
11170
11204
  const out = {};
11171
- const cacheKey4 = `${chainId}:${account.toLowerCase()}`;
11172
- BROKER_USER_CACHE[cacheKey4] = out;
11205
+ const cacheKey5 = `${chainId}:${account.toLowerCase()}`;
11206
+ BROKER_USER_CACHE[cacheKey5] = out;
11173
11207
  if (ids.length === 0) return out;
11174
11208
  try {
11175
11209
  const client = getClient(chainId);
@@ -11272,8 +11306,8 @@ async function fetchListaBrokerUserData(chainId, account, marketKeys, nowSecs =
11272
11306
  }
11273
11307
  return out;
11274
11308
  }
11275
- function getCachedListaBrokerUserData(chainId, account, marketKey) {
11276
- return BROKER_USER_CACHE[`${chainId}:${account.toLowerCase()}`]?.[toBytes32MarketId(marketKey)];
11309
+ function getCachedListaBrokerUserData(chainId, account, marketKey2) {
11310
+ return BROKER_USER_CACHE[`${chainId}:${account.toLowerCase()}`]?.[toBytes32MarketId(marketKey2)];
11277
11311
  }
11278
11312
  var { chunk } = lodash;
11279
11313
  var MORPHO_LENS = {
@@ -12530,12 +12564,12 @@ function rateToApy(rate) {
12530
12564
  );
12531
12565
  }
12532
12566
  function parseLtv(ltv) {
12533
- let str2 = 0;
12567
+ let str3 = 0;
12534
12568
  try {
12535
- str2 = Number(formatUnits(BigInt(ltv), 18));
12569
+ str3 = Number(formatUnits(BigInt(ltv), 18));
12536
12570
  } catch (e) {
12537
12571
  }
12538
- return str2;
12572
+ return str3;
12539
12573
  }
12540
12574
  function liquidationPenaltyFromLltv(lltv) {
12541
12575
  if (!lltv || lltv <= 0) return 0;
@@ -18424,13 +18458,13 @@ function findVaultInfo(normalizedAddr, vaultData) {
18424
18458
  function buildAdjacencyList(vaultData) {
18425
18459
  const adj = /* @__PURE__ */ new Map();
18426
18460
  const knownVaults = /* @__PURE__ */ new Set();
18427
- for (const addr of vaultData.keys()) {
18428
- const norm = addr.toLowerCase();
18461
+ for (const addr2 of vaultData.keys()) {
18462
+ const norm = addr2.toLowerCase();
18429
18463
  knownVaults.add(norm);
18430
18464
  adj.set(norm, /* @__PURE__ */ new Set());
18431
18465
  }
18432
- for (const [addr, info] of vaultData) {
18433
- const from = addr.toLowerCase();
18466
+ for (const [addr2, info] of vaultData) {
18467
+ const from = addr2.toLowerCase();
18434
18468
  const activeCollaterals = getActiveCollaterals(info.collateralLTVInfo);
18435
18469
  for (const to of activeCollaterals) {
18436
18470
  if (knownVaults.has(to) && from !== to) {
@@ -18473,8 +18507,8 @@ function findConnectedComponents(adj) {
18473
18507
  function deriveGovernor(vaultAddresses, vaultData) {
18474
18508
  const counts = /* @__PURE__ */ new Map();
18475
18509
  const zeroNorm = zeroAddress;
18476
- for (const addr of vaultAddresses) {
18477
- const info = findVaultInfo(addr, vaultData);
18510
+ for (const addr2 of vaultAddresses) {
18511
+ const info = findVaultInfo(addr2, vaultData);
18478
18512
  if (!info) continue;
18479
18513
  const gov = info.governorAdmin?.toLowerCase();
18480
18514
  if (!gov || gov === zeroNorm) continue;
@@ -18499,8 +18533,8 @@ function deriveClusters(vaultData, includeSingletons = false) {
18499
18533
  if (!includeSingletons && component.length < 2) continue;
18500
18534
  if (!includeSingletons) {
18501
18535
  let hasActiveEdge = false;
18502
- for (const addr of component) {
18503
- const neighbors = adj.get(addr);
18536
+ for (const addr2 of component) {
18537
+ const neighbors = adj.get(addr2);
18504
18538
  if (neighbors && neighbors.size > 0) {
18505
18539
  hasActiveEdge = true;
18506
18540
  break;
@@ -18509,9 +18543,9 @@ function deriveClusters(vaultData, includeSingletons = false) {
18509
18543
  if (!hasActiveEdge) continue;
18510
18544
  }
18511
18545
  const clusterVaultData = /* @__PURE__ */ new Map();
18512
- for (const addr of component) {
18513
- const info = findVaultInfo(addr, vaultData);
18514
- if (info) clusterVaultData.set(addr, info);
18546
+ for (const addr2 of component) {
18547
+ const info = findVaultInfo(addr2, vaultData);
18548
+ if (info) clusterVaultData.set(addr2, info);
18515
18549
  }
18516
18550
  clusters.push({
18517
18551
  governor: deriveGovernor(component, vaultData),
@@ -18536,21 +18570,21 @@ function toTokenAmount(raw, decimals) {
18536
18570
  }
18537
18571
  function identifyBorrowVaults(cluster) {
18538
18572
  const borrowVaults = /* @__PURE__ */ new Set();
18539
- for (const [addr, info] of cluster.vaultData) {
18573
+ for (const [addr2, info] of cluster.vaultData) {
18540
18574
  const hasIRM = info.interestRateModel && info.interestRateModel.toLowerCase() !== zeroAddress;
18541
18575
  const hasActiveCollateral = (info.collateralLTVInfo ?? []).some(
18542
18576
  (ltv) => ltv.borrowLTV > 0n
18543
18577
  );
18544
18578
  if (hasIRM && hasActiveCollateral) {
18545
- borrowVaults.add(addr.toLowerCase());
18579
+ borrowVaults.add(addr2.toLowerCase());
18546
18580
  }
18547
18581
  }
18548
18582
  return borrowVaults;
18549
18583
  }
18550
18584
  function buildReverseLTVIndex(cluster) {
18551
18585
  const index = /* @__PURE__ */ new Map();
18552
- for (const [addr, info] of cluster.vaultData) {
18553
- const borrowVault = addr.toLowerCase();
18586
+ for (const [addr2, info] of cluster.vaultData) {
18587
+ const borrowVault = addr2.toLowerCase();
18554
18588
  for (const ltv of info.collateralLTVInfo ?? []) {
18555
18589
  if (ltv.borrowLTV <= 0n) continue;
18556
18590
  const collateral = ltv.collateral.toLowerCase();
@@ -18601,8 +18635,8 @@ function buildTokenConfig(vaultAddr, reverseLTV, borrowVaults, vaultData) {
18601
18635
  }
18602
18636
  function buildEModes(borrowVaults, cluster) {
18603
18637
  const eModes = {};
18604
- for (const addr of borrowVaults) {
18605
- const info = findInfo(addr, cluster.vaultData);
18638
+ for (const addr2 of borrowVaults) {
18639
+ const info = findInfo(addr2, cluster.vaultData);
18606
18640
  if (!info) continue;
18607
18641
  const activeLTVs = info.collateralLTVInfo.filter((l) => l.borrowLTV > 0n);
18608
18642
  const avgBorrowLTV = activeLTVs.length > 0 ? activeLTVs.reduce((sum, l) => sum + ltvToNumber(l.borrowLTV), 0) / activeLTVs.length : 0;
@@ -18610,8 +18644,8 @@ function buildEModes(borrowVaults, cluster) {
18610
18644
  (sum, l) => sum + ltvToNumber(l.liquidationLTV),
18611
18645
  0
18612
18646
  ) / activeLTVs.length : 0;
18613
- eModes[addr] = {
18614
- category: addr,
18647
+ eModes[addr2] = {
18648
+ category: addr2,
18615
18649
  label: `${info.assetSymbol} Borrow (${info.vaultSymbol})`,
18616
18650
  borrowCollateralFactor: avgBorrowLTV,
18617
18651
  collateralFactor: avgLiqLTV,
@@ -18633,11 +18667,11 @@ function buildMetadata(info) {
18633
18667
  }
18634
18668
  function buildTokenEntry(info, config, collateralActive, borrowVaults, opts) {
18635
18669
  if (!info.asset) return void 0;
18636
- const addr = info.asset.toLowerCase();
18637
- const tokenMeta = opts.tokenList?.[addr];
18670
+ const addr2 = info.asset.toLowerCase();
18671
+ const tokenMeta = opts.tokenList?.[addr2];
18638
18672
  const asset = {
18639
18673
  chainId: opts.chainId,
18640
- address: addr,
18674
+ address: addr2,
18641
18675
  name: tokenMeta?.name ?? info.assetName,
18642
18676
  symbol: tokenMeta?.symbol ?? info.assetSymbol,
18643
18677
  decimals: tokenMeta?.decimals ?? Number(info.assetDecimals)
@@ -18698,9 +18732,9 @@ function buildTokenEntry(info, config, collateralActive, borrowVaults, opts) {
18698
18732
  params: { metadata: buildMetadata(info) }
18699
18733
  };
18700
18734
  }
18701
- function findInfo(addr, vaultData) {
18735
+ function findInfo(addr2, vaultData) {
18702
18736
  for (const [key, value] of vaultData) {
18703
- if (key.toLowerCase() === addr) return value;
18737
+ if (key.toLowerCase() === addr2) return value;
18704
18738
  }
18705
18739
  return void 0;
18706
18740
  }
@@ -18715,8 +18749,8 @@ function normalizeCluster(cluster, opts) {
18715
18749
  }
18716
18750
  const eModes = buildEModes(borrowVaults, cluster);
18717
18751
  const data = {};
18718
- for (const [addr, info] of cluster.vaultData) {
18719
- const norm = addr.toLowerCase();
18752
+ for (const [addr2, info] of cluster.vaultData) {
18753
+ const norm = addr2.toLowerCase();
18720
18754
  const config = buildTokenConfig(
18721
18755
  norm,
18722
18756
  reverseLTV,
@@ -18861,8 +18895,8 @@ var getEulerV2ReservesDataConverter = (lender, chainId, prices, additionalYields
18861
18895
  var BASE_CALLS_PER_RESERVE = 5;
18862
18896
  var CALLS_PER_SPOKE_TAIL = 1;
18863
18897
  var MAX_HUB_ASSETS = 25;
18864
- function isValidAddress(addr) {
18865
- return !!addr && addr !== "0x" && addr.length > 2;
18898
+ function isValidAddress(addr2) {
18899
+ return !!addr2 && addr2 !== "0x" && addr2.length > 2;
18866
18900
  }
18867
18901
  function getDynamicConfigCount(spokeEntry) {
18868
18902
  const max = spokeEntry?.dynamicConfigKeyMax ?? 0;
@@ -19206,8 +19240,8 @@ function normalizeAaveV4(spokeDataList, chainId, spokeLenderKeyArg, prices, addi
19206
19240
  }
19207
19241
 
19208
19242
  // src/lending/public-data/aave-v4-type/publicCallParse.ts
19209
- function isValidAddress2(addr) {
19210
- return !!addr && addr !== "0x" && addr.length > 2;
19243
+ function isValidAddress2(addr2) {
19244
+ return !!addr2 && addr2 !== "0x" && addr2.length > 2;
19211
19245
  }
19212
19246
  var getAaveV4ReservesDataConverter = (lender, chainId, prices, additionalYields, tokenList = {}) => {
19213
19247
  const expectedCalls = getAaveV4ExpectedCallCount(chainId, lender);
@@ -19656,7 +19690,7 @@ var getSiloV2ReservesDataConverter = (lender, chainId, prices, additionalYields,
19656
19690
  { self: market.silo0, other: market.silo1 },
19657
19691
  { self: market.silo1, other: market.silo0 }
19658
19692
  ];
19659
- const toBigInt16 = (v) => {
19693
+ const toBigInt17 = (v) => {
19660
19694
  if (v === void 0 || v === null || v === "0x") return 0n;
19661
19695
  if (typeof v === "bigint") return v;
19662
19696
  try {
@@ -19668,8 +19702,8 @@ var getSiloV2ReservesDataConverter = (lender, chainId, prices, additionalYields,
19668
19702
  for (let s = 0; s < 2; s++) {
19669
19703
  const { self, other } = sides[s];
19670
19704
  const slot = s * SILO_V2_CALLS_PER_SIDE;
19671
- const totalAssetsRaw = toBigInt16(data[slot]);
19672
- const debtAssetsRaw = toBigInt16(data[slot + 1]);
19705
+ const totalAssetsRaw = toBigInt17(data[slot]);
19706
+ const debtAssetsRaw = toBigInt17(data[slot + 1]);
19673
19707
  const irmConfigRaw = data[slot + 2];
19674
19708
  const decimals = self.decimals;
19675
19709
  const totalDeposits = Number(formatUnits(totalAssetsRaw, decimals));
@@ -19824,7 +19858,7 @@ var getSiloV3ReservesDataConverter = (lender, chainId, prices, additionalYields,
19824
19858
  { self: market.silo0, other: market.silo1 },
19825
19859
  { self: market.silo1, other: market.silo0 }
19826
19860
  ];
19827
- const toBigInt16 = (v) => {
19861
+ const toBigInt17 = (v) => {
19828
19862
  if (v === void 0 || v === null || v === "0x") return 0n;
19829
19863
  if (typeof v === "bigint") return v;
19830
19864
  try {
@@ -19836,8 +19870,8 @@ var getSiloV3ReservesDataConverter = (lender, chainId, prices, additionalYields,
19836
19870
  for (let s = 0; s < 2; s++) {
19837
19871
  const { self, other } = sides[s];
19838
19872
  const slot = s * SILO_V3_CALLS_PER_SIDE;
19839
- const totalAssetsRaw = toBigInt16(data[slot]);
19840
- const debtAssetsRaw = toBigInt16(data[slot + 1]);
19873
+ const totalAssetsRaw = toBigInt17(data[slot]);
19874
+ const debtAssetsRaw = toBigInt17(data[slot + 1]);
19841
19875
  const irmConfigRaw = data[slot + 2];
19842
19876
  const decimals = self.decimals;
19843
19877
  const totalDeposits = Number(formatUnits(totalAssetsRaw, decimals));
@@ -19962,7 +19996,7 @@ var buildFluidCall = (chainId, _lender) => {
19962
19996
 
19963
19997
  // src/lending/public-data/fluid/publicCallParse.ts
19964
19998
  var FLUID_EEE_LOWER = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
19965
- var normalizeUnderlying = (addr) => addr === FLUID_EEE_LOWER ? zeroAddress : addr;
19999
+ var normalizeUnderlying = (addr2) => addr2 === FLUID_EEE_LOWER ? zeroAddress : addr2;
19966
20000
  var FLUID_RATE_SCALE = 100;
19967
20001
  var scaleFluidRate = (raw) => {
19968
20002
  if (raw === void 0 || raw === null) return 0;
@@ -20465,9 +20499,9 @@ var getGearboxV3PublicDataConverter = (_lender, chainId, prices, additionalYield
20465
20499
  const underlyingPrice = prices[underlyingPriceKey] ?? 0;
20466
20500
  const debtByCm = {};
20467
20501
  for (const dp of pool.creditManagerDebtParams ?? []) {
20468
- const addr = (dp?.creditManager ?? "").toString().toLowerCase();
20469
- if (!addr) continue;
20470
- debtByCm[addr] = {
20502
+ const addr2 = (dp?.creditManager ?? "").toString().toLowerCase();
20503
+ if (!addr2) continue;
20504
+ debtByCm[addr2] = {
20471
20505
  borrowed: BigInt(dp.borrowed ?? 0),
20472
20506
  limit: BigInt(dp.limit ?? 0),
20473
20507
  available: BigInt(dp.available ?? 0)
@@ -21091,7 +21125,7 @@ function createMidnightBookSource(chainId, fetchImpl = fetch) {
21091
21125
  var MIDNIGHT_BOOK_LEVELS = 20;
21092
21126
  var LKG_TTL_SEC = 30 * 60;
21093
21127
  var lastGood = /* @__PURE__ */ new Map();
21094
- async function fetchTopAndBookWithFallback(source, chainId, marketId, nowSec7) {
21128
+ async function fetchTopAndBookWithFallback(source, chainId, marketId, nowSec9) {
21095
21129
  const key = `${chainId}:${marketId}`;
21096
21130
  let fresh = null;
21097
21131
  if (source.getTopAndBook) {
@@ -21101,11 +21135,11 @@ async function fetchTopAndBookWithFallback(source, chainId, marketId, nowSec7) {
21101
21135
  if (top) fresh = { top, book: { bids: [], asks: [] } };
21102
21136
  }
21103
21137
  if (fresh) {
21104
- lastGood.set(key, { top: fresh.top, book: fresh.book, at: nowSec7 });
21138
+ lastGood.set(key, { top: fresh.top, book: fresh.book, at: nowSec9 });
21105
21139
  return { top: fresh.top, book: fresh.book };
21106
21140
  }
21107
21141
  const cached = lastGood.get(key);
21108
- if (cached && nowSec7 - cached.at <= LKG_TTL_SEC) {
21142
+ if (cached && nowSec9 - cached.at <= LKG_TTL_SEC) {
21109
21143
  return { top: cached.top, book: cached.book };
21110
21144
  }
21111
21145
  return { top: null, book: null };
@@ -21113,17 +21147,17 @@ async function fetchTopAndBookWithFallback(source, chainId, marketId, nowSec7) {
21113
21147
  async function fetchMidnightMarkets(chainId, source = createMidnightBookSource(chainId)) {
21114
21148
  const markets = midnightMarketsByChain(chainId);
21115
21149
  if (markets.length === 0) return [];
21116
- const nowSec7 = Math.floor(Date.now() / 1e3);
21150
+ const nowSec9 = Math.floor(Date.now() / 1e3);
21117
21151
  return Promise.all(
21118
21152
  markets.map(async (config) => {
21119
- if (Number(config.maturity) <= nowSec7) {
21153
+ if (Number(config.maturity) <= nowSec9) {
21120
21154
  return { config, top: null, book: null };
21121
21155
  }
21122
21156
  const { top, book } = await fetchTopAndBookWithFallback(
21123
21157
  source,
21124
21158
  chainId,
21125
21159
  config.marketId,
21126
- nowSec7
21160
+ nowSec9
21127
21161
  );
21128
21162
  return { config, top, book };
21129
21163
  })
@@ -21230,9 +21264,9 @@ function midnightLenderKey(marketId) {
21230
21264
  return "MORPHO_MIDNIGHT_" + marketId.slice(2).toUpperCase();
21231
21265
  }
21232
21266
  function currencyFor(address, decimals, tokens) {
21233
- const lower = address.toLowerCase();
21234
- return tokens[lower] ?? {
21235
- address: lower,
21267
+ const lower3 = address.toLowerCase();
21268
+ return tokens[lower3] ?? {
21269
+ address: lower3,
21236
21270
  symbol: "",
21237
21271
  name: "",
21238
21272
  decimals
@@ -21470,6 +21504,20 @@ var toBig3 = (v) => {
21470
21504
  return 0n;
21471
21505
  }
21472
21506
  };
21507
+ function pickAuction(rows, nowSec9 = Math.floor(Date.now() / 1e3)) {
21508
+ if (!Array.isArray(rows) || rows.length === 0) return null;
21509
+ const live = rows.filter((a) => a && !a.delisted && !a.nonViableAuction).map((a) => ({
21510
+ id: String(a.id ?? ""),
21511
+ startTime: toNum(a.auctionStartTime),
21512
+ revealTime: toNum(a.revealTime),
21513
+ endTime: toNum(a.auctionEndTime),
21514
+ minBidAmount: String(a.auctionMinBidAmount ?? "0"),
21515
+ minOfferAmount: String(a.auctionMinOfferAmount ?? "0"),
21516
+ maxBidPriceWad: String(a.auctionMaxBidPrice ?? "0"),
21517
+ maxOfferPriceWad: String(a.auctionMaxOfferPrice ?? "0")
21518
+ })).filter((a) => a.endTime > nowSec9).sort((a, b) => a.endTime - b.endTime);
21519
+ return live[0] ?? null;
21520
+ }
21473
21521
  var TermSubgraphSource = class {
21474
21522
  url;
21475
21523
  fetchImpl;
@@ -21504,29 +21552,54 @@ var TermSubgraphSource = class {
21504
21552
  }
21505
21553
  /**
21506
21554
  * ONE query → the aggregate top (best APR + FULL depth) PLUS a bounded book
21507
- * slice (top `maxLevels` open orders per side). `asks` = orders selling repo
21508
- * tokens (the secondary LEND book); `bids` = the rest (borrow side, usually
21509
- * empty Term borrow is sealed-bid auction, not a continuous book). Term
21510
- * secondary orders carry no per-order rate, so every level shares the market's
21511
- * clearing APR; the levels expose per-order SIZE for filtering.
21555
+ * slice (top `maxLevels` open orders per side) PLUS the repo's current
21556
+ * auction round. `asks` = orders selling repo tokens (the secondary LEND
21557
+ * book); `bids` = the rest (borrow side, usually empty Term borrow is
21558
+ * sealed-bid auction, not a continuous book). Term secondary orders carry no
21559
+ * per-order rate, so every level shares the market's clearing APR; the levels
21560
+ * expose per-order SIZE for filtering.
21561
+ *
21562
+ * Two auction reads, deliberately distinct:
21563
+ * - `cleared` — the latest COMPLETE round, whose clearing price IS the
21564
+ * market's fixed APR (and stays the reference rate between auctions).
21565
+ * - `pending` — rounds not yet complete/cancelled. Only one of these is a
21566
+ * real, actionable round; the rest are abandoned listings the subgraph
21567
+ * never marked complete, filtered out below.
21512
21568
  */
21513
21569
  async getTopAndBook(config, maxLevels = 20) {
21514
21570
  const id = config.termRepoId.toLowerCase();
21515
21571
  const repoToken = config.repoToken.toLowerCase();
21516
21572
  const data = await this.gql(
21517
- `query Top($id: ID!, $repoId: Bytes!) {
21573
+ `query Top($id: ID!, $termId: String!, $repoId: Bytes!) {
21518
21574
  termRepo(id: $id) { termRepoTokenRedemptionRatio }
21519
21575
  termAuctions(where: { term: $id, auctionComplete: true }, orderBy: auctionEndTime, orderDirection: desc, first: 1) {
21520
21576
  auctionClearingPrice
21521
21577
  dayCountFractionMantissa
21522
21578
  }
21579
+ pending: termAuctions(
21580
+ where: { term: $termId, auctionComplete: false, auctionCancelled: false }
21581
+ orderBy: auctionEndTime
21582
+ orderDirection: desc
21583
+ first: 5
21584
+ ) {
21585
+ id
21586
+ auctionStartTime
21587
+ revealTime
21588
+ auctionEndTime
21589
+ delisted
21590
+ nonViableAuction
21591
+ auctionMinBidAmount
21592
+ auctionMinOfferAmount
21593
+ auctionMaxBidPrice
21594
+ auctionMaxOfferPrice
21595
+ }
21523
21596
  termOrders(where: { termRepoId: $repoId, orderCancelled: false }, first: 500) {
21524
21597
  makerToken
21525
21598
  originalOrderAmount
21526
21599
  filledAmount
21527
21600
  }
21528
21601
  }`,
21529
- { id, repoId: id }
21602
+ { id, termId: id, repoId: id }
21530
21603
  );
21531
21604
  if (!data) return null;
21532
21605
  const redemptionRatio = toBig3(data.termRepo?.termRepoTokenRedemptionRatio) || BigInt(WAD3);
@@ -21563,7 +21636,7 @@ var TermSubgraphSource = class {
21563
21636
  supplyLiquidity: toLoan(supplyUnits),
21564
21637
  borrowLiquidity: toLoan(borrowUnits)
21565
21638
  };
21566
- return { top, book: { bids, asks } };
21639
+ return { top, book: { bids, asks }, auction: pickAuction(data.pending) };
21567
21640
  }
21568
21641
  async getListings(config) {
21569
21642
  const id = config.termRepoId.toLowerCase();
@@ -21665,41 +21738,47 @@ function createTermBookSource(chainId, fetchImpl = fetch) {
21665
21738
  var TERM_BOOK_LEVELS = 20;
21666
21739
  var LKG_TTL_SEC2 = 30 * 60;
21667
21740
  var lastGood2 = /* @__PURE__ */ new Map();
21668
- async function fetchTopAndBookWithFallback2(source, chainId, config, nowSec7) {
21741
+ async function fetchTopAndBookWithFallback2(source, chainId, config, nowSec9) {
21669
21742
  const key = `${chainId}:${config.termRepoId}`;
21670
21743
  let fresh = null;
21671
21744
  if (source.getTopAndBook) {
21672
21745
  fresh = await source.getTopAndBook(config, TERM_BOOK_LEVELS).catch(() => null);
21673
21746
  } else {
21674
21747
  const top = await source.getBookTop(config).catch(() => null);
21675
- if (top) fresh = { top, book: { bids: [], asks: [] } };
21748
+ if (top) fresh = { top, book: { bids: [], asks: [] }, auction: null };
21676
21749
  }
21677
21750
  if (fresh) {
21678
- lastGood2.set(key, { top: fresh.top, book: fresh.book, at: nowSec7 });
21679
- return { top: fresh.top, book: fresh.book };
21751
+ lastGood2.set(key, {
21752
+ top: fresh.top,
21753
+ book: fresh.book,
21754
+ auction: fresh.auction ?? null,
21755
+ at: nowSec9
21756
+ });
21757
+ return { top: fresh.top, book: fresh.book, auction: fresh.auction ?? null };
21680
21758
  }
21681
21759
  const cached = lastGood2.get(key);
21682
- if (cached && nowSec7 - cached.at <= LKG_TTL_SEC2) {
21683
- return { top: cached.top, book: cached.book };
21760
+ if (cached && nowSec9 - cached.at <= LKG_TTL_SEC2) {
21761
+ const stillOpen = cached.auction && cached.auction.endTime > nowSec9 ? cached.auction : null;
21762
+ return { top: cached.top, book: cached.book, auction: stillOpen };
21684
21763
  }
21685
- return { top: null, book: null };
21764
+ return { top: null, book: null, auction: null };
21686
21765
  }
21687
21766
  async function fetchTermMarkets(chainId, source = createTermBookSource(chainId)) {
21688
21767
  const markets = termMarketsByChain(chainId);
21689
21768
  if (markets.length === 0) return [];
21690
- const nowSec7 = Math.floor(Date.now() / 1e3);
21769
+ const nowSec9 = Math.floor(Date.now() / 1e3);
21691
21770
  return Promise.all(
21692
21771
  markets.map(async (config) => {
21693
- if (Number(config.maturity) <= nowSec7) {
21694
- return { config, top: null, book: null };
21772
+ if (Number(config.maturity) <= nowSec9) {
21773
+ return { config, top: null, book: null, auction: null };
21695
21774
  }
21696
- const { top, book } = await fetchTopAndBookWithFallback2(
21775
+ const { top, book, auction } = await fetchTopAndBookWithFallback2(
21697
21776
  source,
21698
21777
  chainId,
21699
21778
  config,
21700
- nowSec7
21779
+ nowSec9
21701
21780
  );
21702
- return { config, top, book };
21781
+ return { config, top, book, auction };
21703
21782
  })
21704
21783
  );
21705
21784
  }
@@ -21733,9 +21812,79 @@ function termLenderKey(termRepoId) {
21733
21812
  const body = termRepoId.startsWith("0x") ? termRepoId.slice(2) : termRepoId;
21734
21813
  return "TERM_FINANCE_" + body.toUpperCase();
21735
21814
  }
21815
+ function fmtDuration(secs) {
21816
+ if (secs >= 2 * 86400) return `${Math.round(secs / 86400)} days`;
21817
+ if (secs >= 2 * 3600) return `${Math.round(secs / 3600)} hours`;
21818
+ return `${Math.max(1, Math.round(secs / 60))} minutes`;
21819
+ }
21820
+ function auctionImplications(status, matured, secondsUntilClose) {
21821
+ const out = [];
21822
+ if (matured) {
21823
+ out.push(
21824
+ "This term has MATURED \u2014 it can no longer be borrowed or lent. Existing positions settle through the repurchase/redemption window."
21825
+ );
21826
+ return out;
21827
+ }
21828
+ if (status === "open") {
21829
+ out.push(
21830
+ `\u26A0 Borrowing is a SEALED BID into an auction, not an instant loan. Submissions close in ${secondsUntilClose != null ? fmtDuration(secondsUntilClose) : "a limited window"}; after that nothing can be borrowed until the next round is listed.`
21831
+ );
21832
+ out.push(
21833
+ "Your rate is NOT the rate shown \u2014 the shown figure is the last round\u2019s clearing rate. Your actual rate is set when this round clears, and a bid above the clearing rate may not be filled at all."
21834
+ );
21835
+ } else if (status === "revealing") {
21836
+ out.push(
21837
+ "\u26A0 Bidding has CLOSED for this round \u2014 sealed prices are being revealed and the auction is clearing. No new borrows until the next round is listed."
21838
+ );
21839
+ } else if (status === "upcoming") {
21840
+ out.push(
21841
+ "An auction round is scheduled but not yet accepting bids. Borrowing becomes possible when it opens."
21842
+ );
21843
+ } else {
21844
+ out.push(
21845
+ "\u26A0 NO auction is open, so this market CANNOT be borrowed right now. Term originates loans only during scheduled sealed-bid auctions."
21846
+ );
21847
+ out.push(
21848
+ "Any borrow rate shown is the last round\u2019s clearing rate \u2014 historical, not obtainable."
21849
+ );
21850
+ }
21851
+ out.push(
21852
+ "Lending is still possible between rounds by buying repo tokens on the secondary market; only borrowing depends on the auction window."
21853
+ );
21854
+ out.push(
21855
+ "Fixed maturity: the debt is a static face value with no interest accrual, repayable up to the end of the repurchase window."
21856
+ );
21857
+ return out;
21858
+ }
21859
+ function toFixedTermAuction(auction, now, matured = false) {
21860
+ const base = { canBorrow: false, canLend: !matured };
21861
+ if (!auction || auction.endTime <= now) {
21862
+ return {
21863
+ status: "closed",
21864
+ ...base,
21865
+ implications: auctionImplications("closed", matured)
21866
+ };
21867
+ }
21868
+ const status = now < auction.startTime ? "upcoming" : now < auction.revealTime ? "open" : "revealing";
21869
+ const secondsUntilClose = status === "open" ? Math.max(0, auction.revealTime - now) : void 0;
21870
+ return {
21871
+ status,
21872
+ ...base,
21873
+ // A matured repo is never borrowable, whatever the round says.
21874
+ canBorrow: status === "open" && !matured,
21875
+ secondsUntilClose,
21876
+ implications: auctionImplications(status, matured, secondsUntilClose),
21877
+ id: auction.id,
21878
+ startTime: auction.startTime,
21879
+ revealTime: auction.revealTime,
21880
+ endTime: auction.endTime,
21881
+ minBorrowAmount: auction.minBidAmount,
21882
+ minLendAmount: auction.minOfferAmount
21883
+ };
21884
+ }
21736
21885
  function currencyFor2(address, decimals, tokens) {
21737
- const lower = address.toLowerCase();
21738
- return tokens[lower] ?? { address: lower, symbol: "", name: "", decimals };
21886
+ const lower3 = address.toLowerCase();
21887
+ return tokens[lower3] ?? { address: lower3, symbol: "", name: "", decimals };
21739
21888
  }
21740
21889
  function convertTermMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
21741
21890
  intrinsicYields: {},
@@ -21744,7 +21893,7 @@ function convertTermMarketsToResponse(raw, chainId, prices = {}, _additionalYiel
21744
21893
  }, tokens = {}) {
21745
21894
  const out = {};
21746
21895
  const now = nowSec2();
21747
- for (const { config, top, book } of raw) {
21896
+ for (const { config, top, book, auction } of raw) {
21748
21897
  if (!config?.termRepoId || !config.purchaseToken) continue;
21749
21898
  const m = termLenderKey(config.termRepoId);
21750
21899
  const maturity = Number(config.maturity);
@@ -21752,7 +21901,9 @@ function convertTermMarketsToResponse(raw, chainId, prices = {}, _additionalYiel
21752
21901
  const matured = ttm <= 0;
21753
21902
  const supplyAprPct = !matured ? top?.supplyAprPct ?? 0 : 0;
21754
21903
  const borrowAprPct = !matured ? top?.borrowAprPct ?? 0 : 0;
21755
- const terms = borrowAprPct > 0 && !matured ? [
21904
+ const auctionInfo = toFixedTermAuction(auction, now, matured);
21905
+ const auctionOpen = auctionInfo.canBorrow;
21906
+ const terms = borrowAprPct > 0 && auctionOpen ? [
21756
21907
  {
21757
21908
  termId: 0,
21758
21909
  durationSecs: Math.max(0, ttm),
@@ -21807,10 +21958,15 @@ function convertTermMarketsToResponse(raw, chainId, prices = {}, _additionalYiel
21807
21958
  },
21808
21959
  closeFactor: 1,
21809
21960
  collateralActive: false,
21810
- borrowingEnabled: !matured,
21811
- depositsEnabled: !matured,
21961
+ // Borrow needs a LIVE auction round, not just an unmatured repo.
21962
+ // `depositsEnabled` stays on the maturity alone: lending is also possible
21963
+ // between rounds by buying repo tokens on the secondary book.
21964
+ borrowingEnabled: auctionOpen,
21965
+ depositsEnabled: auctionInfo.canLend,
21812
21966
  hasStable: false,
21813
- variableBorrowDisabled: false,
21967
+ // Term has no variable rate at all; between auctions there is no
21968
+ // borrowable rate either, so flag it rather than let a 0 read as free.
21969
+ variableBorrowDisabled: true,
21814
21970
  isActive: true,
21815
21971
  isFrozen: false
21816
21972
  };
@@ -21893,7 +22049,11 @@ function convertTermMarketsToResponse(raw, chainId, prices = {}, _additionalYiel
21893
22049
  earlyRepay: { kind: "none" },
21894
22050
  // Fixed rate is discovered by the periodic sealed-bid auction; the
21895
22051
  // per-repo servicer is the market-level venue reference.
21896
- provider: { kind: "auction", address: config.servicer }
22052
+ provider: { kind: "auction", address: config.servicer },
22053
+ // The origination window. `closed` (the common state between rounds)
22054
+ // is what tells a consumer that this market is display-only right
22055
+ // now, rather than an ordinary market with an empty rate card.
22056
+ auction: auctionInfo
21897
22057
  },
21898
22058
  collateralParams: config.collateralParams,
21899
22059
  // Bounded book slice (top-N open orders/side) for later filtering. Term
@@ -21974,8 +22134,8 @@ function toHuman(raw, decimals) {
21974
22134
  return Number(raw) / 10 ** decimals;
21975
22135
  }
21976
22136
  function currencyFor3(address, decimals, symbol, tokens) {
21977
- const lower = address.toLowerCase();
21978
- return tokens[lower] ?? { address: lower, symbol, name: symbol, decimals };
22137
+ const lower3 = address.toLowerCase();
22138
+ return tokens[lower3] ?? { address: lower3, symbol, name: symbol, decimals };
21979
22139
  }
21980
22140
  function convertExactlyMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
21981
22141
  intrinsicYields: {},
@@ -22245,8 +22405,8 @@ function toHuman2(raw, decimals) {
22245
22405
  return Number(raw) / 10 ** decimals;
22246
22406
  }
22247
22407
  function currencyFor4(address, decimals, symbol, tokens) {
22248
- const lower = address.toLowerCase();
22249
- return tokens[lower] ?? { address: lower, symbol, name: symbol, decimals };
22408
+ const lower3 = address.toLowerCase();
22409
+ return tokens[lower3] ?? { address: lower3, symbol, name: symbol, decimals };
22250
22410
  }
22251
22411
  function convertLiquityMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
22252
22412
  intrinsicYields: {},
@@ -22522,8 +22682,8 @@ function toHuman3(raw, decimals) {
22522
22682
  return Number(raw) / 10 ** decimals;
22523
22683
  }
22524
22684
  function currencyFor5(address, decimals, symbol, tokens) {
22525
- const lower = address.toLowerCase();
22526
- return tokens[lower] ?? { address: lower, symbol, name: symbol, decimals };
22685
+ const lower3 = address.toLowerCase();
22686
+ return tokens[lower3] ?? { address: lower3, symbol, name: symbol, decimals };
22527
22687
  }
22528
22688
  function convertRiverMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
22529
22689
  intrinsicYields: {},
@@ -22752,7 +22912,7 @@ async function fetchTellerMarkets(chainId) {
22752
22912
  } catch {
22753
22913
  return { chainId, pools: [] };
22754
22914
  }
22755
- const big4 = (i) => {
22915
+ const big7 = (i) => {
22756
22916
  const r = results[i];
22757
22917
  if (typeof r === "bigint") return r;
22758
22918
  if (typeof r === "number") return BigInt(r);
@@ -22765,21 +22925,21 @@ async function fetchTellerMarkets(chainId) {
22765
22925
  }
22766
22926
  return null;
22767
22927
  };
22768
- const num6 = (i) => {
22769
- const b = big4(i);
22928
+ const num9 = (i) => {
22929
+ const b = big7(i);
22770
22930
  return b === null ? null : Number(b);
22771
22931
  };
22772
22932
  const pool0 = pools.map((config, i) => {
22773
22933
  const base = i * READS_PER_POOL;
22774
22934
  return {
22775
22935
  config,
22776
- available: big4(base),
22777
- committed: big4(base + 1),
22778
- minRateBps: num6(base + 2),
22779
- collateralPerPrincipal: big4(base + 3),
22780
- maxLoanDuration: num6(base + 4),
22781
- marketId: big4(base + 5),
22782
- totalAssets: big4(base + 6)
22936
+ available: big7(base),
22937
+ committed: big7(base + 1),
22938
+ minRateBps: num9(base + 2),
22939
+ collateralPerPrincipal: big7(base + 3),
22940
+ maxLoanDuration: num9(base + 4),
22941
+ marketId: big7(base + 5),
22942
+ totalAssets: big7(base + 6)
22783
22943
  };
22784
22944
  });
22785
22945
  const attByMarket = /* @__PURE__ */ new Map();
@@ -22850,6 +23010,240 @@ async function fetchTellerMarkets(chainId) {
22850
23010
  });
22851
23011
  return { chainId, pools: out };
22852
23012
  }
23013
+ var DEFAULT_TERMMAX_API = "https://api.termmax.ts.finance";
23014
+ var warn3 = (...args) => {
23015
+ };
23016
+ function termMaxApiBase(chainId) {
23017
+ return termMaxApiBaseUrl(chainId) || DEFAULT_TERMMAX_API;
23018
+ }
23019
+ var toBig4 = (v) => {
23020
+ try {
23021
+ if (v == null) return 0n;
23022
+ if (typeof v === "bigint") return v;
23023
+ if (typeof v === "number") return BigInt(Math.trunc(v));
23024
+ const s = String(v).trim();
23025
+ if (s === "") return 0n;
23026
+ return BigInt(s.includes(".") ? s.slice(0, s.indexOf(".")) : s);
23027
+ } catch {
23028
+ return 0n;
23029
+ }
23030
+ };
23031
+ var toNum2 = (v) => {
23032
+ const n = Number(v);
23033
+ return Number.isFinite(n) ? n : 0;
23034
+ };
23035
+ var lower = (v) => String(v ?? "").toLowerCase();
23036
+ function parseCuts(raw) {
23037
+ if (!Array.isArray(raw)) return [];
23038
+ return raw.map((c) => ({
23039
+ xtReserve: toBig4(c?.xtReserve),
23040
+ liqSquare: toBig4(c?.liqSquare),
23041
+ offset: toBig4(c?.offset)
23042
+ }));
23043
+ }
23044
+ function parseFeeConfig(raw) {
23045
+ if (!raw) return void 0;
23046
+ return {
23047
+ lendTakerFeeRatio: toBig4(raw.lendTakerFeeRatio),
23048
+ lendMakerFeeRatio: toBig4(raw.lendMakerFeeRatio),
23049
+ borrowTakerFeeRatio: toBig4(raw.borrowTakerFeeRatio),
23050
+ borrowMakerFeeRatio: toBig4(raw.borrowMakerFeeRatio),
23051
+ mintGtFeeRatio: toBig4(raw.mintGtFeeRatio),
23052
+ mintGtFeeRef: toBig4(raw.mintGtFeeRef)
23053
+ };
23054
+ }
23055
+ function toUnix(iso) {
23056
+ if (typeof iso === "number") return Math.trunc(iso);
23057
+ const t = Date.parse(String(iso ?? ""));
23058
+ return Number.isFinite(t) ? Math.floor(t / 1e3) : 0;
23059
+ }
23060
+ function parseMarket(raw, assetDecimals) {
23061
+ const c = raw?.contracts;
23062
+ if (!c?.marketAddr || !c?.underlyingAddr || !c?.collateralAddr) return null;
23063
+ const debtToken = lower(c.underlyingAddr);
23064
+ const collateral = lower(c.collateralAddr);
23065
+ return {
23066
+ market: lower(c.marketAddr),
23067
+ ft: lower(c.ftAddr),
23068
+ xt: lower(c.xtAddr),
23069
+ gt: lower(c.gtAddr),
23070
+ debtToken,
23071
+ debtDecimals: assetDecimals.get(debtToken) ?? 18,
23072
+ collateral,
23073
+ collateralDecimals: assetDecimals.get(collateral) ?? 18,
23074
+ symbol: raw.symbol,
23075
+ maturity: toUnix(raw.maturity),
23076
+ maxLtv: String(raw.maxLtv ?? "0"),
23077
+ liquidationLtv: String(raw.liquidationLtv ?? "0"),
23078
+ liquidatable: raw.liquidatable !== false,
23079
+ liquidationWindowSeconds: toNum2(raw.liquidationWindowSeconds) || void 0,
23080
+ version: raw.version,
23081
+ feeConfig: parseFeeConfig(raw.defaultFeeConfig),
23082
+ isMatured: raw.isMatured === true,
23083
+ isEnabled: raw.isEnabled !== false
23084
+ };
23085
+ }
23086
+ function parseOrder(raw) {
23087
+ const oc = raw?.orderConfig?.contracts ?? raw?.orderInfo;
23088
+ const orderAddress = lower(oc?.orderAddr ?? raw?.orderInfo?.orderAddress);
23089
+ const marketAddress = lower(oc?.marketAddr ?? raw?.orderInfo?.marketAddress);
23090
+ if (!orderAddress || !marketAddress) return null;
23091
+ const state = raw?.orderInfo?.contractState ?? raw?.contractState ?? {};
23092
+ const meta = raw?.metadata ?? {};
23093
+ const term = raw?.priceInfo?.term ?? {};
23094
+ return {
23095
+ orderAddress,
23096
+ marketAddress,
23097
+ makerAddress: raw?.orderConfig?.makerAddress ? lower(raw.orderConfig.makerAddress) : void 0,
23098
+ makerIsVault: state.makerIsVault === true,
23099
+ virtualXtReserve: toBig4(state.virtualXtReserve),
23100
+ ftReserve: toBig4(state.ftReserve),
23101
+ xtReserve: toBig4(state.xtReserve),
23102
+ maxXtReserve: toBig4(state.maxXtReserve),
23103
+ gtId: toBig4(state.gtId),
23104
+ // ── the crossing ──
23105
+ takerLendCuts: parseCuts(state.borrowCurve),
23106
+ takerBorrowCuts: parseCuts(state.lendCurve),
23107
+ takerLendApr: term?.bcft?.apr != null ? toNum2(term.bcft.apr) : void 0,
23108
+ takerBorrowApr: term?.lcft?.apr != null ? toNum2(term.lcft.apr) : void 0,
23109
+ feeConfig: parseFeeConfig(state.feeConfig),
23110
+ lendCapacityUsd: toNum2(meta.lendCapacityValue),
23111
+ borrowCapacityUsd: toNum2(meta.borrowCapacityValue),
23112
+ lendCapacityAmount: toNum2(meta.lendCapacityAmount),
23113
+ borrowCapacityAmount: toNum2(meta.borrowCapacityAmount)
23114
+ };
23115
+ }
23116
+ function reduceTop2(orders) {
23117
+ let bestLendApr;
23118
+ let bestBorrowApr;
23119
+ let lendDepthUsd = 0;
23120
+ let borrowDepthUsd = 0;
23121
+ let lendDepthAmount = 0;
23122
+ let borrowDepthAmount = 0;
23123
+ for (const o of orders) {
23124
+ lendDepthUsd += o.lendCapacityUsd;
23125
+ borrowDepthUsd += o.borrowCapacityUsd;
23126
+ lendDepthAmount += o.lendCapacityAmount;
23127
+ borrowDepthAmount += o.borrowCapacityAmount;
23128
+ if (o.takerLendApr != null && o.takerLendApr > 0 && o.lendCapacityUsd > 0) {
23129
+ if (bestLendApr === void 0 || o.takerLendApr > bestLendApr) {
23130
+ bestLendApr = o.takerLendApr;
23131
+ }
23132
+ }
23133
+ if (o.takerBorrowApr != null && o.takerBorrowApr > 0 && o.borrowCapacityUsd > 0) {
23134
+ if (bestBorrowApr === void 0 || o.takerBorrowApr < bestBorrowApr) {
23135
+ bestBorrowApr = o.takerBorrowApr;
23136
+ }
23137
+ }
23138
+ }
23139
+ return {
23140
+ bestLendApr,
23141
+ bestBorrowApr,
23142
+ lendDepthUsd,
23143
+ borrowDepthUsd,
23144
+ lendDepthAmount,
23145
+ borrowDepthAmount
23146
+ };
23147
+ }
23148
+ var TermMaxApiSource = class {
23149
+ baseUrl;
23150
+ fetchImpl;
23151
+ constructor(baseUrl, fetchImpl = fetch) {
23152
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
23153
+ this.fetchImpl = (input, init) => fetchImpl.call(globalThis, input, init);
23154
+ }
23155
+ async getChainMarkets(chainId) {
23156
+ const url = `${this.baseUrl}/market/data?chainId=${chainId}`;
23157
+ let json;
23158
+ try {
23159
+ const res = await this.fetchImpl(url);
23160
+ if (!res.ok) {
23161
+ warn3(`market/data ${chainId} \u2192 HTTP ${res.status}`);
23162
+ return null;
23163
+ }
23164
+ json = await res.json();
23165
+ } catch (e) {
23166
+ warn3(`market/data ${chainId} fetch failed:`, e?.message ?? e);
23167
+ return null;
23168
+ }
23169
+ const data = json?.data ?? json;
23170
+ if (!data) return null;
23171
+ const assetDecimals = /* @__PURE__ */ new Map();
23172
+ for (const a of Array.isArray(data.assetConfigs) ? data.assetConfigs : []) {
23173
+ const addr2 = lower(a?.assetAddress);
23174
+ const dec = Number(a?.assetDecimals);
23175
+ if (addr2 && Number.isFinite(dec)) assetDecimals.set(addr2, dec);
23176
+ }
23177
+ const markets = [];
23178
+ for (const m of Array.isArray(data.markets) ? data.markets : []) {
23179
+ const parsed = parseMarket(m, assetDecimals);
23180
+ if (parsed && parsed.isEnabled && !parsed.isMatured) markets.push(parsed);
23181
+ }
23182
+ if (markets.length === 0) return [];
23183
+ const ordersByMarket = /* @__PURE__ */ new Map();
23184
+ for (const o of Array.isArray(data.orders) ? data.orders : []) {
23185
+ const parsed = parseOrder(o);
23186
+ if (!parsed) continue;
23187
+ const list = ordersByMarket.get(parsed.marketAddress);
23188
+ if (list) list.push(parsed);
23189
+ else ordersByMarket.set(parsed.marketAddress, [parsed]);
23190
+ }
23191
+ return markets.map((config) => {
23192
+ const orders = ordersByMarket.get(config.market) ?? [];
23193
+ return { config, top: reduceTop2(orders), orders };
23194
+ });
23195
+ }
23196
+ };
23197
+ function createTermMaxDataSource(chainId, fetchImpl = fetch) {
23198
+ return new TermMaxApiSource(termMaxApiBase(chainId), fetchImpl);
23199
+ }
23200
+
23201
+ // src/lending/public-data/termmax/fetchPublic.ts
23202
+ var LKG_TTL_SEC3 = 30 * 60;
23203
+ var lastGood3 = /* @__PURE__ */ new Map();
23204
+ var MARKET_CACHE_TTL_MS = 10 * 6e4;
23205
+ var marketCache = /* @__PURE__ */ new Map();
23206
+ var marketKey = (chainId, market) => `${chainId}:${market.toLowerCase()}`;
23207
+ function rememberMarkets(chainId, raw) {
23208
+ const at = Date.now();
23209
+ for (const { config } of raw) {
23210
+ marketCache.set(marketKey(chainId, config.market), { config, at });
23211
+ }
23212
+ }
23213
+ function getCachedTermMaxMarket(chainId, market) {
23214
+ const hit = marketCache.get(marketKey(chainId, market));
23215
+ if (!hit || Date.now() - hit.at > MARKET_CACHE_TTL_MS) return void 0;
23216
+ return hit.config;
23217
+ }
23218
+ function getCachedTermMaxMarkets(chainId) {
23219
+ const prefix = `${chainId}:`;
23220
+ const now = Date.now();
23221
+ const out = [];
23222
+ for (const [key, hit] of marketCache) {
23223
+ if (!key.startsWith(prefix)) continue;
23224
+ if (now - hit.at > MARKET_CACHE_TTL_MS) continue;
23225
+ out.push(hit.config);
23226
+ }
23227
+ return out;
23228
+ }
23229
+ async function fetchTermMaxMarkets(chainId, source = createTermMaxDataSource(chainId)) {
23230
+ if (!termMaxConfigByChain(chainId)) return [];
23231
+ const nowSec9 = Math.floor(Date.now() / 1e3);
23232
+ const fresh = await source.getChainMarkets(chainId).catch(() => null);
23233
+ if (fresh) {
23234
+ const live = fresh.filter((m) => m.config.maturity > nowSec9);
23235
+ lastGood3.set(chainId, { markets: live, at: nowSec9 });
23236
+ rememberMarkets(chainId, live);
23237
+ return live;
23238
+ }
23239
+ const cached = lastGood3.get(chainId);
23240
+ if (cached && nowSec9 - cached.at <= LKG_TTL_SEC3) {
23241
+ const live = cached.markets.filter((m) => m.config.maturity > nowSec9);
23242
+ rememberMarkets(chainId, live);
23243
+ return live;
23244
+ }
23245
+ return [];
23246
+ }
22853
23247
 
22854
23248
  // src/lending/public-data/teller/math.ts
22855
23249
  function tellerBpsToPercent(bps) {
@@ -22880,19 +23274,19 @@ function tellerPoolFromLenderKey(lender) {
22880
23274
  return body.length === 40 ? "0x" + body.toLowerCase() : void 0;
22881
23275
  }
22882
23276
  function currencyFor6(address, decimals, symbol, tokens) {
22883
- const lower = address.toLowerCase();
22884
- return tokens[lower] ?? { address: lower, symbol, name: symbol, decimals };
23277
+ const lower3 = address.toLowerCase();
23278
+ return tokens[lower3] ?? { address: lower3, symbol, name: symbol, decimals };
22885
23279
  }
22886
- function fmtDuration(sec) {
23280
+ function fmtDuration2(sec) {
22887
23281
  if (sec == null || sec <= 0) return "a short window";
22888
23282
  if (sec < 3600) return `${Math.round(sec / 60)} minute${sec < 120 ? "" : "s"}`;
22889
23283
  if (sec < 86400) return `${Math.round(sec / 3600)} hour${sec < 7200 ? "" : "s"}`;
22890
23284
  return `${Math.round(sec / 86400)} day${sec < 172800 ? "" : "s"}`;
22891
23285
  }
22892
23286
  function priceFor(address, chainId, tokens, prices) {
22893
- const lower = address.toLowerCase();
22894
- const token = tokens[lower];
22895
- const key = toOracleKey(token?.assetGroup) || toGenericPriceKey(lower, chainId);
23287
+ const lower3 = address.toLowerCase();
23288
+ const token = tokens[lower3];
23289
+ const key = toOracleKey(token?.assetGroup) || toGenericPriceKey(lower3, chainId);
22896
23290
  return prices[key] ?? 0;
22897
23291
  }
22898
23292
  function convertTellerMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
@@ -23049,7 +23443,7 @@ function convertTellerMarketsToResponse(raw, chainId, prices = {}, _additionalYi
23049
23443
  const originationFeeBps = marketFeeBps + protocolFeeBps;
23050
23444
  const originationFeePercent = originationFeeBps / 100;
23051
23445
  const graceSec = p.paymentDefaultDuration;
23052
- const graceHuman = fmtDuration(graceSec);
23446
+ const graceHuman = fmtDuration2(graceSec);
23053
23447
  const ltvPct = ltv > 0 ? Math.round(ltv * 100) : void 0;
23054
23448
  const lossX = ltv > 0 ? (1 / ltv).toFixed(1) : void 0;
23055
23449
  const implications = [];
@@ -23141,6 +23535,615 @@ function convertTellerMarketsToResponse(raw, chainId, prices = {}, _additionalYi
23141
23535
  return out;
23142
23536
  }
23143
23537
 
23538
+ // src/lending/public-data/termmax/math.ts
23539
+ var DECIMAL_BASE = 100000000n;
23540
+ var DAYS_IN_YEAR2 = 365n;
23541
+ var SECONDS_IN_DAY = 86400n;
23542
+ var MAX_FEE_RATIO = 20000000n;
23543
+ function daysToMaturity(maturity, nowSec9) {
23544
+ const remaining = BigInt(Math.trunc(maturity)) - BigInt(Math.trunc(nowSec9));
23545
+ if (remaining <= 0n) return 0n;
23546
+ return (remaining + SECONDS_IN_DAY - 1n) / SECONDS_IN_DAY;
23547
+ }
23548
+ function calcCutId(cuts, xtReserve) {
23549
+ let id = cuts.length;
23550
+ while (id > 0) {
23551
+ id--;
23552
+ if (xtReserve >= cuts[id].xtReserve) return id;
23553
+ }
23554
+ return cuts.length > 0 ? 0 : -1;
23555
+ }
23556
+ function intervalProps(netInterestFactor, days, cut, xtReserve) {
23557
+ if (days <= 0n) return null;
23558
+ const liqSquare = cut.liqSquare * days * netInterestFactor / (DAYS_IN_YEAR2 * DECIMAL_BASE);
23559
+ const vXtReserve = xtReserve + cut.offset;
23560
+ if (vXtReserve <= 0n) return null;
23561
+ return { liqSquare, vXtReserve, vFtReserve: liqSquare / vXtReserve };
23562
+ }
23563
+ function curveApr(cuts, virtualXtReserve, days) {
23564
+ if (cuts.length === 0 || days <= 0n) return 0n;
23565
+ const id = calcCutId(cuts, virtualXtReserve);
23566
+ if (id < 0) return 0n;
23567
+ const props = intervalProps(DECIMAL_BASE, days, cuts[id], virtualXtReserve);
23568
+ if (!props || props.vXtReserve === 0n) return 0n;
23569
+ return props.vFtReserve * DECIMAL_BASE * DAYS_IN_YEAR2 / (props.vXtReserve * days);
23570
+ }
23571
+ function ratioToNumber(v) {
23572
+ return Number(v) / Number(DECIMAL_BASE);
23573
+ }
23574
+ function ratioToPercent(v) {
23575
+ return Number(v) / Number(DECIMAL_BASE) * 100;
23576
+ }
23577
+ function curveAprNumber(cuts, virtualXtReserve, days) {
23578
+ return ratioToNumber(curveApr(cuts, virtualXtReserve, days));
23579
+ }
23580
+ function lendNif(fee) {
23581
+ const f = fee?.lendTakerFeeRatio ?? 0n;
23582
+ const nif = DECIMAL_BASE - (f > MAX_FEE_RATIO ? MAX_FEE_RATIO : f);
23583
+ return nif > 0n ? nif : DECIMAL_BASE;
23584
+ }
23585
+ function borrowNif(fee) {
23586
+ const f = fee?.borrowTakerFeeRatio ?? 0n;
23587
+ return DECIMAL_BASE + (f > MAX_FEE_RATIO ? MAX_FEE_RATIO : f);
23588
+ }
23589
+ function mintGtFeeRatio(fee, days) {
23590
+ if (!fee || days <= 0n) return 0n;
23591
+ const ratio = fee.mintGtFeeRatio ?? 0n;
23592
+ const ref = fee.mintGtFeeRef ?? 0n;
23593
+ const denom = DAYS_IN_YEAR2 * DECIMAL_BASE + ref * days;
23594
+ if (denom === 0n) return 0n;
23595
+ return days * ratio * ref / denom;
23596
+ }
23597
+ var TERMMAX_LIQUIDATION_PENALTY = 0.1;
23598
+ var TERMMAX_LIQUIDATOR_BONUS = 0.05;
23599
+ var TERMMAX_PARTIAL_LIQUIDATION_THRESHOLD_USD = 1e4;
23600
+ var TERMMAX_PARTIAL_CLOSE_FACTOR = 0.5;
23601
+ var TERMMAX_LIQUIDATION_WINDOW_SECS = 7200;
23602
+ function parseTermMaxLtv(v) {
23603
+ if (v === void 0 || v === null || v === "") return 0;
23604
+ try {
23605
+ return Number(BigInt(v)) / Number(DECIMAL_BASE);
23606
+ } catch {
23607
+ const n = Number(v);
23608
+ return Number.isFinite(n) ? n / Number(DECIMAL_BASE) : 0;
23609
+ }
23610
+ }
23611
+
23612
+ // src/lending/public-data/termmax/convertPublic.ts
23613
+ var nowSec4 = () => Math.floor(Date.now() / 1e3);
23614
+ function currencyFor7(address, decimals, tokens) {
23615
+ const lower3 = address.toLowerCase();
23616
+ return tokens[lower3] ?? {
23617
+ address: lower3,
23618
+ symbol: "",
23619
+ name: "",
23620
+ decimals
23621
+ };
23622
+ }
23623
+ function priceFor2(address, chainId, prices, tokens) {
23624
+ const asset = tokens[address];
23625
+ const key = toOracleKey(asset?.assetGroup) || toGenericPriceKey(address, chainId);
23626
+ return prices[key] ?? 0;
23627
+ }
23628
+ function convertTermMaxMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
23629
+ intrinsicYields: {},
23630
+ lenderRewards: {},
23631
+ loaded: true
23632
+ }, tokens = {}) {
23633
+ const out = {};
23634
+ const now = nowSec4();
23635
+ for (const { config, top, orders } of raw) {
23636
+ if (!config?.market || !config.debtToken || !config.collateral) continue;
23637
+ const m = termMaxLenderKey(config.market);
23638
+ const maturity = Number(config.maturity);
23639
+ const ttm = maturity - now;
23640
+ const matured = ttm <= 0;
23641
+ const days = daysToMaturity(maturity, now);
23642
+ const supplyAprPct = !matured ? (top?.bestLendApr ?? 0) * 100 : 0;
23643
+ const borrowAprPct = !matured ? (top?.bestBorrowApr ?? 0) * 100 : 0;
23644
+ const debtAddr = config.debtToken;
23645
+ const collAddr = config.collateral;
23646
+ priceFor2(debtAddr, chainId, prices, tokens);
23647
+ const collPrice = priceFor2(collAddr, chainId, prices, tokens);
23648
+ const supplyLiquidity = matured ? 0 : top?.lendDepthAmount ?? 0;
23649
+ const borrowLiquidity = matured ? 0 : top?.borrowDepthAmount ?? 0;
23650
+ const supplyLiquidityUSD = matured ? 0 : top?.lendDepthUsd ?? 0;
23651
+ const borrowLiquidityUSD = matured ? 0 : top?.borrowDepthUsd ?? 0;
23652
+ const maxLtv = parseTermMaxLtv(config.maxLtv);
23653
+ const liquidationLtv = parseTermMaxLtv(config.liquidationLtv);
23654
+ const closeFactor = borrowLiquidityUSD > TERMMAX_PARTIAL_LIQUIDATION_THRESHOLD_USD ? TERMMAX_PARTIAL_CLOSE_FACTOR : 1;
23655
+ const liquidationPenalty = config.liquidatable ? TERMMAX_LIQUIDATION_PENALTY : 0;
23656
+ const terms = borrowAprPct > 0 && !matured ? [
23657
+ {
23658
+ termId: maturity,
23659
+ durationSecs: Math.max(0, ttm),
23660
+ durationDays: ttm / 86400,
23661
+ apr: borrowAprPct
23662
+ }
23663
+ ] : void 0;
23664
+ const originationFeePercent = ratioToPercent(
23665
+ mintGtFeeRatio(config.feeConfig, days)
23666
+ );
23667
+ const entry = { data: {} };
23668
+ const loanUid = createMarketUid(chainId, m, debtAddr);
23669
+ entry.data[loanUid] = {
23670
+ marketUid: loanUid,
23671
+ name: "Loan " + (tokens[debtAddr]?.symbol ?? ""),
23672
+ poolId: debtAddr,
23673
+ underlying: debtAddr,
23674
+ asset: currencyFor7(debtAddr, config.debtDecimals, tokens),
23675
+ totalDeposits: supplyLiquidity,
23676
+ totalDebtStable: 0,
23677
+ totalDebt: 0,
23678
+ totalLiquidity: borrowLiquidity,
23679
+ borrowLiquidity,
23680
+ totalLiquidityUSD: borrowLiquidityUSD,
23681
+ borrowLiquidityUSD,
23682
+ totalDepositsUSD: supplyLiquidityUSD,
23683
+ totalDebtStableUSD: 0,
23684
+ totalDebtUSD: 0,
23685
+ // No utilization curve — price comes from per-maker curves, not a pool.
23686
+ utilization: 0,
23687
+ depositRate: supplyAprPct,
23688
+ variableBorrowRate: borrowAprPct,
23689
+ rateModel: "fixedTerm",
23690
+ // Fixed-rate: mirror onto stableBorrowRate so fixed-rate consumers pick it
23691
+ // up as a term product.
23692
+ stableBorrowRate: borrowAprPct,
23693
+ intrinsicYield: 0,
23694
+ rewards: void 0,
23695
+ decimals: config.debtDecimals,
23696
+ config: {
23697
+ 0: {
23698
+ category: 0,
23699
+ borrowCollateralFactor: 0,
23700
+ collateralFactor: 0,
23701
+ borrowFactor: 1,
23702
+ liquidationPenalty: 0,
23703
+ closeFactor,
23704
+ collateralDisabled: true,
23705
+ debtDisabled: false
23706
+ }
23707
+ },
23708
+ closeFactor,
23709
+ collateralActive: false,
23710
+ borrowingEnabled: !matured && borrowLiquidity > 0,
23711
+ depositsEnabled: !matured,
23712
+ hasStable: false,
23713
+ // Borrowing IS fixed-term (see `terms` + `fixedTerm`), but it is real
23714
+ // borrowing — do NOT set this, or borrowable-only filters hide the market.
23715
+ variableBorrowDisabled: false,
23716
+ isActive: true,
23717
+ isFrozen: false
23718
+ };
23719
+ const collUid = createMarketUid(chainId, m, collAddr);
23720
+ const collCapacityUSD = maxLtv > 0 ? borrowLiquidityUSD / maxLtv : borrowLiquidityUSD;
23721
+ const collCapacity = collPrice > 0 ? collCapacityUSD / collPrice : 0;
23722
+ entry.data[collUid] = {
23723
+ marketUid: collUid,
23724
+ name: "Collateral " + (tokens[collAddr]?.symbol ?? ""),
23725
+ poolId: collAddr,
23726
+ underlying: collAddr,
23727
+ asset: currencyFor7(collAddr, config.collateralDecimals, tokens),
23728
+ totalDeposits: collCapacity,
23729
+ totalDebtStable: 0,
23730
+ totalDebt: 0,
23731
+ totalLiquidity: collCapacity,
23732
+ borrowLiquidity: 0,
23733
+ totalLiquidityUSD: collCapacityUSD,
23734
+ borrowLiquidityUSD: 0,
23735
+ totalDepositsUSD: collCapacityUSD,
23736
+ totalDebtStableUSD: 0,
23737
+ totalDebtUSD: 0,
23738
+ utilization: 0,
23739
+ depositRate: 0,
23740
+ variableBorrowRate: 0,
23741
+ stableBorrowRate: 0,
23742
+ intrinsicYield: 0,
23743
+ rewards: void 0,
23744
+ decimals: config.collateralDecimals,
23745
+ config: {
23746
+ 0: {
23747
+ category: 0,
23748
+ borrowCollateralFactor: liquidationLtv,
23749
+ collateralFactor: maxLtv,
23750
+ borrowFactor: 1,
23751
+ liquidationPenalty,
23752
+ closeFactor,
23753
+ collateralDisabled: false,
23754
+ debtDisabled: true
23755
+ }
23756
+ },
23757
+ closeFactor,
23758
+ collateralActive: true,
23759
+ borrowingEnabled: false,
23760
+ depositsEnabled: !matured,
23761
+ hasStable: false,
23762
+ isActive: true,
23763
+ isFrozen: false
23764
+ };
23765
+ entry.params = {
23766
+ market: {
23767
+ lender: m,
23768
+ name: config.symbol,
23769
+ loanDecimals: config.debtDecimals,
23770
+ collateralDecimals: config.collateralDecimals,
23771
+ id: config.market,
23772
+ lltv: config.liquidationLtv,
23773
+ oracle: config.oracle ?? zeroAddress,
23774
+ irm: zeroAddress,
23775
+ collateralAddress: collAddr,
23776
+ loanAddress: debtAddr,
23777
+ terms,
23778
+ // TermMax-specific extras consumed by the calldata / worker-api
23779
+ // resolvers. FT is the lend position, GT the borrow sub-account.
23780
+ maturity: String(config.maturity),
23781
+ ft: config.ft,
23782
+ xt: config.xt,
23783
+ gt: config.gt,
23784
+ maxLtv: config.maxLtv,
23785
+ liquidationLtv: config.liquidationLtv,
23786
+ liquidatable: config.liquidatable,
23787
+ liquidationWindowSeconds: config.liquidationWindowSeconds,
23788
+ version: config.version,
23789
+ // Executable order set, best-first per side — what a builder quotes
23790
+ // against. Depth caps are hard: an order can refuse beyond them.
23791
+ orders: orders.map((o) => ({
23792
+ order: o.orderAddress,
23793
+ maker: o.makerAddress,
23794
+ makerIsVault: o.makerIsVault,
23795
+ lendApr: o.takerLendApr,
23796
+ borrowApr: o.takerBorrowApr,
23797
+ lendCapacityUsd: o.lendCapacityUsd,
23798
+ borrowCapacityUsd: o.borrowCapacityUsd,
23799
+ lendCapacityAmount: o.lendCapacityAmount,
23800
+ borrowCapacityAmount: o.borrowCapacityAmount
23801
+ })),
23802
+ fixedTerm: {
23803
+ model: "termmax",
23804
+ maturity,
23805
+ fees: {
23806
+ // % of principal, charged once when the GT is minted.
23807
+ originationFeePercent
23808
+ },
23809
+ // Exit early by buying discounted FT and handing it back at par — a
23810
+ // market price, not a penalty. Same as Midnight.
23811
+ earlyRepay: { kind: "none" },
23812
+ // The term is an aggregate of many per-maker order contracts; there is
23813
+ // no single provider at the market level.
23814
+ provider: { kind: "orderbook" }
23815
+ }
23816
+ }
23817
+ };
23818
+ entry.chainId = chainId;
23819
+ out[m] = entry;
23820
+ }
23821
+ return out;
23822
+ }
23823
+ var FIXED_MARKETS_URL = "https://www.inverse.finance/api/f2/fixed-markets";
23824
+ var DBR_URL = "https://www.inverse.finance/api/dbr";
23825
+ var INVERSE_PUBLIC_READ_ABI = [
23826
+ ...InverseMarketAbi,
23827
+ ...InverseOracleAbi,
23828
+ ...InverseDbrAbi,
23829
+ ...Erc20Abi
23830
+ ];
23831
+ var READS_PER_MARKET2 = 4;
23832
+ var fetchJson = async (url, timeoutMs = 6e3) => {
23833
+ const res = await fetch(url, {
23834
+ headers: { accept: "application/json" },
23835
+ signal: AbortSignal.timeout(timeoutMs)
23836
+ });
23837
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
23838
+ return res.json();
23839
+ };
23840
+ var fetchDbrPriceDola = async (snapshot) => {
23841
+ try {
23842
+ const d = await fetchJson(DBR_URL);
23843
+ const p = Number(d?.priceDola);
23844
+ if (Number.isFinite(p) && p > 0) return p;
23845
+ } catch {
23846
+ }
23847
+ const snap = Number(snapshot);
23848
+ return Number.isFinite(snap) && snap > 0 ? snap : null;
23849
+ };
23850
+ async function fetchInverseMarkets(lender, chainId) {
23851
+ const config = inverseConfigFor(lender, chainId);
23852
+ const chainData = inverseChainData(lender, chainId);
23853
+ const markets = chainData?.markets ?? [];
23854
+ const empty = {
23855
+ lender,
23856
+ config,
23857
+ chainData,
23858
+ dbrPriceDola: null,
23859
+ replenishmentPriceBps: null,
23860
+ markets: [],
23861
+ source: "none"
23862
+ };
23863
+ if (!config || markets.length === 0) return empty;
23864
+ const dbrPricePromise = fetchDbrPriceDola(config.dbrPriceDolaSnapshot);
23865
+ try {
23866
+ const api = await fetchJson(FIXED_MARKETS_URL);
23867
+ const byAddr = {};
23868
+ for (const m of api?.markets ?? []) {
23869
+ if (m?.address) byAddr[String(m.address).toLowerCase()] = m;
23870
+ }
23871
+ if (Object.keys(byAddr).length > 0) {
23872
+ const rows = markets.map((market) => {
23873
+ const m = byAddr[market.address.toLowerCase()];
23874
+ const num9 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
23875
+ return {
23876
+ market,
23877
+ totalDebt: num9(m?.totalDebt),
23878
+ dolaLiquidity: num9(m?.dolaLiquidity),
23879
+ leftToBorrow: num9(m?.leftToBorrow),
23880
+ price: num9(m?.price),
23881
+ borrowPaused: typeof m?.borrowPaused === "boolean" ? m.borrowPaused : null,
23882
+ dailyBorrows: num9(m?.dailyBorrows)
23883
+ };
23884
+ });
23885
+ return {
23886
+ lender,
23887
+ config,
23888
+ chainData,
23889
+ dbrPriceDola: await dbrPricePromise,
23890
+ replenishmentPriceBps: num(api, "replenishmentPriceBps"),
23891
+ markets: rows,
23892
+ source: "api"
23893
+ };
23894
+ }
23895
+ } catch {
23896
+ }
23897
+ const calls = [
23898
+ { address: config.dbr, name: "replenishmentPriceBps", params: [] },
23899
+ ...markets.flatMap((m) => [
23900
+ { address: m.address, name: "totalDebt", params: [] },
23901
+ { address: m.address, name: "borrowPaused", params: [] },
23902
+ { address: config.dola, name: "balanceOf", params: [m.address] },
23903
+ {
23904
+ address: config.oracle,
23905
+ name: "viewPrice",
23906
+ params: [m.collToken, BigInt(m.collateralFactorBps)]
23907
+ }
23908
+ ])
23909
+ ];
23910
+ try {
23911
+ const results = await multicallRetryUniversal({
23912
+ chain: chainId,
23913
+ calls,
23914
+ abi: INVERSE_PUBLIC_READ_ABI,
23915
+ allowFailure: true
23916
+ });
23917
+ const bigAt = (i) => {
23918
+ const r = results[i];
23919
+ if (typeof r === "bigint") return r;
23920
+ if (typeof r === "number") return BigInt(r);
23921
+ return null;
23922
+ };
23923
+ const debtDecimals = config.debtDecimals ?? 18;
23924
+ const rows = markets.map((market, i) => {
23925
+ const base = 1 + i * READS_PER_MARKET2;
23926
+ const totalDebt = bigAt(base);
23927
+ const paused = results[base + 1];
23928
+ const liq = bigAt(base + 2);
23929
+ const price2 = bigAt(base + 3);
23930
+ return {
23931
+ market,
23932
+ totalDebt: totalDebt !== null ? Number(totalDebt) / 10 ** debtDecimals : null,
23933
+ dolaLiquidity: liq !== null ? Number(liq) / 10 ** debtDecimals : null,
23934
+ // dailyBorrows lives on the BorrowController (day-bucketed
23935
+ // mapping) — the fallback conservatively caps by liquidity only.
23936
+ leftToBorrow: null,
23937
+ // viewPrice scales so that price * balance / 1e18 is USD-ish:
23938
+ // 10^(36 − collDecimals) per unit — normalize to USD per token.
23939
+ price: price2 !== null ? Number(price2) / 10 ** (36 - market.collDecimals) : null,
23940
+ borrowPaused: typeof paused === "boolean" ? paused : null,
23941
+ dailyBorrows: null
23942
+ };
23943
+ });
23944
+ return {
23945
+ lender,
23946
+ config,
23947
+ chainData,
23948
+ dbrPriceDola: await dbrPricePromise,
23949
+ replenishmentPriceBps: bigAt(0) !== null ? Number(bigAt(0)) : null,
23950
+ markets: rows,
23951
+ source: "chain"
23952
+ };
23953
+ } catch {
23954
+ return { ...empty, dbrPriceDola: await dbrPricePromise };
23955
+ }
23956
+ }
23957
+ function num(api, key) {
23958
+ const v = api?.[key];
23959
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
23960
+ }
23961
+
23962
+ // src/lending/public-data/inverse/convertPublic.ts
23963
+ function inverseLenderKey(lender, market) {
23964
+ return `${lender}_${market.replace(/^0x/i, "").toUpperCase()}`;
23965
+ }
23966
+ function inverseKeyParts(key) {
23967
+ if (!key.startsWith("INVERSE_")) return void 0;
23968
+ const suffix = key.slice("INVERSE_".length);
23969
+ if (!/^[0-9A-F]{40}$/.test(suffix)) return void 0;
23970
+ return { lender: "INVERSE", market: "0x" + suffix.toLowerCase() };
23971
+ }
23972
+ function currencyFor8(address, decimals, symbol, tokens) {
23973
+ const lower3 = address.toLowerCase();
23974
+ return tokens[lower3] ?? { address: lower3, symbol, name: symbol, decimals };
23975
+ }
23976
+ function convertInverseMarketsToResponse(raw, chainId, prices = {}, _additionalYields = {
23977
+ intrinsicYields: {},
23978
+ lenderRewards: {},
23979
+ loaded: true
23980
+ }, tokens = {}) {
23981
+ const out = {};
23982
+ const cfg = raw?.config;
23983
+ const chainData = raw?.chainData;
23984
+ if (!cfg || !chainData) return out;
23985
+ const dolaAddr = cfg.dola.toLowerCase();
23986
+ const debtDecimals = cfg.debtDecimals ?? 18;
23987
+ const dolaToken = tokens[dolaAddr];
23988
+ const dolaPriceKey = toOracleKey(dolaToken?.assetGroup) || toGenericPriceKey(dolaAddr, chainId);
23989
+ const dolaPrice = prices[dolaPriceKey] || 1;
23990
+ const borrowAprPct = raw.dbrPriceDola !== null ? raw.dbrPriceDola * 100 : 0;
23991
+ for (const m of raw.markets ?? []) {
23992
+ const market = m.market;
23993
+ const lenderKey = inverseLenderKey(raw.lender, market.address);
23994
+ const collAddr = market.collToken.toLowerCase();
23995
+ const collDecimals = market.collDecimals;
23996
+ const collToken = tokens[collAddr];
23997
+ const collSymbol = collToken?.symbol ?? market.name ?? "COLL";
23998
+ const marketName = `DOLA / ${market.name ?? collSymbol}`;
23999
+ const collPriceKey = toOracleKey(collToken?.assetGroup) || toGenericPriceKey(collAddr, chainId);
24000
+ const collPrice = m.price ?? prices[collPriceKey] ?? 0;
24001
+ const totalDebt = m.totalDebt ?? 0;
24002
+ const paused = m.borrowPaused ?? !!market.borrowPaused;
24003
+ const ltv = Number(market.collateralFactorBps) / 1e4;
24004
+ const liqPenalty = Number(market.liquidationIncentiveBps) / 1e4;
24005
+ const closeFactor = Number(market.liquidationFactorBps) / 1e4 || 1;
24006
+ const collateralTotal = 0;
24007
+ let borrowLiquidity = m.leftToBorrow ?? m.dolaLiquidity ?? 0;
24008
+ if (paused) borrowLiquidity = 0;
24009
+ const entry = { data: {} };
24010
+ const collUid = createMarketUid(chainId, lenderKey, collAddr);
24011
+ entry.data[collUid] = {
24012
+ marketUid: collUid,
24013
+ name: "Collateral " + collSymbol,
24014
+ poolId: market.address.toLowerCase(),
24015
+ underlying: collAddr,
24016
+ asset: currencyFor8(collAddr, collDecimals, collSymbol, tokens),
24017
+ totalDeposits: collateralTotal,
24018
+ totalDebtStable: 0,
24019
+ totalDebt: 0,
24020
+ totalLiquidity: collateralTotal,
24021
+ borrowLiquidity: 0,
24022
+ totalLiquidityUSD: collateralTotal * collPrice,
24023
+ borrowLiquidityUSD: 0,
24024
+ totalDepositsUSD: collateralTotal * collPrice,
24025
+ totalDebtStableUSD: 0,
24026
+ totalDebtUSD: 0,
24027
+ utilization: 0,
24028
+ depositRate: 0,
24029
+ variableBorrowRate: 0,
24030
+ stableBorrowRate: 0,
24031
+ intrinsicYield: _additionalYields?.intrinsicYields?.[collToken?.assetGroup] ?? 0,
24032
+ rewards: void 0,
24033
+ decimals: collDecimals,
24034
+ config: {
24035
+ 0: {
24036
+ category: 0,
24037
+ borrowCollateralFactor: ltv,
24038
+ collateralFactor: ltv,
24039
+ borrowFactor: 1,
24040
+ liquidationPenalty: liqPenalty,
24041
+ closeFactor,
24042
+ collateralDisabled: false,
24043
+ debtDisabled: true
24044
+ }
24045
+ },
24046
+ closeFactor,
24047
+ collateralActive: true,
24048
+ borrowingEnabled: false,
24049
+ depositsEnabled: true,
24050
+ hasStable: false,
24051
+ isActive: true,
24052
+ isFrozen: false
24053
+ };
24054
+ const loanUid = createMarketUid(chainId, lenderKey, dolaAddr);
24055
+ entry.data[loanUid] = {
24056
+ marketUid: loanUid,
24057
+ name: "DOLA",
24058
+ poolId: market.address.toLowerCase(),
24059
+ underlying: dolaAddr,
24060
+ asset: currencyFor8(dolaAddr, debtDecimals, "DOLA", tokens),
24061
+ totalDeposits: 0,
24062
+ totalDebtStable: 0,
24063
+ totalDebt,
24064
+ totalLiquidity: borrowLiquidity,
24065
+ borrowLiquidity,
24066
+ totalLiquidityUSD: borrowLiquidity * dolaPrice,
24067
+ borrowLiquidityUSD: borrowLiquidity * dolaPrice,
24068
+ totalDepositsUSD: 0,
24069
+ totalDebtStableUSD: 0,
24070
+ totalDebtUSD: totalDebt * dolaPrice,
24071
+ utilization: 0,
24072
+ depositRate: 0,
24073
+ // The DBR price IS the fixed borrow APR (percent). Debt principal
24074
+ // is static — interest burns the user's DBR balance instead.
24075
+ variableBorrowRate: borrowAprPct,
24076
+ stableBorrowRate: 0,
24077
+ rateModel: "dbr",
24078
+ intrinsicYield: 0,
24079
+ rewards: void 0,
24080
+ decimals: debtDecimals,
24081
+ config: {
24082
+ 0: {
24083
+ category: 0,
24084
+ borrowCollateralFactor: 0,
24085
+ collateralFactor: 0,
24086
+ borrowFactor: 1,
24087
+ liquidationPenalty: liqPenalty,
24088
+ closeFactor,
24089
+ collateralDisabled: true,
24090
+ debtDisabled: paused
24091
+ }
24092
+ },
24093
+ closeFactor,
24094
+ collateralActive: false,
24095
+ borrowingEnabled: !paused,
24096
+ depositsEnabled: false,
24097
+ hasStable: false,
24098
+ variableBorrowDisabled: paused,
24099
+ isActive: true,
24100
+ isFrozen: false
24101
+ };
24102
+ entry.params = {
24103
+ market: {
24104
+ lender: lenderKey,
24105
+ name: marketName,
24106
+ loanDecimals: debtDecimals,
24107
+ collateralDecimals: collDecimals,
24108
+ // The Market contract doubles as the market id.
24109
+ id: market.address.toLowerCase(),
24110
+ lltv: String(ltv),
24111
+ oracle: cfg.oracle,
24112
+ irm: zeroAddress,
24113
+ collateralAddress: collAddr,
24114
+ loanAddress: dolaAddr,
24115
+ // --- FiRM descriptor (metadata + live snapshot; consumed by
24116
+ // calldata builders + worker-api resolvers) ---
24117
+ inverse: {
24118
+ escrowImplementation: market.escrowImplementation,
24119
+ /** DOLA units, human numbers as strings. */
24120
+ minDebt: market.minDebt,
24121
+ dailyLimit: market.dailyLimit,
24122
+ dailyBorrows: m.dailyBorrows !== null ? String(m.dailyBorrows) : void 0,
24123
+ dolaLiquidity: m.dolaLiquidity !== null ? String(m.dolaLiquidity) : void 0,
24124
+ leftToBorrow: m.leftToBorrow !== null ? String(m.leftToBorrow) : void 0,
24125
+ liquidationFactorBps: market.liquidationFactorBps,
24126
+ /** Fixed borrow APR as a DECIMAL (DBR price in DOLA). */
24127
+ dbrPriceDola: raw.dbrPriceDola !== null ? String(raw.dbrPriceDola) : void 0,
24128
+ /** Force-replenish penalty (5475 = 54.75% APR on missed DBR). */
24129
+ replenishmentPriceBps: raw.replenishmentPriceBps !== null ? String(raw.replenishmentPriceBps) : void 0,
24130
+ borrowPaused: paused,
24131
+ addresses: {
24132
+ market: market.address,
24133
+ dola: cfg.dola,
24134
+ dbr: cfg.dbr,
24135
+ oracle: cfg.oracle,
24136
+ borrowController: cfg.borrowController
24137
+ }
24138
+ }
24139
+ }
24140
+ };
24141
+ entry.chainId = chainId;
24142
+ out[lenderKey] = entry;
24143
+ }
24144
+ return out;
24145
+ }
24146
+
23144
24147
  // src/lending/public-data/silo-v2/fetchPublic.ts
23145
24148
  var BASE_URL2 = "https://api-v3.silo.finance";
23146
24149
  var SILO_API_SUPPORTED_CHAIN_IDS = /* @__PURE__ */ new Set([
@@ -23737,7 +24740,7 @@ function convertDolomiteSubgraphMarkets(raw, chainId, prices, additionalYields,
23737
24740
  }
23738
24741
  return { data: result, chainId };
23739
24742
  }
23740
- var warn3 = (...args) => {
24743
+ var warn4 = (...args) => {
23741
24744
  };
23742
24745
  async function getLenderDataFromApi(lender, chainId, prices, additionalYields, includeUnlisted = false) {
23743
24746
  if (isMorphoType(lender))
@@ -23748,6 +24751,8 @@ async function getLenderDataFromApi(lender, chainId, prices, additionalYields, i
23748
24751
  if (isLiquityFamily(lender)) return await fetchLiquityMarkets(lender, chainId);
23749
24752
  if (isRiver(lender)) return await fetchRiverMarkets(lender, chainId);
23750
24753
  if (isTeller(lender)) return await fetchTellerMarkets(chainId);
24754
+ if (isInverse(lender)) return await fetchInverseMarkets(lender, chainId);
24755
+ if (isTermMax(lender)) return await fetchTermMaxMarkets(chainId);
23751
24756
  return {};
23752
24757
  }
23753
24758
  function convertLenderDataFromApi(lender, chainId, data, prices, additionalYields, list = {}) {
@@ -23801,6 +24806,22 @@ function convertLenderDataFromApi(lender, chainId, data, prices, additionalYield
23801
24806
  additionalYields,
23802
24807
  list
23803
24808
  );
24809
+ if (isInverse(lender))
24810
+ return convertInverseMarketsToResponse(
24811
+ data,
24812
+ chainId,
24813
+ prices,
24814
+ additionalYields,
24815
+ list
24816
+ );
24817
+ if (isTermMax(lender))
24818
+ return convertTermMaxMarketsToResponse(
24819
+ data,
24820
+ chainId,
24821
+ prices,
24822
+ additionalYields,
24823
+ list
24824
+ );
23804
24825
  return {};
23805
24826
  }
23806
24827
  var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYields, tokenList = async () => {
@@ -23841,7 +24862,7 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23841
24862
  const listResult = settled[0];
23842
24863
  const list = listResult.status === "fulfilled" ? listResult.value : {};
23843
24864
  if (listResult.status === "rejected") {
23844
- warn3(
24865
+ warn4(
23845
24866
  `[lending] tokenList fetch failed on chain ${chainId}:`,
23846
24867
  listResult.reason
23847
24868
  );
@@ -23863,13 +24884,13 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23863
24884
  if (converted[lk]) lenderData[lk] = converted[lk];
23864
24885
  }
23865
24886
  } catch (e) {
23866
- warn3(
24887
+ warn4(
23867
24888
  `[lending] Silo v2 API convert failed on chain ${chainId}:`,
23868
24889
  e?.message ?? e
23869
24890
  );
23870
24891
  }
23871
24892
  } else {
23872
- warn3(
24893
+ warn4(
23873
24894
  `[lending] Silo v2 API fetch failed on chain ${chainId}:`,
23874
24895
  siloV2Result.reason?.message ?? siloV2Result.reason
23875
24896
  );
@@ -23891,13 +24912,13 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23891
24912
  if (converted[lk]) lenderData[lk] = converted[lk];
23892
24913
  }
23893
24914
  } catch (e) {
23894
- warn3(
24915
+ warn4(
23895
24916
  `[lending] Silo v3 API convert failed on chain ${chainId}:`,
23896
24917
  e?.message ?? e
23897
24918
  );
23898
24919
  }
23899
24920
  } else {
23900
- warn3(
24921
+ warn4(
23901
24922
  `[lending] Silo v3 API fetch failed on chain ${chainId}:`,
23902
24923
  siloV3Result.reason?.message ?? siloV3Result.reason
23903
24924
  );
@@ -23907,7 +24928,7 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23907
24928
  try {
23908
24929
  const result = settled[i + 3];
23909
24930
  if (result.status === "rejected") {
23910
- warn3(
24931
+ warn4(
23911
24932
  `[lending] API fetch failed for ${otherLenders[i]} on chain ${chainId}:`,
23912
24933
  result.reason?.message ?? result.reason
23913
24934
  );
@@ -23951,13 +24972,13 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23951
24972
  );
23952
24973
  for (const lk of dolomiteLenders) lenderData[lk] = converted;
23953
24974
  } catch (e) {
23954
- warn3(
24975
+ warn4(
23955
24976
  `[lending] Dolomite subgraph convert failed on chain ${chainId}:`,
23956
24977
  e?.message ?? e
23957
24978
  );
23958
24979
  }
23959
24980
  } else if (dolomiteResult.status === "rejected") {
23960
- warn3(
24981
+ warn4(
23961
24982
  `[lending] Dolomite subgraph fetch failed on chain ${chainId}:`,
23962
24983
  dolomiteResult.reason?.message ?? dolomiteResult.reason
23963
24984
  );
@@ -23965,7 +24986,7 @@ var getLenderPublicDataViaApi = async (chainId, lenders, prices, additionalYield
23965
24986
  }
23966
24987
  return lenderData;
23967
24988
  };
23968
- var warn4 = (...args) => {
24989
+ var warn5 = (...args) => {
23969
24990
  };
23970
24991
  function lenderApiOnly(lender, chainId) {
23971
24992
  if (lender === Lender.MORPHO_BLUE) {
@@ -24027,7 +25048,7 @@ var getLenderPublicDataAll = async (chainId, lenders, prices, additionalYields,
24027
25048
  includeUnlistedMorphoMarkets
24028
25049
  );
24029
25050
  } catch (e) {
24030
- warn4(
25051
+ warn5(
24031
25052
  `[lending] API fetch failed for chain ${chainId}:`,
24032
25053
  e?.message ?? e
24033
25054
  );
@@ -24050,7 +25071,7 @@ var getLenderPublicDataAll = async (chainId, lenders, prices, additionalYields,
24050
25071
  tokenList
24051
25072
  );
24052
25073
  } catch (e) {
24053
- warn4(
25074
+ warn5(
24054
25075
  `[lending] on-chain fetch failed for chain ${chainId}:`,
24055
25076
  e?.message ?? e
24056
25077
  );
@@ -24651,8 +25672,8 @@ function getSubAccountAddress(owner, index) {
24651
25672
  const suffix = newLastByte.toString(16).padStart(2, "0");
24652
25673
  return (prefix + suffix).toLowerCase();
24653
25674
  }
24654
- function getSubAccountIndex(addr, owner) {
24655
- const addrLastByte = parseInt(addr.slice(40), 16);
25675
+ function getSubAccountIndex(addr2, owner) {
25676
+ const addrLastByte = parseInt(addr2.slice(40), 16);
24656
25677
  if (!owner) return addrLastByte;
24657
25678
  const ownerLastByte = parseInt(owner.slice(40), 16);
24658
25679
  return (addrLastByte ^ ownerLastByte) & 255;
@@ -25151,6 +26172,46 @@ var buildRiverUserCall = (chainId, lender, account) => {
25151
26172
  });
25152
26173
  return calls;
25153
26174
  };
26175
+ var INVERSE_CALLS_PER_MARKET = 4;
26176
+ var INVERSE_TAIL_CALLS = 3;
26177
+ var proxyInitCode = (impl) => concat([
26178
+ "0x3d602d80600a3d3981f3363d3d373d3d3d363d73",
26179
+ impl,
26180
+ "0x5af43d82803e903d91602b57fd5bf3"
26181
+ ]);
26182
+ function predictInverseEscrow(market, escrowImplementation, user) {
26183
+ return getContractAddress({
26184
+ opcode: "CREATE2",
26185
+ from: market,
26186
+ salt: pad(user, { size: 32 }),
26187
+ bytecodeHash: keccak256(proxyInitCode(escrowImplementation))
26188
+ });
26189
+ }
26190
+ var buildInverseUserCall = (chainId, lender, account) => {
26191
+ const cfg = inverseConfigFor(lender, chainId);
26192
+ const markets = inverseChainData(lender, chainId)?.markets ?? [];
26193
+ if (!cfg || markets.length === 0) return [];
26194
+ const calls = markets.flatMap((m) => [
26195
+ {
26196
+ address: predictInverseEscrow(
26197
+ m.address,
26198
+ m.escrowImplementation,
26199
+ account
26200
+ ),
26201
+ name: "balance",
26202
+ params: []
26203
+ },
26204
+ { address: m.address, name: "debts", params: [account] },
26205
+ { address: m.address, name: "getCreditLimit", params: [account] },
26206
+ { address: m.address, name: "getWithdrawalLimit", params: [account] }
26207
+ ]);
26208
+ calls.push(
26209
+ { address: cfg.dbr, name: "balanceOf", params: [account] },
26210
+ { address: cfg.dbr, name: "deficitOf", params: [account] },
26211
+ { address: cfg.dbr, name: "signedBalanceOf", params: [account] }
26212
+ );
26213
+ return calls;
26214
+ };
25154
26215
  var TELLER_CALLS_PER_BID = 4;
25155
26216
  var CACHE_TTL_MS2 = 5 * 6e4;
25156
26217
  var discoveryCache2 = /* @__PURE__ */ new Map();
@@ -25160,7 +26221,7 @@ var getCachedTellerBids = (chainId, account) => {
25160
26221
  if (!hit || Date.now() - hit.at > CACHE_TTL_MS2) return void 0;
25161
26222
  return hit;
25162
26223
  };
25163
- var nowSec4 = () => Math.floor(Date.now() / 1e3);
26224
+ var nowSec5 = () => Math.floor(Date.now() / 1e3);
25164
26225
  var toBigints = (arr) => {
25165
26226
  if (!Array.isArray(arr)) return [];
25166
26227
  const out = [];
@@ -25226,7 +26287,7 @@ var buildTellerUserCall = async (chainId, _lender, account) => {
25226
26287
  });
25227
26288
  discoveryCache2.set(cacheKey2(chainId, account), { bids: kept, at: Date.now() });
25228
26289
  if (kept.length === 0) return [];
25229
- const ts = nowSec4();
26290
+ const ts = nowSec5();
25230
26291
  const calls = [];
25231
26292
  for (const b of kept) {
25232
26293
  calls.push({ address: proto.tellerV2, name: "bids", params: [b.bidId] });
@@ -25248,6 +26309,40 @@ var buildTellerUserCall = async (chainId, _lender, account) => {
25248
26309
  }
25249
26310
  return calls;
25250
26311
  };
26312
+ var TERMMAX_CALLS_PER_ACCOUNT = 1;
26313
+ var CACHE_TTL_MS3 = 5 * 6e4;
26314
+ var discoveryCache3 = /* @__PURE__ */ new Map();
26315
+ var cacheKey3 = (chainId, account) => `${chainId}:${account.toLowerCase()}`;
26316
+ var getCachedTermMaxDiscovery = (chainId, account) => {
26317
+ const hit = discoveryCache3.get(cacheKey3(chainId, account));
26318
+ if (!hit || Date.now() - hit.at > CACHE_TTL_MS3) return void 0;
26319
+ return hit;
26320
+ };
26321
+ var buildTermMaxUserCall = async (chainId, _lender, account) => {
26322
+ const proto = termMaxConfigByChain(chainId);
26323
+ if (!proto?.viewer) return [];
26324
+ let markets = getCachedTermMaxMarkets(chainId);
26325
+ if (markets.length === 0) {
26326
+ try {
26327
+ markets = (await fetchTermMaxMarkets(chainId)).map((m) => m.config);
26328
+ } catch {
26329
+ return [];
26330
+ }
26331
+ }
26332
+ if (markets.length === 0) {
26333
+ discoveryCache3.set(cacheKey3(chainId, account), { markets: [], at: Date.now() });
26334
+ return [];
26335
+ }
26336
+ markets = [...markets].sort((a, b) => a.market.localeCompare(b.market));
26337
+ discoveryCache3.set(cacheKey3(chainId, account), { markets, at: Date.now() });
26338
+ return [
26339
+ {
26340
+ address: proto.viewer,
26341
+ name: "getPositionDetails",
26342
+ params: [markets.map((m) => m.market), account]
26343
+ }
26344
+ ];
26345
+ };
25251
26346
 
25252
26347
  // src/lending/user-data/fetch-balances/prepare.ts
25253
26348
  async function buildUserCall(chainId, lender, account, params, getClient) {
@@ -25270,6 +26365,8 @@ async function buildUserCall(chainId, lender, account, params, getClient) {
25270
26365
  return buildLiquityUserCall(chainId, lender, account);
25271
26366
  if (isRiver(lender)) return buildRiverUserCall(chainId, lender, account);
25272
26367
  if (isTeller(lender)) return buildTellerUserCall(chainId, lender, account);
26368
+ if (isTermMax(lender)) return buildTermMaxUserCall(chainId, lender, account);
26369
+ if (isInverse(lender)) return buildInverseUserCall(chainId, lender, account);
25273
26370
  if (isCompoundV3Type(lender))
25274
26371
  return buildCompoundV3UserCall(chainId, lender, account);
25275
26372
  if (isEulerType(lender))
@@ -25297,10 +26394,11 @@ function organizeUserQueries(queries) {
25297
26394
  const liquity = queries.filter((q) => isLiquityFamily(q.lender));
25298
26395
  const river = queries.filter((q) => isRiver(q.lender));
25299
26396
  const teller = queries.filter((q) => isTeller(q.lender));
25300
- if (morphos.length === 0 && gearbox.length === 0 && midnight.length === 0 && term.length === 0 && exactly.length === 0 && liquity.length === 0 && river.length === 0 && teller.length === 0)
26397
+ const termMax = queries.filter((q) => isTermMax(q.lender));
26398
+ if (morphos.length === 0 && gearbox.length === 0 && midnight.length === 0 && term.length === 0 && exactly.length === 0 && liquity.length === 0 && river.length === 0 && teller.length === 0 && termMax.length === 0)
25301
26399
  return queries;
25302
26400
  const others = queries.filter(
25303
- (q) => !isMorphoType(q.lender) && !isGearboxV3(q.lender) && !isMidnight(q.lender) && !isTerm(q.lender) && !isExactly(q.lender) && !isLiquityFamily(q.lender) && !isRiver(q.lender) && !isTeller(q.lender)
26401
+ (q) => !isMorphoType(q.lender) && !isGearboxV3(q.lender) && !isMidnight(q.lender) && !isTerm(q.lender) && !isExactly(q.lender) && !isLiquityFamily(q.lender) && !isRiver(q.lender) && !isTeller(q.lender) && !isTermMax(q.lender)
25304
26402
  );
25305
26403
  const morphoBlue = morphos.filter((q) => q.lender.startsWith("MORPHO_BLUE"));
25306
26404
  const moolah = morphos.filter((q) => q.lender.startsWith("LISTA_DAO"));
@@ -25369,6 +26467,14 @@ function organizeUserQueries(queries) {
25369
26467
  assets: void 0
25370
26468
  });
25371
26469
  }
26470
+ if (termMax.length > 0) {
26471
+ result.push({
26472
+ lender: Lender.TERMMAX,
26473
+ account: termMax[0].account,
26474
+ params: termMax.map((p) => p.lender),
26475
+ assets: void 0
26476
+ });
26477
+ }
25372
26478
  if (liquity.length > 0) {
25373
26479
  for (const base of LIQUITY_FAMILY_LENDERS) {
25374
26480
  const members = liquity.filter((q) => q.lender.startsWith(base));
@@ -27168,7 +28274,7 @@ function toBigInt7(v) {
27168
28274
  }
27169
28275
  }
27170
28276
  var FLUID_EEE_LOWER2 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
27171
- var normalizeUnderlying2 = (addr) => addr === FLUID_EEE_LOWER2 ? zeroAddress : addr;
28277
+ var normalizeUnderlying2 = (addr2) => addr2 === FLUID_EEE_LOWER2 ? zeroAddress : addr2;
27172
28278
  function toBigInt8(v) {
27173
28279
  if (v === void 0 || v === null || v === "0x") return 0n;
27174
28280
  if (typeof v === "bigint") return v;
@@ -27569,8 +28675,8 @@ var WETH_BY_CHAIN = {
27569
28675
  // populated by the meta's native handling; kept as a hook. Default: identity.
27570
28676
  };
27571
28677
  function normalizeUnderlying3(token) {
27572
- const lower = token.toLowerCase();
27573
- return Object.values(WETH_BY_CHAIN).includes(lower) ? zeroAddress : lower;
28678
+ const lower3 = token.toLowerCase();
28679
+ return Object.values(WETH_BY_CHAIN).includes(lower3) ? zeroAddress : lower3;
27574
28680
  }
27575
28681
  function toBigInt10(v) {
27576
28682
  if (v === void 0 || v === null || v === "0x") return 0n;
@@ -27835,7 +28941,7 @@ var getTermUserDataConverter = (_lender, chainId, account, meta) => {
27835
28941
  totalCalls
27836
28942
  ];
27837
28943
  };
27838
- var nowSec5 = () => Math.floor(Date.now() / 1e3);
28944
+ var nowSec6 = () => Math.floor(Date.now() / 1e3);
27839
28945
  function sumPreview(positions) {
27840
28946
  return positions.reduce((acc, p) => acc + p.previewValue, 0n);
27841
28947
  }
@@ -27857,7 +28963,7 @@ var getExactlyUserDataConverter = (_lender, chainId, account, meta) => {
27857
28963
  const res = data[0];
27858
28964
  if (!res || res === "0x" || !Array.isArray(res)) return void 0;
27859
28965
  const markets = res;
27860
- const now = nowSec5();
28966
+ const now = nowSec6();
27861
28967
  const out = {};
27862
28968
  for (const m of markets) {
27863
28969
  const lenderKey = exactlyLenderKey(m.market);
@@ -28025,7 +29131,7 @@ var getLiquityUserDataConverter = (lender, chainId, account, meta) => {
28025
29131
  branches.forEach((branch, bi) => {
28026
29132
  const troves = discovery.perBranch[bi] ?? [];
28027
29133
  const callCount = liquityBranchCallCount(branch, troves.length);
28028
- const slice = data.slice(cursor, cursor + callCount);
29134
+ const slice2 = data.slice(cursor, cursor + callCount);
28029
29135
  cursor += callCount;
28030
29136
  const lenderKey = liquityLenderKey(lender, chainId, branch.collIndex);
28031
29137
  const metaMap = meta?.[lenderKey];
@@ -28046,8 +29152,8 @@ var getLiquityUserDataConverter = (lender, chainId, account, meta) => {
28046
29152
  const modes = {};
28047
29153
  const hist = {};
28048
29154
  troves.forEach((t, ti) => {
28049
- const troveData = slice[ti * 2];
28050
- const ownerRaw = slice[ti * 2 + 1];
29155
+ const troveData = slice2[ti * 2];
29156
+ const ownerRaw = slice2[ti * 2 + 1];
28051
29157
  const owner = typeof ownerRaw === "string" ? ownerRaw.toLowerCase() : void 0;
28052
29158
  if (owner !== accountLower) return;
28053
29159
  if (!troveData || troveData === "0x") return;
@@ -28125,11 +29231,11 @@ var getLiquityUserDataConverter = (lender, chainId, account, meta) => {
28125
29231
  };
28126
29232
  });
28127
29233
  const spBase = troves.length * 2;
28128
- const spDeposit = big(slice[spBase]);
28129
- const spYield = big(slice[spBase + 1]);
28130
- const spCollGain = big(slice[spBase + 2]);
28131
- const spStashed = big(slice[spBase + 3]);
28132
- const collSurplus = branch.collSurplusPool ? big(slice[spBase + 4]) : 0n;
29234
+ const spDeposit = big(slice2[spBase]);
29235
+ const spYield = big(slice2[spBase + 1]);
29236
+ const spCollGain = big(slice2[spBase + 2]);
29237
+ const spStashed = big(slice2[spBase + 3]);
29238
+ const collSurplus = branch.collSurplusPool ? big(slice2[spBase + 4]) : 0n;
28133
29239
  const spStable = spDeposit + spYield;
28134
29240
  const spColl = spCollGain + spStashed + collSurplus;
28135
29241
  if (spStable > 0n || spColl > 0n) {
@@ -28342,10 +29448,125 @@ var getRiverUserDataConverter = (lender, chainId, account, meta) => {
28342
29448
  expected
28343
29449
  ];
28344
29450
  };
29451
+ var big3 = (v) => {
29452
+ try {
29453
+ if (typeof v === "bigint") return v;
29454
+ if (typeof v === "number" || typeof v === "string") return BigInt(v);
29455
+ } catch {
29456
+ }
29457
+ return 0n;
29458
+ };
29459
+ var getInverseUserDataConverter = (lender, chainId, account, meta) => {
29460
+ const cfg = inverseConfigFor(lender, chainId);
29461
+ const markets = inverseChainData(lender, chainId)?.markets ?? [];
29462
+ const expected = cfg && markets.length > 0 ? markets.length * INVERSE_CALLS_PER_MARKET + INVERSE_TAIL_CALLS : 0;
29463
+ return [
29464
+ (data) => {
29465
+ if (!cfg || expected === 0) return void 0;
29466
+ if (!data || data.length < expected) return void 0;
29467
+ const dolaAddr = cfg.dola.toLowerCase();
29468
+ const debtDecimals = cfg.debtDecimals ?? 18;
29469
+ const tailBase = markets.length * INVERSE_CALLS_PER_MARKET;
29470
+ const dbrBalance = big3(data[tailBase]);
29471
+ const dbrDeficit = big3(data[tailBase + 1]);
29472
+ const dbrSignedRaw = data[tailBase + 2];
29473
+ const dbrSigned = isFailedCall(dbrSignedRaw) ? 0n : big3(dbrSignedRaw);
29474
+ const out = {};
29475
+ markets.forEach((market, i) => {
29476
+ const base = i * INVERSE_CALLS_PER_MARKET;
29477
+ const escrowBal = isFailedCall(data[base]) ? 0n : big3(data[base]);
29478
+ const debtRaw = data[base + 1];
29479
+ if (isFailedCall(debtRaw)) return;
29480
+ const debt = big3(debtRaw);
29481
+ if (escrowBal === 0n && debt === 0n) return;
29482
+ const creditLimit = isFailedCall(data[base + 2]) ? 0n : big3(data[base + 2]);
29483
+ const withdrawalLimit = isFailedCall(data[base + 3]) ? 0n : big3(data[base + 3]);
29484
+ const lenderKey = inverseLenderKey(lender, market.address);
29485
+ const metaMap = meta?.[lenderKey];
29486
+ if (!metaMap) return;
29487
+ const collAddr = market.collToken.toLowerCase();
29488
+ const collUid = createMarketUid(chainId, lenderKey, collAddr);
29489
+ const loanUid = createMarketUid(chainId, lenderKey, dolaAddr);
29490
+ const collMeta = metaMap[collUid];
29491
+ const loanMeta = metaMap[loanUid];
29492
+ const collDecimals = collMeta?.asset?.decimals ?? market.collDecimals;
29493
+ const collDisplay = collMeta ? getDisplayPrice(collMeta) : 0;
29494
+ const collOracle = collMeta ? getOraclePrice(collMeta) : 0;
29495
+ const collHist = collMeta?.price?.priceUsd24h ?? collDisplay;
29496
+ const loanDisplay = loanMeta ? getDisplayPrice(loanMeta) : 0;
29497
+ const loanOracle = loanMeta ? getOraclePrice(loanMeta) : 0;
29498
+ const loanHist = loanMeta?.price?.priceUsd24h ?? loanDisplay;
29499
+ const inverseInfo = {
29500
+ creditLimit: creditLimit.toString(),
29501
+ withdrawalLimit: withdrawalLimit.toString(),
29502
+ dbrBalance: dbrBalance.toString(),
29503
+ dbrDeficit: dbrDeficit.toString(),
29504
+ dbrSignedBalance: dbrSigned.toString()
29505
+ };
29506
+ const collStr = parseRawAmount(escrowBal.toString(), collDecimals);
29507
+ const collNum = Number(collStr);
29508
+ const debtStr = parseRawAmount(debt.toString(), debtDecimals);
29509
+ const debtNum = Number(debtStr);
29510
+ const lendingPositions = {
29511
+ "0": {
29512
+ [collUid]: {
29513
+ marketUid: collUid,
29514
+ underlying: collAddr,
29515
+ deposits: collStr,
29516
+ debt: "0",
29517
+ debtStable: "0",
29518
+ depositsUSD: collNum * collDisplay,
29519
+ debtUSD: 0,
29520
+ debtStableUSD: 0,
29521
+ depositsUSDOracle: collNum * collOracle,
29522
+ debtUSDOracle: 0,
29523
+ debtStableUSDOracle: 0,
29524
+ stableBorrowRate: "0",
29525
+ collateralEnabled: true,
29526
+ claimableRewards: 0
29527
+ },
29528
+ [loanUid]: {
29529
+ marketUid: loanUid,
29530
+ underlying: dolaAddr,
29531
+ deposits: "0",
29532
+ debt: debtStr,
29533
+ debtStable: "0",
29534
+ depositsUSD: 0,
29535
+ debtUSD: debtNum * loanDisplay,
29536
+ debtStableUSD: 0,
29537
+ depositsUSDOracle: 0,
29538
+ debtUSDOracle: debtNum * loanOracle,
29539
+ debtStableUSDOracle: 0,
29540
+ stableBorrowRate: "0",
29541
+ collateralEnabled: false,
29542
+ claimableRewards: 0,
29543
+ inverseInfo
29544
+ }
29545
+ }
29546
+ };
29547
+ const modes = { "0": 0 };
29548
+ const hist = {
29549
+ "0": {
29550
+ totalDeposits24h: collNum * collHist,
29551
+ totalDebt24h: debtNum * loanHist
29552
+ }
29553
+ };
29554
+ const userData = createMultiAccountTypeUserState(
29555
+ { chainId, account, lendingPositions, modes },
29556
+ metaMap,
29557
+ hist
29558
+ );
29559
+ if (userData && userData.data.length > 0) out[lenderKey] = userData;
29560
+ });
29561
+ return Object.keys(out).length > 0 ? out : void 0;
29562
+ },
29563
+ expected
29564
+ ];
29565
+ };
28345
29566
 
28346
29567
  // src/lending/user-data/teller/userCallParse.ts
28347
- var nowSec6 = () => Math.floor(Date.now() / 1e3);
28348
- var big3 = (v) => {
29568
+ var nowSec7 = () => Math.floor(Date.now() / 1e3);
29569
+ var big4 = (v) => {
28349
29570
  try {
28350
29571
  if (typeof v === "bigint") return v;
28351
29572
  if (typeof v === "number" || typeof v === "string") return BigInt(v);
@@ -28361,13 +29582,13 @@ var getTellerUserDataConverter = (_lender, chainId, account, meta) => {
28361
29582
  return [
28362
29583
  (data) => {
28363
29584
  if (expected === 0 || !data || data.length < expected) return void 0;
28364
- const now = nowSec6();
29585
+ const now = nowSec7();
28365
29586
  const perPool = {};
28366
29587
  kept.forEach((b, i) => {
28367
29588
  const base = i * TELLER_CALLS_PER_BID;
28368
29589
  const bidRes = data[base];
28369
29590
  const owed = data[base + 1];
28370
- const collAmount = big3(data[base + 2]);
29591
+ const collAmount = big4(data[base + 2]);
28371
29592
  const defaulted = !!data[base + 3];
28372
29593
  if (isFailedCall(bidRes) || isFailedCall(owed) || !bidRes) return;
28373
29594
  const pool = b.pool;
@@ -28388,17 +29609,17 @@ var getTellerUserDataConverter = (_lender, chainId, account, meta) => {
28388
29609
  const collDisplay = collMeta ? getDisplayPrice(collMeta) : 0;
28389
29610
  const collOracle = collMeta ? getOraclePrice(collMeta) : 0;
28390
29611
  const collHist = collMeta?.price?.priceUsd24h ?? collDisplay;
28391
- const owedPrincipal = big3(field8(owed, "principal", 0));
28392
- const owedInterest = big3(field8(owed, "interest", 1));
29612
+ const owedPrincipal = big4(field8(owed, "principal", 0));
29613
+ const owedInterest = big4(field8(owed, "interest", 1));
28393
29614
  const owedTotal = owedPrincipal + owedInterest;
28394
29615
  if (owedTotal === 0n && collAmount === 0n) return;
28395
29616
  const loanDetails = field8(bidRes, "loanDetails", 5);
28396
29617
  const terms = field8(bidRes, "terms", 6);
28397
29618
  const acceptedTs = Number(
28398
- big3(field8(loanDetails, "acceptedTimestamp", 4))
29619
+ big4(field8(loanDetails, "acceptedTimestamp", 4))
28399
29620
  );
28400
- const loanDuration = Number(big3(field8(loanDetails, "loanDuration", 6)));
28401
- const aprBps = Number(big3(field8(terms, "APR", 2)));
29621
+ const loanDuration = Number(big4(field8(loanDetails, "loanDuration", 6)));
29622
+ const aprBps = Number(big4(field8(terms, "APR", 2)));
28402
29623
  const maturity = acceptedTs > 0 ? acceptedTs + loanDuration : void 0;
28403
29624
  const isMatured = defaulted || maturity !== void 0 && maturity < now;
28404
29625
  const collStr = parseRawAmount(collAmount.toString(), collDecimals);
@@ -28486,6 +29707,179 @@ var getTellerUserDataConverter = (_lender, chainId, account, meta) => {
28486
29707
  expected
28487
29708
  ];
28488
29709
  };
29710
+ var nowSec8 = () => Math.floor(Date.now() / 1e3);
29711
+ function toBigInt12(v) {
29712
+ if (v === void 0 || v === null || v === "0x") return 0n;
29713
+ if (typeof v === "bigint") return v;
29714
+ try {
29715
+ return BigInt(v);
29716
+ } catch {
29717
+ return 0n;
29718
+ }
29719
+ }
29720
+ function field9(res, name, index) {
29721
+ if (res && typeof res === "object" && !Array.isArray(res) && name in res) {
29722
+ return res[name];
29723
+ }
29724
+ if (Array.isArray(res)) return res[index];
29725
+ return void 0;
29726
+ }
29727
+ function parsePosition(res) {
29728
+ const ftBalance = toBigInt12(field9(res, "ftBalance", 2));
29729
+ const xtBalance = toBigInt12(field9(res, "xtBalance", 3));
29730
+ const rawGts = field9(res, "gtInfo", 4);
29731
+ const gts = [];
29732
+ if (Array.isArray(rawGts)) {
29733
+ for (const g of rawGts) {
29734
+ const loanId = toBigInt12(field9(g, "loanId", 0));
29735
+ if (loanId === 0n) continue;
29736
+ gts.push({
29737
+ loanId: loanId.toString(),
29738
+ collateralAmt: toBigInt12(field9(g, "collateralAmt", 1)),
29739
+ debtAmt: toBigInt12(field9(g, "debtAmt", 2))
29740
+ });
29741
+ }
29742
+ }
29743
+ return { ftBalance, xtBalance, gts };
29744
+ }
29745
+ var getTermMaxUserDataConverter = (_lender, chainId, account, meta) => {
29746
+ const discovery = getCachedTermMaxDiscovery(chainId, account);
29747
+ const markets = discovery?.markets ?? [];
29748
+ const expected = markets.length > 0 ? TERMMAX_CALLS_PER_ACCOUNT : 0;
29749
+ return [
29750
+ (data) => {
29751
+ if (expected === 0) return void 0;
29752
+ if (!data || data.length < expected) return void 0;
29753
+ const positions = data[0];
29754
+ if (!Array.isArray(positions)) return void 0;
29755
+ const now = nowSec8();
29756
+ const out = {};
29757
+ markets.forEach((market, i) => {
29758
+ const parsed = parsePosition(positions[i]);
29759
+ if (!parsed) return;
29760
+ if (parsed.ftBalance === 0n && parsed.gts.length === 0) return;
29761
+ const lenderKey = termMaxLenderKey(market.market);
29762
+ const metaMap = meta?.[lenderKey];
29763
+ if (!metaMap) return;
29764
+ const loanAddr = market.debtToken.toLowerCase();
29765
+ const collAddr = market.collateral.toLowerCase();
29766
+ const loanUid = createMarketUid(chainId, lenderKey, loanAddr);
29767
+ const collUid = createMarketUid(chainId, lenderKey, collAddr);
29768
+ const loanMeta = metaMap[loanUid];
29769
+ const collMeta = metaMap[collUid];
29770
+ const loanDisplay = loanMeta ? getDisplayPrice(loanMeta) : 0;
29771
+ const loanOracle = loanMeta ? getOraclePrice(loanMeta) : 0;
29772
+ const loanHist = loanMeta?.price?.priceUsd24h ?? loanDisplay;
29773
+ const collDisplay = collMeta ? getDisplayPrice(collMeta) : 0;
29774
+ const collOracle = collMeta ? getOraclePrice(collMeta) : 0;
29775
+ const collHist = collMeta?.price?.priceUsd24h ?? collDisplay;
29776
+ const loanDec = loanMeta?.asset?.decimals ?? market.debtDecimals;
29777
+ const collDec = collMeta?.asset?.decimals ?? market.collateralDecimals;
29778
+ const maturity = Number(market.maturity);
29779
+ const isMatured = maturity > 0 && maturity <= now;
29780
+ const positionsByAccount = {};
29781
+ const modes = {};
29782
+ const hist = {};
29783
+ if (parsed.ftBalance > 0n) {
29784
+ const ftStr = parseRawAmount(parsed.ftBalance.toString(), loanDec);
29785
+ const ftNum = Number(ftStr);
29786
+ positionsByAccount["0"] = {
29787
+ [loanUid]: {
29788
+ marketUid: loanUid,
29789
+ underlying: loanAddr,
29790
+ deposits: ftStr,
29791
+ debt: "0",
29792
+ debtStable: "0",
29793
+ depositsUSD: ftNum * loanDisplay,
29794
+ debtUSD: 0,
29795
+ debtStableUSD: 0,
29796
+ depositsUSDOracle: ftNum * loanOracle,
29797
+ debtUSDOracle: 0,
29798
+ debtStableUSDOracle: 0,
29799
+ stableBorrowRate: "0",
29800
+ // A TermMax lend position never collateralizes a borrow.
29801
+ collateralEnabled: false,
29802
+ claimableRewards: 0
29803
+ }
29804
+ };
29805
+ modes["0"] = 0;
29806
+ hist["0"] = { totalDeposits24h: ftNum * loanHist, totalDebt24h: 0 };
29807
+ }
29808
+ for (const gt of parsed.gts) {
29809
+ const collStr = parseRawAmount(gt.collateralAmt.toString(), collDec);
29810
+ const collNum = Number(collStr);
29811
+ const debtStr = parseRawAmount(gt.debtAmt.toString(), loanDec);
29812
+ const debtNum = Number(debtStr);
29813
+ if (gt.collateralAmt === 0n && gt.debtAmt === 0n) continue;
29814
+ positionsByAccount[gt.loanId] = {
29815
+ [collUid]: {
29816
+ marketUid: collUid,
29817
+ underlying: collAddr,
29818
+ deposits: collStr,
29819
+ debt: "0",
29820
+ debtStable: "0",
29821
+ depositsUSD: collNum * collDisplay,
29822
+ debtUSD: 0,
29823
+ debtStableUSD: 0,
29824
+ depositsUSDOracle: collNum * collOracle,
29825
+ debtUSDOracle: 0,
29826
+ debtStableUSDOracle: 0,
29827
+ stableBorrowRate: "0",
29828
+ collateralEnabled: true,
29829
+ claimableRewards: 0
29830
+ },
29831
+ [loanUid]: {
29832
+ marketUid: loanUid,
29833
+ underlying: loanAddr,
29834
+ deposits: "0",
29835
+ debt: "0",
29836
+ // Fixed-term debt → stable slot (Exactly / Lista / Teller convention).
29837
+ debtStable: debtStr,
29838
+ depositsUSD: 0,
29839
+ debtUSD: 0,
29840
+ debtStableUSD: debtNum * loanDisplay,
29841
+ depositsUSDOracle: 0,
29842
+ debtUSDOracle: 0,
29843
+ debtStableUSDOracle: debtNum * loanOracle,
29844
+ stableBorrowRate: "0",
29845
+ collateralEnabled: false,
29846
+ claimableRewards: 0,
29847
+ // Fixed-term loan detail. `loanId` = the gtId, which is the target
29848
+ // of every write op (repay / removeCollateral / …). Debt is a
29849
+ // STATIC face value: nothing accrues, so no accruedInterest.
29850
+ term: {
29851
+ loanId: gt.loanId,
29852
+ isDynamic: false,
29853
+ debt: debtStr,
29854
+ maturity: maturity || void 0,
29855
+ isMatured
29856
+ }
29857
+ }
29858
+ };
29859
+ modes[gt.loanId] = 0;
29860
+ hist[gt.loanId] = {
29861
+ totalDeposits24h: collNum * collHist,
29862
+ totalDebt24h: debtNum * loanHist
29863
+ };
29864
+ }
29865
+ if (Object.keys(positionsByAccount).length === 0) return;
29866
+ const userData = createMultiAccountTypeUserState(
29867
+ {
29868
+ chainId,
29869
+ account,
29870
+ lendingPositions: positionsByAccount,
29871
+ modes
29872
+ },
29873
+ metaMap,
29874
+ hist
29875
+ );
29876
+ if (userData && userData.data.length > 0) out[lenderKey] = userData;
29877
+ });
29878
+ return Object.keys(out).length > 0 ? out : void 0;
29879
+ },
29880
+ expected
29881
+ ];
29882
+ };
28489
29883
 
28490
29884
  // src/lending/user-data/fetch-balances/parse.ts
28491
29885
  function getUserDataConverter(lender, chainId, account, params, meta) {
@@ -28519,6 +29913,10 @@ function getUserDataConverter(lender, chainId, account, params, meta) {
28519
29913
  return getRiverUserDataConverter(lender, chainId, account, meta);
28520
29914
  if (isTeller(lender))
28521
29915
  return getTellerUserDataConverter(lender, chainId, account, meta);
29916
+ if (isTermMax(lender))
29917
+ return getTermMaxUserDataConverter(lender, chainId, account, meta);
29918
+ if (isInverse(lender))
29919
+ return getInverseUserDataConverter(lender, chainId, account, meta);
28522
29920
  if (isCompoundV3Type(lender))
28523
29921
  return getCompoundV3UserDataConverter(
28524
29922
  lender,
@@ -33116,6 +34514,8 @@ var getAbi2 = (lender) => {
33116
34514
  return [...RiverTroveManagerAbi, ...RiverStabilityPoolAbi];
33117
34515
  if (isTeller(lender))
33118
34516
  return [...TellerV2Abi, ...TellerCollateralManagerAbi];
34517
+ if (isInverse(lender))
34518
+ return [...InverseMarketAbi, ...InverseEscrowAbi, ...InverseDbrAbi];
33119
34519
  if (isInit(lender)) return InitLensAbi;
33120
34520
  if (isEulerType(lender)) return accountLensAbi;
33121
34521
  if (isCompoundV2Type(lender))
@@ -33672,7 +35072,7 @@ var MORPHO_API_CHAIN_IDS = {
33672
35072
  [Chain.UNICHAIN]: 130
33673
35073
  };
33674
35074
  var FETCH_TIMEOUT_MS = 3e3;
33675
- var CACHE_TTL_MS3 = 2e3;
35075
+ var CACHE_TTL_MS4 = 2e3;
33676
35076
  var buildSubgraphQuery = (account) => `
33677
35077
  {
33678
35078
  account(id: "${account.toLowerCase()}") {
@@ -33727,11 +35127,11 @@ async function fetchJsonWithProxyFallback(url, body, proxyConfig) {
33727
35127
  }
33728
35128
  var inflight = /* @__PURE__ */ new Map();
33729
35129
  var resolved = /* @__PURE__ */ new Map();
33730
- function cacheKey3(chainId, account) {
35130
+ function cacheKey4(chainId, account) {
33731
35131
  return `${chainId}:${account.toLowerCase()}`;
33732
35132
  }
33733
35133
  async function dedupedFetch(chainId, account, loader) {
33734
- const key = cacheKey3(chainId, account);
35134
+ const key = cacheKey4(chainId, account);
33735
35135
  const now = Date.now();
33736
35136
  const cached = resolved.get(key);
33737
35137
  if (cached && cached.expiresAt > now) {
@@ -33740,7 +35140,7 @@ async function dedupedFetch(chainId, account, loader) {
33740
35140
  const existing = inflight.get(key);
33741
35141
  if (existing) return existing;
33742
35142
  const promise = loader().then((value) => {
33743
- resolved.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS3 });
35143
+ resolved.set(key, { value, expiresAt: Date.now() + CACHE_TTL_MS4 });
33744
35144
  return value;
33745
35145
  }).finally(() => {
33746
35146
  inflight.delete(key);
@@ -33872,8 +35272,8 @@ function calculateOverallNetApr(totalDepositsUSD, totalDebtUSD, avgDepositApr, a
33872
35272
  return (totalDepositsUSD * avgDepositApr - totalDebtUSD * avgBorrowApr) / Math.abs(totalNetWorth) * (totalNetWorth > 0 ? 1 : -1);
33873
35273
  }
33874
35274
  function calculateWeightedAprs(items) {
33875
- const wa = (field9, weightField) => calculateWeightedAverage(
33876
- items.filter((i) => i[weightField] !== 0).map((i) => ({ value: i[field9], weight: Math.abs(i[weightField]) }))
35275
+ const wa = (field10, weightField) => calculateWeightedAverage(
35276
+ items.filter((i) => i[weightField] !== 0).map((i) => ({ value: i[field10], weight: Math.abs(i[weightField]) }))
33877
35277
  );
33878
35278
  return {
33879
35279
  apr: wa("apr", "nav"),
@@ -35617,8 +37017,8 @@ var TIMEOUT_MS = 8e3;
35617
37017
  var slisBnbFetcher = {
35618
37018
  label: "SLISBNB",
35619
37019
  fetch: async () => {
35620
- const nowSec7 = Math.floor(Date.now() / 1e3);
35621
- const url = `${HISTORY_URL}?name=slisBNBRate&cycle=1&startTime=${nowSec7 - LOOKBACK_SECONDS}&endTime=${nowSec7}`;
37020
+ const nowSec9 = Math.floor(Date.now() / 1e3);
37021
+ const url = `${HISTORY_URL}?name=slisBNBRate&cycle=1&startTime=${nowSec9 - LOOKBACK_SECONDS}&endTime=${nowSec9}`;
35622
37022
  const controller = new AbortController();
35623
37023
  const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
35624
37024
  try {
@@ -38212,6 +39612,40 @@ var rwaFundsFetcher = {
38212
39612
  }
38213
39613
  };
38214
39614
 
39615
+ // src/yields/intrinsic/fetchers/inverse.ts
39616
+ var DOLA_STAKING_URL = "https://www.inverse.finance/api/dola-staking";
39617
+ var JDOLA_STAKING_URL = "https://www.inverse.finance/api/junior/jdola-staking";
39618
+ var SDOLA_KEY = "SDOLA";
39619
+ var SDOLA_GROUP_KEY = "sDOLA::SDOLA";
39620
+ var fetchJson2 = async (url) => {
39621
+ const res = await fetch(url, {
39622
+ headers: { accept: "application/json" },
39623
+ signal: AbortSignal.timeout(8e3)
39624
+ });
39625
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
39626
+ return res.json();
39627
+ };
39628
+ var fetchSdolaApyPercent = async () => {
39629
+ try {
39630
+ const d = await fetchJson2(DOLA_STAKING_URL);
39631
+ const apy = Number(d?.calculatedApy);
39632
+ if (Number.isFinite(apy) && apy > 0) return apy;
39633
+ throw new Error("calculatedApy missing");
39634
+ } catch {
39635
+ const d = await fetchJson2(JDOLA_STAKING_URL);
39636
+ const apy = Number(d?.sDolaApy);
39637
+ if (Number.isFinite(apy) && apy > 0) return apy;
39638
+ throw new Error("sDolaApy missing");
39639
+ }
39640
+ };
39641
+ var sdolaFetcher = {
39642
+ label: "SDOLA",
39643
+ fetch: async () => {
39644
+ const apr = apyToAprPercent(await fetchSdolaApyPercent());
39645
+ return { [SDOLA_KEY]: apr, [SDOLA_GROUP_KEY]: apr };
39646
+ }
39647
+ };
39648
+
38215
39649
  // src/yields/intrinsic/fetchers/reProtocol.ts
38216
39650
  var REUSD_KEY = "RE::reUSD";
38217
39651
  var REUSDE_KEY = "RE::reUSDe";
@@ -39722,6 +41156,27 @@ var SINGLE_CHAIN_ENTRIES = {
39722
41156
  yieldFetcher: fraxSavingsFetcher,
39723
41157
  yieldKey: "SFRAX"
39724
41158
  },
41159
+ {
41160
+ // Inverse sDOLA — 4626 auto-compounder over the DOLA Savings
41161
+ // Account; yield is FiRM's DBR revenue via a continuous on-chain
41162
+ // auction, no rehypothecation. Instant permissionless exit
41163
+ // (maxDeposit = uint.max verified 2026-08; ~6.9M DOLA TVL).
41164
+ // Ethereum-only; Inverse propagates the rate cross-chain via
41165
+ // CCIP, so bridged deployments may appear later. The jDOLA
41166
+ // junior tranche (48h exit window + fee, ~$28k) is deliberately
41167
+ // not registered.
41168
+ address: "0xb45ad160634c528cc3d2926d9807104fa3157305",
41169
+ underlying: "0x865377367054516e17014ccded1e7d814edc9ce4",
41170
+ // DOLA
41171
+ symbol: "sDOLA",
41172
+ brand: "Inverse",
41173
+ decimals: 18,
41174
+ isRebasing: false,
41175
+ isMintable: true,
41176
+ withdrawalMode: "instant",
41177
+ yieldFetcher: sdolaFetcher,
41178
+ yieldKey: SDOLA_GROUP_KEY
41179
+ },
39725
41180
  {
39726
41181
  address: "0x83f20f44975d03b1b09e64809b757c47f942beea",
39727
41182
  underlying: "0x6b175474e89094c44da98b954eedeac495271d0f",
@@ -40256,13 +41711,13 @@ var gmxFetcher = {
40256
41711
  fetch: async () => {
40257
41712
  const { apy } = await fetchGmxRawData(GMX_CHAIN, GMX_DEFAULT_APY_PERIOD);
40258
41713
  const rData = {};
40259
- for (const [addr, d] of Object.entries(apy.markets ?? {})) {
40260
- const a = addr.toLowerCase();
41714
+ for (const [addr2, d] of Object.entries(apy.markets ?? {})) {
41715
+ const a = addr2.toLowerCase();
40261
41716
  if (a === gmx_eth_usd_address) rData[gmx_eth_usd] = apyToApr(d.apy) * 100;
40262
41717
  if (a === gmx_btc_usd_address) rData[gmx_btc_usd] = apyToApr(d.apy) * 100;
40263
41718
  }
40264
- for (const [addr, d] of Object.entries(apy.glvs ?? {})) {
40265
- const a = addr.toLowerCase();
41719
+ for (const [addr2, d] of Object.entries(apy.glvs ?? {})) {
41720
+ const a = addr2.toLowerCase();
40266
41721
  if (a === glv_wbtc_usdc_address)
40267
41722
  rData[glv_wbtc_usdc] = apyToApr(d.apy) * 100;
40268
41723
  if (a === glv_weth_usdc_address)
@@ -40746,8 +42201,8 @@ var yearnKatanaFetcher = {
40746
42201
  YEARN_KATANA_URL
40747
42202
  ).then((r) => r.json());
40748
42203
  let map = {};
40749
- Object.entries(res).forEach(([addr, data]) => {
40750
- const key = addressToAssetYearn[addr.toLowerCase()];
42204
+ Object.entries(res).forEach(([addr2, data]) => {
42205
+ const key = addressToAssetYearn[addr2.toLowerCase()];
40751
42206
  if (key) {
40752
42207
  const apr = ((data.apr.netAPR ?? 0) + (data.apr.extra?.extrinsicYield ?? 0) + (data.apr.extra?.katanaNativeYield ?? 0)) * 100;
40753
42208
  map[key] = apr;
@@ -41949,9 +43404,9 @@ function parseTellerResults(data, meta, context) {
41949
43404
  const principal = meta.principal;
41950
43405
  const collateral = meta.collateral;
41951
43406
  const lenderKey = tellerLenderKey(meta.pool);
41952
- const usdOf = (addr) => {
41953
- const key = tokenList?.[addr]?.assetGroup ?? `${chainId}-${addr}`;
41954
- return usdPrices[key] ?? usdPrices[addr];
43407
+ const usdOf = (addr2) => {
43408
+ const key = tokenList?.[addr2]?.assetGroup ?? `${chainId}-${addr2}`;
43409
+ return usdPrices[key] ?? usdPrices[addr2];
41955
43410
  };
41956
43411
  const principalUSD = usdOf(principal);
41957
43412
  const collateralUSD = usdOf(collateral);
@@ -42017,6 +43472,86 @@ var tellerFetcher = {
42017
43472
  parse: parseTellerResults,
42018
43473
  getAbi: getTellerAbi
42019
43474
  };
43475
+ function getTermMaxCalls(chainId) {
43476
+ const proto = termMaxConfigByChain(chainId);
43477
+ if (!proto?.oracleAggregatorV2) return [];
43478
+ const markets = getCachedTermMaxMarkets(chainId);
43479
+ if (markets.length === 0) return [];
43480
+ const oracle = proto.oracleAggregatorV2;
43481
+ const results = [];
43482
+ for (const m of markets) {
43483
+ if (!m.market || !m.debtToken || !m.collateral) continue;
43484
+ const calls = [
43485
+ { address: oracle, name: "getPrice", params: [m.debtToken] },
43486
+ { address: oracle, name: "getPrice", params: [m.collateral] }
43487
+ ];
43488
+ results.push({
43489
+ calls,
43490
+ meta: {
43491
+ market: m.market.toLowerCase(),
43492
+ debtToken: m.debtToken.toLowerCase(),
43493
+ collateral: m.collateral.toLowerCase()
43494
+ },
43495
+ lender: termMaxLenderKey(m.market)
43496
+ });
43497
+ }
43498
+ return results;
43499
+ }
43500
+ function readUsdPrice(res) {
43501
+ if (res == null || res === "0x") return void 0;
43502
+ let raw;
43503
+ let dec;
43504
+ if (Array.isArray(res)) {
43505
+ raw = res[0];
43506
+ dec = res[1];
43507
+ } else if (typeof res === "object") {
43508
+ raw = res.price;
43509
+ dec = res.decimals;
43510
+ } else {
43511
+ return void 0;
43512
+ }
43513
+ let price2;
43514
+ try {
43515
+ price2 = BigInt(raw);
43516
+ } catch {
43517
+ return void 0;
43518
+ }
43519
+ if (price2 <= 0n) return void 0;
43520
+ const decimals = Number(dec);
43521
+ if (!Number.isFinite(decimals) || decimals < 0 || decimals > 36) return void 0;
43522
+ const usd = Number(price2) / 10 ** decimals;
43523
+ return Number.isFinite(usd) && usd > 0 ? usd : void 0;
43524
+ }
43525
+ function parseTermMaxResults(data, meta, context) {
43526
+ const { chainId } = context;
43527
+ const lenderKey = termMaxLenderKey(meta.market);
43528
+ const entries = [];
43529
+ const legs = [
43530
+ [meta.debtToken, data?.[0], "TermMax oracle (debt asset)"],
43531
+ [meta.collateral, data?.[1], "TermMax oracle (collateral)"]
43532
+ ];
43533
+ for (const [asset, res, description] of legs) {
43534
+ const usd = readUsdPrice(res);
43535
+ if (usd === void 0) continue;
43536
+ entries.push({
43537
+ asset,
43538
+ price: usd,
43539
+ priceUSD: usd,
43540
+ marketUid: createMarketUid(chainId, lenderKey, asset),
43541
+ targetLender: lenderKey,
43542
+ description
43543
+ });
43544
+ }
43545
+ return entries;
43546
+ }
43547
+ function getTermMaxAbi() {
43548
+ return TermMaxOracleAggregatorV2Abi;
43549
+ }
43550
+ var termMaxFetcher = {
43551
+ getCalls: getTermMaxCalls,
43552
+ parse: parseTermMaxResults,
43553
+ getAbi: getTermMaxAbi
43554
+ };
42020
43555
  var CompoundV2OracleAbi = [
42021
43556
  {
42022
43557
  inputs: [{ internalType: "address", name: "cToken", type: "address" }],
@@ -42356,8 +43891,8 @@ var priceLensAbi = [
42356
43891
  // src/prices/oracle-prices/fetchers/euler.ts
42357
43892
  var MAX_VIRTUAL_ADDRESS = 65535;
42358
43893
  var MAX_SANE_PRICE_USD = 1e7;
42359
- function isUsdUnitOfAccount(addr) {
42360
- const numeric = parseInt(addr, 16);
43894
+ function isUsdUnitOfAccount(addr2) {
43895
+ const numeric = parseInt(addr2, 16);
42361
43896
  return numeric <= MAX_VIRTUAL_ADDRESS;
42362
43897
  }
42363
43898
  var PRICE_LENS_ADDRESS = "0x6392892f3C57c658d2c748fc64c6fe57680E889F";
@@ -42915,7 +44450,7 @@ var siloV3Fetcher = {
42915
44450
  getAbi: getSiloV3Abi
42916
44451
  };
42917
44452
  var FLUID_EEE_LOWER3 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
42918
- var normalizeUnderlying4 = (addr) => addr === FLUID_EEE_LOWER3 ? zeroAddress : addr;
44453
+ var normalizeUnderlying4 = (addr2) => addr2 === FLUID_EEE_LOWER3 ? zeroAddress : addr2;
42919
44454
  function priceColInDebt(raw, colDec, debtDec) {
42920
44455
  return formatMorphoPrice(raw, debtDec, colDec + 9);
42921
44456
  }
@@ -43760,6 +45295,11 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
43760
45295
  () => tellerFetcher.getCalls(chainId),
43761
45296
  getCallsErrors
43762
45297
  ) : [];
45298
+ const termMaxResults = isActive("termmax") ? safeGetCalls(
45299
+ "termmax",
45300
+ () => termMaxFetcher.getCalls(chainId),
45301
+ getCallsErrors
45302
+ ) : [];
43763
45303
  const siloV2Results = isActive("silov2") ? safeGetCalls(
43764
45304
  "siloV2",
43765
45305
  () => siloV2Fetcher.getCalls(chainId),
@@ -43876,6 +45416,15 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
43876
45416
  getTellerAbi(),
43877
45417
  "derived"
43878
45418
  );
45419
+ const termMaxGroup = buildGroup(
45420
+ "termmax",
45421
+ termMaxResults,
45422
+ termMaxFetcher.parse,
45423
+ getTermMaxAbi(),
45424
+ // DIRECT: `OracleAggregatorV2.getPrice` returns a USD price outright —
45425
+ // nothing is derived from another asset's price.
45426
+ "direct"
45427
+ );
43879
45428
  const siloV2Group = buildGroup(
43880
45429
  "siloV2",
43881
45430
  siloV2Results,
@@ -43925,6 +45474,7 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
43925
45474
  liquityGroup,
43926
45475
  riverGroup,
43927
45476
  tellerGroup,
45477
+ termMaxGroup,
43928
45478
  siloV2Group,
43929
45479
  siloV3Group,
43930
45480
  fluidGroup,
@@ -43971,6 +45521,7 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
43971
45521
  liquityData,
43972
45522
  riverData,
43973
45523
  tellerData,
45524
+ termMaxData,
43974
45525
  morphoGqlEntries,
43975
45526
  siloV2GqlEntries,
43976
45527
  siloV3GqlEntries
@@ -44095,6 +45646,14 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
44095
45646
  allowFailure,
44096
45647
  rpcOverrides
44097
45648
  ),
45649
+ executeGroup(
45650
+ termMaxGroup,
45651
+ chainId,
45652
+ chainBatchSize,
45653
+ retries,
45654
+ allowFailure,
45655
+ rpcOverrides
45656
+ ),
44098
45657
  morphoGqlPromise,
44099
45658
  siloV2GqlPromise,
44100
45659
  siloV3GqlPromise
@@ -44147,6 +45706,7 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
44147
45706
  { group: dolomiteGroup, data: dolomiteData },
44148
45707
  { group: midnightGroup, data: midnightData },
44149
45708
  { group: tellerGroup, data: tellerData },
45709
+ { group: termMaxGroup, data: termMaxData },
44150
45710
  ...siloV2GqlEntries != null ? [] : [{ group: siloV2Group, data: siloV2Data }],
44151
45711
  ...siloV3GqlEntries != null ? [] : [{ group: siloV3Group, data: siloV3Data }],
44152
45712
  // In hybrid mode the on-chain multicall ran too — surface its errors.
@@ -44206,6 +45766,7 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
44206
45766
  parseTrackers(listaGroup, listaData.results);
44207
45767
  parseTrackers(eulerGroup, eulerData.results);
44208
45768
  parseTrackers(aaveV4Group, aaveV4Data.results);
45769
+ parseTrackers(termMaxGroup, termMaxData.results);
44209
45770
  parseTrackers(
44210
45771
  aaveGroup,
44211
45772
  aaveData.results,
@@ -44455,9 +46016,9 @@ function rejectOutliers(candidates, guard = DEFAULT_OUTLIER_GUARD) {
44455
46016
  const reference = consensusReference(candidates, guard);
44456
46017
  if (reference === void 0) return candidates;
44457
46018
  const upper = reference * guard.rejectFactor;
44458
- const lower = reference / guard.rejectFactor;
46019
+ const lower3 = reference / guard.rejectFactor;
44459
46020
  const kept = candidates.filter(
44460
- (c) => c.priceUSD <= upper && c.priceUSD >= lower
46021
+ (c) => c.priceUSD <= upper && c.priceUSD >= lower3
44461
46022
  );
44462
46023
  return kept.length > 0 ? kept : candidates;
44463
46024
  }
@@ -44816,10 +46377,10 @@ function createAssetArrayPerChain() {
44816
46377
  return assetsPerChain;
44817
46378
  }
44818
46379
  var RELEVANT_LENDING_ASSETS = () => createAssetArrayPerChain();
44819
- function createSimpleArrayPerChain(fork, field9 = void 0) {
46380
+ function createSimpleArrayPerChain(fork, field10 = void 0) {
44820
46381
  let pools = {};
44821
46382
  Object.entries(fork ?? {}).forEach(([b2, data]) => {
44822
- Object.entries(field9 ? data[field9] : data).forEach(
46383
+ Object.entries(field10 ? data[field10] : data).forEach(
44823
46384
  ([chainId, address]) => {
44824
46385
  if (!pools[chainId]) pools[chainId] = [];
44825
46386
  pools[chainId] = uniq2([...pools[chainId], { address, pool: b2 }]);
@@ -45175,7 +46736,7 @@ var composeVaultDisplayName = (brand, curatorName, asset, fallbackName) => {
45175
46736
 
45176
46737
  // src/vaults/fluid/publicCallParse.ts
45177
46738
  var FLUID_EEE_LOWER4 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
45178
- var normalizeUnderlying5 = (addr) => addr === FLUID_EEE_LOWER4 ? zeroAddress : addr;
46739
+ var normalizeUnderlying5 = (addr2) => addr2 === FLUID_EEE_LOWER4 ? zeroAddress : addr2;
45179
46740
  var FLUID_RATE_SCALE2 = 100;
45180
46741
  var scaleFluidRate2 = (raw) => {
45181
46742
  if (raw === void 0 || raw === null) return 0;
@@ -45416,10 +46977,10 @@ function deriveConvertToAssets(totalAssetsRaw, totalSupplyRaw, shareDecimals) {
45416
46977
 
45417
46978
  // src/vaults/gearbox/publicCallParse.ts
45418
46979
  var WETH_MAINNET = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
45419
- var normalizeUnderlying6 = (addr, chainId) => {
45420
- const lower = addr.toLowerCase();
45421
- if (chainId === "1" && lower === WETH_MAINNET) return zeroAddress;
45422
- return lower;
46980
+ var normalizeUnderlying6 = (addr2, chainId) => {
46981
+ const lower3 = addr2.toLowerCase();
46982
+ if (chainId === "1" && lower3 === WETH_MAINNET) return zeroAddress;
46983
+ return lower3;
45423
46984
  };
45424
46985
  var RAY_TO_PERCENT2 = 1e25;
45425
46986
  var scaleRate = (raw) => {
@@ -45878,9 +47439,9 @@ var VAULT_V2_ADAPTER_ABI = parseAbi([
45878
47439
  ]);
45879
47440
  var PHASE1_ABI = [...MetaMorphoAbi, ...VAULT_V2_PHASE1_ABI];
45880
47441
  var FEE_SCALE = 1e18;
45881
- var isHex40 = (addr) => typeof addr === "string" && /^0x[0-9a-f]{40}$/i.test(addr);
47442
+ var isHex40 = (addr2) => typeof addr2 === "string" && /^0x[0-9a-f]{40}$/i.test(addr2);
45882
47443
  var isHex64 = (v) => typeof v === "string" && /^0x[0-9a-f]{64}$/i.test(v);
45883
- var lcOrUndefined = (addr) => isHex40(addr) ? addr.toLowerCase() : void 0;
47444
+ var lcOrUndefined = (addr2) => isHex40(addr2) ? addr2.toLowerCase() : void 0;
45884
47445
  var toNumberSafe = (raw, fallback = 0) => {
45885
47446
  if (raw === void 0 || raw === null) return fallback;
45886
47447
  const n = Number(raw);
@@ -46027,12 +47588,12 @@ var fetchMorphoVaultsFromChain = async (chainId, multicallRetry, prices = {}, to
46027
47588
  for (let i = 0; i < entries.length; i++) {
46028
47589
  const { entry } = entries[i];
46029
47590
  const base = i * PHASE1_PER_VAULT;
46030
- const slice = phase1.slice(base, base + CALLS_PER_VAULT);
47591
+ const slice2 = phase1.slice(base, base + CALLS_PER_VAULT);
46031
47592
  const v2 = isV2[i] ? v2ByVault.get(entry.vault.toLowerCase()) ?? null : null;
46032
47593
  const v2FeePercent = isV2[i] ? toNumberSafe(phase1[base + PERFORMANCE_FEE_INDEX]) / FEE_SCALE * 100 : void 0;
46033
47594
  const parsed = parseVault3(
46034
47595
  entry,
46035
- slice,
47596
+ slice2,
46036
47597
  chainId,
46037
47598
  prices,
46038
47599
  tokenList,
@@ -46418,11 +47979,11 @@ var PHASE1_CALLS2 = [
46418
47979
  var PHASE1_PER_VAULT2 = PHASE1_CALLS2.length;
46419
47980
  var WITHDRAW_QUEUE_LENGTH_INDEX2 = 8;
46420
47981
  var FEE_SCALE2 = 1e18;
46421
- var isHex402 = (addr) => typeof addr === "string" && /^0x[0-9a-f]{40}$/i.test(addr);
46422
- var lcOrUndefined2 = (addr) => {
46423
- if (!isHex402(addr)) return void 0;
46424
- const lower = addr.toLowerCase();
46425
- return lower === zeroAddress ? void 0 : lower;
47982
+ var isHex402 = (addr2) => typeof addr2 === "string" && /^0x[0-9a-f]{40}$/i.test(addr2);
47983
+ var lcOrUndefined2 = (addr2) => {
47984
+ if (!isHex402(addr2)) return void 0;
47985
+ const lower3 = addr2.toLowerCase();
47986
+ return lower3 === zeroAddress ? void 0 : lower3;
46426
47987
  };
46427
47988
  var isHex642 = (val) => typeof val === "string" && /^0x[0-9a-f]{64}$/i.test(val);
46428
47989
  var toNumberSafe2 = (raw, fallback = 0) => {
@@ -46533,10 +48094,10 @@ var fetchListaVaultsFromChain = async (chainId, multicallRetry, prices = {}, tok
46533
48094
  const out = {};
46534
48095
  for (let i = 0; i < entries.length; i++) {
46535
48096
  const entry = entries[i];
46536
- const slice = phase1.slice(i * PHASE1_PER_VAULT2, (i + 1) * PHASE1_PER_VAULT2);
48097
+ const slice2 = phase1.slice(i * PHASE1_PER_VAULT2, (i + 1) * PHASE1_PER_VAULT2);
46537
48098
  const parsed = parseVault4(
46538
48099
  entry,
46539
- slice,
48100
+ slice2,
46540
48101
  curatorAddrByVault[i],
46541
48102
  chainId,
46542
48103
  prices,
@@ -47028,9 +48589,9 @@ query EvkByAssets($assets: [Bytes!]!) {
47028
48589
  `;
47029
48590
  var ZERO = 0n;
47030
48591
  var RAY_TO_PERCENT3 = 1e25;
47031
- function readAddress2(field9) {
47032
- if (!field9) return void 0;
47033
- return field9.toLowerCase();
48592
+ function readAddress2(field10) {
48593
+ if (!field10) return void 0;
48594
+ return field10.toLowerCase();
47034
48595
  }
47035
48596
  function parseVaultFee(v) {
47036
48597
  if (v.performanceFee == null) return 0;
@@ -47389,6 +48950,300 @@ var fetchEulerEarnVaults = async (chainId, prices = {}, tokenList = {}, multical
47389
48950
  ).catch(() => void 0);
47390
48951
  return isNonEmpty(fromSubgraph) ? fromSubgraph : fromApi ?? {};
47391
48952
  };
48953
+ var warn6 = (...args) => {
48954
+ };
48955
+ var num2 = (v) => {
48956
+ const n = Number(v);
48957
+ return Number.isFinite(n) ? n : 0;
48958
+ };
48959
+ var big5 = (v) => {
48960
+ try {
48961
+ if (v === void 0 || v === null || v === "") return "0";
48962
+ const s = String(v);
48963
+ return BigInt(s.includes(".") ? s.slice(0, s.indexOf(".")) : s).toString();
48964
+ } catch {
48965
+ return "0";
48966
+ }
48967
+ };
48968
+ var lower2 = (v) => String(v ?? "").toLowerCase();
48969
+ async function fetchTermMaxVaultsFromApi(chainId, prices = {}, tokenList = {}, fetchImpl = fetch) {
48970
+ const url = `${termMaxApiBase(chainId)}/vault/list?chainId=${chainId}`;
48971
+ let rows;
48972
+ try {
48973
+ const res = await fetchImpl.call(globalThis, url);
48974
+ if (!res.ok) {
48975
+ warn6(`vault/list ${chainId} \u2192 HTTP ${res.status}`);
48976
+ return null;
48977
+ }
48978
+ const json = await res.json();
48979
+ rows = Array.isArray(json?.data) ? json.data : [];
48980
+ } catch (e) {
48981
+ warn6(`vault/list ${chainId} failed:`, e?.message ?? e);
48982
+ return null;
48983
+ }
48984
+ const out = {};
48985
+ for (const r of rows) {
48986
+ const address = lower2(r?.vaultAddress);
48987
+ const underlying = lower2(r?.asset?.contractAddress);
48988
+ if (!address || !underlying) continue;
48989
+ if (r.isEnabled === false) continue;
48990
+ const assetDecimals = num2(r?.asset?.decimals) || 18;
48991
+ const scale = 10 ** assetDecimals;
48992
+ const assetEntry = tokenList[underlying];
48993
+ const priceKey = toOracleKey(assetEntry?.assetGroup) || toGenericPriceKey(underlying, chainId);
48994
+ const priceUsd = prices[priceKey];
48995
+ const totalAssets = big5(r.totalAssets);
48996
+ const totalSupply = big5(r.totalSupplyAmt);
48997
+ const totalAssetsFormatted = Number(totalAssets) / scale;
48998
+ const supplyRate = num2(r.apr) * 100;
48999
+ const rewardsRate = num2(r?.incentiveData?.TMX_APR) * 100;
49000
+ const rawLiquidity = BigInt(big5(r.redeemableAmt ?? r.idleFunds ?? "0"));
49001
+ const totalAssetsBig = BigInt(totalAssets);
49002
+ const liquidity = (rawLiquidity > totalAssetsBig ? totalAssetsBig : rawLiquidity).toString();
49003
+ const liquidityFormatted = Number(liquidity) / scale;
49004
+ const totalSupplyValue = num2(r.totalSupplyValue);
49005
+ out[address] = {
49006
+ address,
49007
+ underlying,
49008
+ symbol: String(r.symbol ?? ""),
49009
+ name: String(r.name ?? ""),
49010
+ // Share decimals are not reported; TermMax vault shares track the
49011
+ // asset's decimals (verified on-chain: 6-dec USDC vault, 18-dec WETH).
49012
+ decimals: assetDecimals,
49013
+ assetDecimals,
49014
+ totalAssets,
49015
+ totalSupply,
49016
+ convertToAssets: BigInt(totalSupply) > 0n ? (BigInt(totalAssets) * 10n ** BigInt(assetDecimals) / BigInt(totalSupply)).toString() : "0",
49017
+ supplyRate,
49018
+ rewardsRate,
49019
+ depositRate: supplyRate + rewardsRate,
49020
+ // 1e8-scaled upstream (10000000 = 10%).
49021
+ fee: num2(r.performanceFeeRate) / 1e6,
49022
+ timelock: num2(r.timeLockSeconds) || void 0,
49023
+ curator: r?.curator?.curatorAddress ? lower2(r.curator.curatorAddress) : void 0,
49024
+ // The API is the ONLY source for this — do not derive it from `name`.
49025
+ curatorName: r?.curator?.name || void 0,
49026
+ guardian: r?.guardianAddress ? lower2(r.guardianAddress) : void 0,
49027
+ asset: assetEntry,
49028
+ priceUsd,
49029
+ totalAssetsFormatted,
49030
+ totalAssetsUsd: totalSupplyValue > 0 ? totalSupplyValue : priceUsd ? totalAssetsFormatted * priceUsd : 0,
49031
+ liquidity,
49032
+ liquidityFormatted,
49033
+ liquidityUsd: priceUsd ? liquidityFormatted * priceUsd : 0,
49034
+ version: r.version,
49035
+ isPaused: r.isPaused === true || void 0,
49036
+ supplyCap: r.capacity ? big5(r.capacity) : void 0,
49037
+ basePool: r.poolAddress ? lower2(r.poolAddress) : void 0
49038
+ };
49039
+ }
49040
+ return out;
49041
+ }
49042
+
49043
+ // src/vaults/termmax/abi.ts
49044
+ var TermMaxVaultAbi = [
49045
+ { type: "function", name: "name", stateMutability: "view", inputs: [], outputs: [{ type: "string" }] },
49046
+ { type: "function", name: "symbol", stateMutability: "view", inputs: [], outputs: [{ type: "string" }] },
49047
+ { type: "function", name: "decimals", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
49048
+ { type: "function", name: "asset", stateMutability: "view", inputs: [], outputs: [{ type: "address" }] },
49049
+ { type: "function", name: "totalAssets", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49050
+ { type: "function", name: "totalSupply", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49051
+ {
49052
+ type: "function",
49053
+ name: "convertToAssets",
49054
+ stateMutability: "view",
49055
+ inputs: [{ name: "shares", type: "uint256" }],
49056
+ outputs: [{ type: "uint256" }]
49057
+ },
49058
+ {
49059
+ type: "function",
49060
+ name: "balanceOf",
49061
+ stateMutability: "view",
49062
+ inputs: [{ name: "account", type: "address" }],
49063
+ outputs: [{ type: "uint256" }]
49064
+ },
49065
+ // GROSS annual interest in underlying units. The performance fee is deducted
49066
+ // from it on accrual, so it must be netted before publishing a rate.
49067
+ { type: "function", name: "annualizedInterest", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49068
+ // Depositors' accruing claim — the correct APR denominator. REVERTS on 2.0.0.
49069
+ { type: "function", name: "accretingPrincipal", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49070
+ // 1e8-scaled (0.1e8 = 10%).
49071
+ { type: "function", name: "performanceFeeRate", stateMutability: "view", inputs: [], outputs: [{ type: "uint64" }] },
49072
+ // Pre-computed net APY. REVERTS on 2.0.0 — we derive instead.
49073
+ { type: "function", name: "apr", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49074
+ { type: "function", name: "curator", stateMutability: "view", inputs: [], outputs: [{ type: "address" }] },
49075
+ { type: "function", name: "guardian", stateMutability: "view", inputs: [], outputs: [{ type: "address" }] },
49076
+ { type: "function", name: "timelock", stateMutability: "view", inputs: [], outputs: [{ type: "uint256" }] },
49077
+ { type: "function", name: "getVersion", stateMutability: "pure", inputs: [], outputs: [{ type: "string" }] }
49078
+ ];
49079
+ var Erc20DecimalsBalanceAbi = [
49080
+ { type: "function", name: "decimals", stateMutability: "view", inputs: [], outputs: [{ type: "uint8" }] },
49081
+ {
49082
+ type: "function",
49083
+ name: "balanceOf",
49084
+ stateMutability: "view",
49085
+ inputs: [{ name: "account", type: "address" }],
49086
+ outputs: [{ type: "uint256" }]
49087
+ }
49088
+ ];
49089
+
49090
+ // src/vaults/termmax/fetchFromChain.ts
49091
+ var DECIMAL_BASE2 = 100000000n;
49092
+ var big6 = (v) => {
49093
+ if (v === void 0 || v === null || v === "0x") return 0n;
49094
+ try {
49095
+ return typeof v === "bigint" ? v : BigInt(v);
49096
+ } catch {
49097
+ return 0n;
49098
+ }
49099
+ };
49100
+ var num3 = (v) => {
49101
+ const n = Number(v);
49102
+ return Number.isFinite(n) ? n : void 0;
49103
+ };
49104
+ var str = (v) => typeof v === "string" && v.length > 0 ? v : void 0;
49105
+ var addr = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{40}$/.test(v) && !/^0x0{40}$/.test(v) ? v.toLowerCase() : void 0;
49106
+ async function discoverVaultAddresses(chainId) {
49107
+ const markets = await fetchTermMaxMarkets(chainId).catch(() => []);
49108
+ const seen = /* @__PURE__ */ new Set();
49109
+ for (const m of markets) {
49110
+ for (const o of m.orders) {
49111
+ if (!o.makerIsVault) continue;
49112
+ const maker = addr(o.makerAddress);
49113
+ if (maker) seen.add(maker);
49114
+ }
49115
+ }
49116
+ return [...seen];
49117
+ }
49118
+ var VAULT_READS = [
49119
+ "name",
49120
+ "symbol",
49121
+ "decimals",
49122
+ "asset",
49123
+ "totalAssets",
49124
+ "totalSupply",
49125
+ "annualizedInterest",
49126
+ "accretingPrincipal",
49127
+ "performanceFeeRate",
49128
+ "apr",
49129
+ "curator",
49130
+ "guardian",
49131
+ "timelock",
49132
+ "getVersion"
49133
+ ];
49134
+ var READS_PER_VAULT = VAULT_READS.length;
49135
+ var fetchTermMaxVaultsFromChain = async (chainId, multicallRetry, prices = {}, tokenList = {}) => {
49136
+ if (!termMaxConfigByChain(chainId)) return {};
49137
+ const vaults = await discoverVaultAddresses(chainId);
49138
+ if (vaults.length === 0) return {};
49139
+ const calls = vaults.flatMap(
49140
+ (address) => VAULT_READS.map((name) => ({
49141
+ address,
49142
+ name,
49143
+ params: []
49144
+ }))
49145
+ );
49146
+ const res = await multicallRetry({
49147
+ chain: chainId,
49148
+ calls,
49149
+ abi: TermMaxVaultAbi,
49150
+ allowFailure: true
49151
+ });
49152
+ const rows = [];
49153
+ vaults.forEach((address, i) => {
49154
+ const at = (k) => res[i * READS_PER_VAULT + VAULT_READS.indexOf(k)];
49155
+ const asset = addr(at("asset"));
49156
+ const totalAssets = big6(at("totalAssets"));
49157
+ if (!asset || totalAssets === 0n) return;
49158
+ rows.push({
49159
+ address,
49160
+ name: str(at("name")),
49161
+ symbol: str(at("symbol")),
49162
+ decimals: num3(at("decimals")) ?? 18,
49163
+ asset,
49164
+ totalAssets,
49165
+ totalSupply: big6(at("totalSupply")),
49166
+ annualizedInterest: big6(at("annualizedInterest")),
49167
+ accretingPrincipal: big6(at("accretingPrincipal")),
49168
+ performanceFeeRate: big6(at("performanceFeeRate")),
49169
+ aprRaw: at("apr") != null ? big6(at("apr")) : void 0,
49170
+ curator: addr(at("curator")),
49171
+ guardian: addr(at("guardian")),
49172
+ timelock: num3(at("timelock")),
49173
+ version: str(at("getVersion"))
49174
+ });
49175
+ });
49176
+ if (rows.length === 0) return {};
49177
+ const round2 = rows.flatMap((r) => [
49178
+ { address: r.asset, name: "decimals", params: [] },
49179
+ { address: r.asset, name: "balanceOf", params: [r.address] }
49180
+ ]);
49181
+ const res2 = await multicallRetry({
49182
+ chain: chainId,
49183
+ calls: round2,
49184
+ abi: Erc20DecimalsBalanceAbi,
49185
+ allowFailure: true
49186
+ });
49187
+ const out = {};
49188
+ rows.forEach((r, i) => {
49189
+ const assetDecimals = num3(res2[i * 2]) ?? r.decimals;
49190
+ const idle = big6(res2[i * 2 + 1]);
49191
+ const assetEntry = tokenList[r.asset];
49192
+ const priceKey = toOracleKey(assetEntry?.assetGroup) || toGenericPriceKey(r.asset, chainId);
49193
+ const priceUsd = prices[priceKey];
49194
+ const denominator = r.accretingPrincipal > 0n ? r.accretingPrincipal : r.totalAssets;
49195
+ const feeRate = r.performanceFeeRate;
49196
+ let supplyRate = 0;
49197
+ if (denominator > 0n && r.annualizedInterest > 0n) {
49198
+ const netAnnual = r.annualizedInterest * (DECIMAL_BASE2 - feeRate) / DECIMAL_BASE2;
49199
+ supplyRate = Number(netAnnual) / Number(denominator) * 100;
49200
+ }
49201
+ if (r.aprRaw !== void 0 && r.aprRaw > 0n) {
49202
+ supplyRate = Number(r.aprRaw) / Number(DECIMAL_BASE2) * 100;
49203
+ }
49204
+ const scale = 10 ** assetDecimals;
49205
+ const totalAssetsFormatted = Number(r.totalAssets) / scale;
49206
+ const liquidityFormatted = Number(idle) / scale;
49207
+ const convertToAssets = r.totalSupply > 0n ? (r.totalAssets * 10n ** BigInt(r.decimals) / r.totalSupply).toString() : "0";
49208
+ const entry = {
49209
+ address: r.address,
49210
+ underlying: r.asset,
49211
+ symbol: r.symbol ?? "",
49212
+ name: r.name ?? "",
49213
+ decimals: r.decimals,
49214
+ assetDecimals,
49215
+ totalAssets: r.totalAssets.toString(),
49216
+ totalSupply: r.totalSupply.toString(),
49217
+ convertToAssets,
49218
+ supplyRate,
49219
+ rewardsRate: 0,
49220
+ depositRate: supplyRate,
49221
+ fee: Number(feeRate) / Number(DECIMAL_BASE2) * 100,
49222
+ timelock: r.timelock,
49223
+ curator: r.curator,
49224
+ curatorName: curatorNameFromVaultName(r.name),
49225
+ guardian: r.guardian,
49226
+ asset: assetEntry,
49227
+ priceUsd,
49228
+ totalAssetsFormatted,
49229
+ totalAssetsUsd: priceUsd ? totalAssetsFormatted * priceUsd : 0,
49230
+ liquidity: idle.toString(),
49231
+ liquidityFormatted,
49232
+ liquidityUsd: priceUsd ? liquidityFormatted * priceUsd : 0,
49233
+ version: r.version
49234
+ };
49235
+ out[r.address] = entry;
49236
+ });
49237
+ return out;
49238
+ };
49239
+
49240
+ // src/vaults/termmax/fetchPublic.ts
49241
+ var fetchTermMaxVaults = async (chainId, multicallRetry, prices = {}, tokenList = {}) => {
49242
+ if (!termMaxConfigByChain(chainId)) return {};
49243
+ const fromApi = await fetchTermMaxVaultsFromApi(chainId, prices, tokenList);
49244
+ if (fromApi !== null) return fromApi;
49245
+ return fetchTermMaxVaultsFromChain(chainId, multicallRetry, prices, tokenList);
49246
+ };
47392
49247
 
47393
49248
  // src/vaults/lst/abis/beets.ts
47394
49249
  var BeetsStSAbi = [
@@ -47464,7 +49319,7 @@ var Multicall3BalanceAbi = [
47464
49319
  outputs: [{ type: "uint256" }]
47465
49320
  }
47466
49321
  ];
47467
- var toBigInt12 = (v) => {
49322
+ var toBigInt13 = (v) => {
47468
49323
  if (v === void 0 || v === null) return void 0;
47469
49324
  if (typeof v === "bigint") return v;
47470
49325
  if (typeof v === "number") return BigInt(v);
@@ -47488,12 +49343,12 @@ var readerBeetsStS = (entry) => ({
47488
49343
  ],
47489
49344
  abis: [TotalSupplyAbi, BeetsStSAbi, BeetsStSAbi],
47490
49345
  parse: ([supply, rate, pool]) => {
47491
- const totalSupply = toBigInt12(supply);
47492
- const exchangeRate = toBigInt12(rate);
49346
+ const totalSupply = toBigInt13(supply);
49347
+ const exchangeRate = toBigInt13(rate);
47493
49348
  if (totalSupply === void 0 || exchangeRate === void 0) {
47494
49349
  return void 0;
47495
49350
  }
47496
- const liquidity = toBigInt12(pool);
49351
+ const liquidity = toBigInt13(pool);
47497
49352
  return {
47498
49353
  totalAssets: totalSupply * exchangeRate / ONE_E187,
47499
49354
  totalSupply,
@@ -47534,12 +49389,12 @@ var readerBenqiSavax = (entry) => ({
47534
49389
  ],
47535
49390
  abis: [TotalSupplyAbi, BenqiSavaxAbi, BenqiSavaxAbi],
47536
49391
  parse: ([supply, rate, totalPooled]) => {
47537
- const totalSupply = toBigInt12(supply);
47538
- const exchangeRate = toBigInt12(rate);
49392
+ const totalSupply = toBigInt13(supply);
49393
+ const exchangeRate = toBigInt13(rate);
47539
49394
  if (totalSupply === void 0 || exchangeRate === void 0) {
47540
49395
  return void 0;
47541
49396
  }
47542
- const totalAssets = toBigInt12(totalPooled) ?? totalSupply * exchangeRate / ONE_E187;
49397
+ const totalAssets = toBigInt13(totalPooled) ?? totalSupply * exchangeRate / ONE_E187;
47543
49398
  return {
47544
49399
  totalAssets,
47545
49400
  totalSupply,
@@ -47553,7 +49408,7 @@ var readerBgtWrapper1to1 = (entry) => ({
47553
49408
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
47554
49409
  abis: [TotalSupplyAbi],
47555
49410
  parse: ([supply]) => {
47556
- const totalSupply = toBigInt12(supply);
49411
+ const totalSupply = toBigInt13(supply);
47557
49412
  if (totalSupply === void 0) return void 0;
47558
49413
  return {
47559
49414
  totalAssets: totalSupply,
@@ -47582,8 +49437,8 @@ var readerDineroBeraEth = (entry) => ({
47582
49437
  ],
47583
49438
  abis: [TotalSupplyAbi, DineroBeraEthAbi],
47584
49439
  parse: ([supply, rate]) => {
47585
- const totalSupply = toBigInt12(supply);
47586
- const exchangeRate = toBigInt12(rate);
49440
+ const totalSupply = toBigInt13(supply);
49441
+ const exchangeRate = toBigInt13(rate);
47587
49442
  if (totalSupply === void 0 || exchangeRate === void 0) {
47588
49443
  return void 0;
47589
49444
  }
@@ -47604,9 +49459,9 @@ var readerErc4626 = (entry) => ({
47604
49459
  ],
47605
49460
  abis: [Erc4626ReadAbi, TotalSupplyAbi, Erc4626ReadAbi],
47606
49461
  parse: ([assets, supply, rate]) => {
47607
- const totalAssets = toBigInt12(assets);
47608
- const totalSupply = toBigInt12(supply);
47609
- const exchangeRate = toBigInt12(rate);
49462
+ const totalAssets = toBigInt13(assets);
49463
+ const totalSupply = toBigInt13(supply);
49464
+ const exchangeRate = toBigInt13(rate);
47610
49465
  if (totalAssets === void 0 || totalSupply === void 0 || exchangeRate === void 0) {
47611
49466
  return void 0;
47612
49467
  }
@@ -47621,9 +49476,9 @@ var readerErc4626PreviewRedeem = (entry) => ({
47621
49476
  ],
47622
49477
  abis: [Erc4626PreviewRedeemAbi, TotalSupplyAbi, Erc4626PreviewRedeemAbi],
47623
49478
  parse: ([assets, supply, rate]) => {
47624
- const totalAssets = toBigInt12(assets);
47625
- const totalSupply = toBigInt12(supply);
47626
- const exchangeRate = toBigInt12(rate);
49479
+ const totalAssets = toBigInt13(assets);
49480
+ const totalSupply = toBigInt13(supply);
49481
+ const exchangeRate = toBigInt13(rate);
47627
49482
  if (totalAssets === void 0 || totalSupply === void 0 || exchangeRate === void 0) {
47628
49483
  return void 0;
47629
49484
  }
@@ -47682,16 +49537,16 @@ var readerEtherFiWeEth = (entry) => {
47682
49537
  return {
47683
49538
  calls,
47684
49539
  abis,
47685
- parse: (slice) => {
47686
- const totalSupply = toBigInt12(slice[0]);
47687
- const exchangeRate = toBigInt12(slice[1]);
49540
+ parse: (slice2) => {
49541
+ const totalSupply = toBigInt13(slice2[0]);
49542
+ const exchangeRate = toBigInt13(slice2[1]);
47688
49543
  if (totalSupply === void 0 || exchangeRate === void 0) {
47689
49544
  return void 0;
47690
49545
  }
47691
49546
  let liquidity;
47692
49547
  if (lp) {
47693
- const lpBalance = toBigInt12(slice[2]);
47694
- const locked = toBigInt12(slice[3]);
49548
+ const lpBalance = toBigInt13(slice2[2]);
49549
+ const locked = toBigInt13(slice2[3]);
47695
49550
  if (lpBalance !== void 0 && locked !== void 0) {
47696
49551
  liquidity = lpBalance > locked ? lpBalance - locked : 0n;
47697
49552
  }
@@ -47725,7 +49580,7 @@ var readerHyperbeatBeHype = (entry) => {
47725
49580
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
47726
49581
  abis: [TotalSupplyAbi],
47727
49582
  parse: ([supply]) => {
47728
- const totalSupply = toBigInt12(supply);
49583
+ const totalSupply = toBigInt13(supply);
47729
49584
  if (totalSupply === void 0) return void 0;
47730
49585
  return {
47731
49586
  totalAssets: totalSupply,
@@ -47742,8 +49597,8 @@ var readerHyperbeatBeHype = (entry) => {
47742
49597
  ],
47743
49598
  abis: [TotalSupplyAbi, HyperbeatStakingCoreAbi],
47744
49599
  parse: ([supply, rate]) => {
47745
- const totalSupply = toBigInt12(supply);
47746
- const exchangeRate = toBigInt12(rate);
49600
+ const totalSupply = toBigInt13(supply);
49601
+ const exchangeRate = toBigInt13(rate);
47747
49602
  if (totalSupply === void 0 || exchangeRate === void 0) {
47748
49603
  return void 0;
47749
49604
  }
@@ -47775,7 +49630,7 @@ var readerKelpRsEth = (entry) => {
47775
49630
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
47776
49631
  abis: [TotalSupplyAbi],
47777
49632
  parse: ([supply]) => {
47778
- const totalSupply = toBigInt12(supply);
49633
+ const totalSupply = toBigInt13(supply);
47779
49634
  if (totalSupply === void 0) return void 0;
47780
49635
  return {
47781
49636
  totalAssets: totalSupply,
@@ -47792,8 +49647,8 @@ var readerKelpRsEth = (entry) => {
47792
49647
  ],
47793
49648
  abis: [TotalSupplyAbi, KelpLrtOracleAbi],
47794
49649
  parse: ([supply, rate]) => {
47795
- const totalSupply = toBigInt12(supply);
47796
- const exchangeRate = toBigInt12(rate);
49650
+ const totalSupply = toBigInt13(supply);
49651
+ const exchangeRate = toBigInt13(rate);
47797
49652
  if (totalSupply === void 0 || exchangeRate === void 0) {
47798
49653
  return void 0;
47799
49654
  }
@@ -47825,7 +49680,7 @@ var readerKinetiqKHype = (entry) => {
47825
49680
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
47826
49681
  abis: [TotalSupplyAbi],
47827
49682
  parse: ([supply]) => {
47828
- const totalSupply = toBigInt12(supply);
49683
+ const totalSupply = toBigInt13(supply);
47829
49684
  if (totalSupply === void 0) return void 0;
47830
49685
  return {
47831
49686
  totalAssets: totalSupply,
@@ -47842,8 +49697,8 @@ var readerKinetiqKHype = (entry) => {
47842
49697
  ],
47843
49698
  abis: [TotalSupplyAbi, KinetiqStakingAccountantAbi],
47844
49699
  parse: ([supply, rate]) => {
47845
- const totalSupply = toBigInt12(supply);
47846
- const exchangeRate = toBigInt12(rate);
49700
+ const totalSupply = toBigInt13(supply);
49701
+ const exchangeRate = toBigInt13(rate);
47847
49702
  if (totalSupply === void 0 || exchangeRate === void 0) {
47848
49703
  return void 0;
47849
49704
  }
@@ -47883,12 +49738,12 @@ var readerLairStKaia = (entry) => ({
47883
49738
  ],
47884
49739
  abis: [TotalSupplyAbi, LairStKaiaAbi, LairStKaiaAbi],
47885
49740
  parse: ([supply, rate, totalStaking]) => {
47886
- const totalSupply = toBigInt12(supply);
47887
- const exchangeRate = toBigInt12(rate);
49741
+ const totalSupply = toBigInt13(supply);
49742
+ const exchangeRate = toBigInt13(rate);
47888
49743
  if (totalSupply === void 0 || exchangeRate === void 0) {
47889
49744
  return void 0;
47890
49745
  }
47891
- const totalAssets = toBigInt12(totalStaking) ?? totalSupply * exchangeRate / ONE_E187;
49746
+ const totalAssets = toBigInt13(totalStaking) ?? totalSupply * exchangeRate / ONE_E187;
47892
49747
  return {
47893
49748
  totalAssets,
47894
49749
  totalSupply,
@@ -47916,8 +49771,8 @@ var readerLidoWstEth = (entry) => ({
47916
49771
  ],
47917
49772
  abis: [TotalSupplyAbi, LidoWstEthAbi],
47918
49773
  parse: ([supply, rate]) => {
47919
- const totalSupply = toBigInt12(supply);
47920
- const exchangeRate = toBigInt12(rate);
49774
+ const totalSupply = toBigInt13(supply);
49775
+ const exchangeRate = toBigInt13(rate);
47921
49776
  if (totalSupply === void 0 || exchangeRate === void 0) {
47922
49777
  return void 0;
47923
49778
  }
@@ -47955,7 +49810,7 @@ var readerListaSlisBnb = (entry) => {
47955
49810
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
47956
49811
  abis: [TotalSupplyAbi],
47957
49812
  parse: ([supply]) => {
47958
- const totalSupply = toBigInt12(supply);
49813
+ const totalSupply = toBigInt13(supply);
47959
49814
  if (totalSupply === void 0) return void 0;
47960
49815
  return {
47961
49816
  totalAssets: totalSupply,
@@ -47973,12 +49828,12 @@ var readerListaSlisBnb = (entry) => {
47973
49828
  ],
47974
49829
  abis: [TotalSupplyAbi, ListaStakeManagerReadAbi, ListaStakeManagerReadAbi],
47975
49830
  parse: ([supply, rate, pooled]) => {
47976
- const totalSupply = toBigInt12(supply);
47977
- const exchangeRate = toBigInt12(rate);
49831
+ const totalSupply = toBigInt13(supply);
49832
+ const exchangeRate = toBigInt13(rate);
47978
49833
  if (totalSupply === void 0 || exchangeRate === void 0) {
47979
49834
  return void 0;
47980
49835
  }
47981
- const pooledBnb = toBigInt12(pooled);
49836
+ const pooledBnb = toBigInt13(pooled);
47982
49837
  const totalAssets = pooledBnb ?? totalSupply * exchangeRate / ONE_E187;
47983
49838
  return { totalAssets, totalSupply, exchangeRate };
47984
49839
  }
@@ -48004,7 +49859,7 @@ var readerMantleMEth = (entry) => {
48004
49859
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48005
49860
  abis: [TotalSupplyAbi],
48006
49861
  parse: ([supply]) => {
48007
- const totalSupply = toBigInt12(supply);
49862
+ const totalSupply = toBigInt13(supply);
48008
49863
  if (totalSupply === void 0) return void 0;
48009
49864
  return {
48010
49865
  totalAssets: totalSupply,
@@ -48021,8 +49876,8 @@ var readerMantleMEth = (entry) => {
48021
49876
  ],
48022
49877
  abis: [TotalSupplyAbi, MantleStakingAbi],
48023
49878
  parse: ([supply, rate]) => {
48024
- const totalSupply = toBigInt12(supply);
48025
- const exchangeRate = toBigInt12(rate);
49879
+ const totalSupply = toBigInt13(supply);
49880
+ const exchangeRate = toBigInt13(rate);
48026
49881
  if (totalSupply === void 0 || exchangeRate === void 0) {
48027
49882
  return void 0;
48028
49883
  }
@@ -48043,7 +49898,7 @@ var readerOffChain = (entry) => {
48043
49898
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48044
49899
  abis: [TotalSupplyAbi],
48045
49900
  parse: ([supply]) => {
48046
- const totalSupply = toBigInt12(supply);
49901
+ const totalSupply = toBigInt13(supply);
48047
49902
  if (totalSupply === void 0) return void 0;
48048
49903
  return {
48049
49904
  totalAssets: rescaleDecimals(totalSupply, shareDec, underlyingDec),
@@ -48077,7 +49932,7 @@ var readerRenzoEzEth = (entry) => {
48077
49932
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48078
49933
  abis: [TotalSupplyAbi],
48079
49934
  parse: ([supply]) => {
48080
- const totalSupply = toBigInt12(supply);
49935
+ const totalSupply = toBigInt13(supply);
48081
49936
  if (totalSupply === void 0) return void 0;
48082
49937
  return {
48083
49938
  totalAssets: totalSupply,
@@ -48094,9 +49949,9 @@ var readerRenzoEzEth = (entry) => {
48094
49949
  ],
48095
49950
  abis: [TotalSupplyAbi, RenzoRestakeManagerAbi],
48096
49951
  parse: ([supply, tvls]) => {
48097
- const totalSupply = toBigInt12(supply);
49952
+ const totalSupply = toBigInt13(supply);
48098
49953
  if (totalSupply === void 0 || totalSupply === 0n) return void 0;
48099
- const totalTvl = Array.isArray(tvls) && tvls.length >= 3 ? toBigInt12(tvls[2]) : void 0;
49954
+ const totalTvl = Array.isArray(tvls) && tvls.length >= 3 ? toBigInt13(tvls[2]) : void 0;
48100
49955
  if (totalTvl === void 0) return void 0;
48101
49956
  return {
48102
49957
  totalAssets: totalTvl,
@@ -48149,13 +50004,13 @@ var readerRocketReth = (entry) => {
48149
50004
  return {
48150
50005
  calls,
48151
50006
  abis,
48152
- parse: (slice) => {
48153
- const totalSupply = toBigInt12(slice[0]);
48154
- const exchangeRate = toBigInt12(slice[1]);
50007
+ parse: (slice2) => {
50008
+ const totalSupply = toBigInt13(slice2[0]);
50009
+ const exchangeRate = toBigInt13(slice2[1]);
48155
50010
  if (totalSupply === void 0 || exchangeRate === void 0) {
48156
50011
  return void 0;
48157
50012
  }
48158
- const liquidity = depositPool ? toBigInt12(slice[2]) : void 0;
50013
+ const liquidity = depositPool ? toBigInt13(slice2[2]) : void 0;
48159
50014
  return {
48160
50015
  totalAssets: totalSupply * exchangeRate / ONE_E187,
48161
50016
  totalSupply,
@@ -48194,7 +50049,7 @@ var readerStaderEthx = (entry) => {
48194
50049
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48195
50050
  abis: [TotalSupplyAbi],
48196
50051
  parse: ([supply]) => {
48197
- const totalSupply = toBigInt12(supply);
50052
+ const totalSupply = toBigInt13(supply);
48198
50053
  if (totalSupply === void 0) return void 0;
48199
50054
  return {
48200
50055
  totalAssets: totalSupply,
@@ -48211,8 +50066,8 @@ var readerStaderEthx = (entry) => {
48211
50066
  ],
48212
50067
  abis: [TotalSupplyAbi, StaderEthxAbi],
48213
50068
  parse: ([supply, rate]) => {
48214
- const totalSupply = toBigInt12(supply);
48215
- const exchangeRate = toBigInt12(rate);
50069
+ const totalSupply = toBigInt13(supply);
50070
+ const exchangeRate = toBigInt13(rate);
48216
50071
  if (totalSupply === void 0 || exchangeRate === void 0) {
48217
50072
  return void 0;
48218
50073
  }
@@ -48240,10 +50095,10 @@ var readerStaderMaticX = (entry) => {
48240
50095
  ],
48241
50096
  abis: [TotalSupplyAbi, StaderMaticXAbi],
48242
50097
  parse: ([supply, tup]) => {
48243
- const totalSupply = toBigInt12(supply);
50098
+ const totalSupply = toBigInt13(supply);
48244
50099
  if (!Array.isArray(tup) || tup.length < 3) return void 0;
48245
- const amountInMatic = toBigInt12(tup[0]);
48246
- const totalPooledMatic = toBigInt12(tup[2]);
50100
+ const amountInMatic = toBigInt13(tup[0]);
50101
+ const totalPooledMatic = toBigInt13(tup[2]);
48247
50102
  if (totalSupply === void 0 || amountInMatic === void 0) {
48248
50103
  return void 0;
48249
50104
  }
@@ -48276,7 +50131,7 @@ var readerStakeWiseOsEth = (entry) => {
48276
50131
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48277
50132
  abis: [TotalSupplyAbi],
48278
50133
  parse: ([supply]) => {
48279
- const totalSupply = toBigInt12(supply);
50134
+ const totalSupply = toBigInt13(supply);
48280
50135
  if (totalSupply === void 0) return void 0;
48281
50136
  return {
48282
50137
  totalAssets: totalSupply,
@@ -48293,8 +50148,8 @@ var readerStakeWiseOsEth = (entry) => {
48293
50148
  ],
48294
50149
  abis: [TotalSupplyAbi, StakeWiseOsTokenAbi],
48295
50150
  parse: ([supply, rate]) => {
48296
- const totalSupply = toBigInt12(supply);
48297
- const exchangeRate = toBigInt12(rate);
50151
+ const totalSupply = toBigInt13(supply);
50152
+ const exchangeRate = toBigInt13(rate);
48298
50153
  if (totalSupply === void 0 || exchangeRate === void 0) {
48299
50154
  return void 0;
48300
50155
  }
@@ -48326,7 +50181,7 @@ var readerStCelo = (entry) => {
48326
50181
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48327
50182
  abis: [TotalSupplyAbi],
48328
50183
  parse: ([supply]) => {
48329
- const totalSupply = toBigInt12(supply);
50184
+ const totalSupply = toBigInt13(supply);
48330
50185
  if (totalSupply === void 0) return void 0;
48331
50186
  return {
48332
50187
  totalAssets: totalSupply,
@@ -48343,8 +50198,8 @@ var readerStCelo = (entry) => {
48343
50198
  ],
48344
50199
  abis: [TotalSupplyAbi, StCeloManagerAbi],
48345
50200
  parse: ([supply, rate]) => {
48346
- const totalSupply = toBigInt12(supply);
48347
- const exchangeRate = toBigInt12(rate);
50201
+ const totalSupply = toBigInt13(supply);
50202
+ const exchangeRate = toBigInt13(rate);
48348
50203
  if (totalSupply === void 0 || exchangeRate === void 0) {
48349
50204
  return void 0;
48350
50205
  }
@@ -48376,8 +50231,8 @@ var readerSwellGetRate = (entry) => ({
48376
50231
  ],
48377
50232
  abis: [TotalSupplyAbi, SwellGetRateAbi],
48378
50233
  parse: ([supply, rate]) => {
48379
- const totalSupply = toBigInt12(supply);
48380
- const exchangeRate = toBigInt12(rate);
50234
+ const totalSupply = toBigInt13(supply);
50235
+ const exchangeRate = toBigInt13(rate);
48381
50236
  if (totalSupply === void 0 || exchangeRate === void 0) {
48382
50237
  return void 0;
48383
50238
  }
@@ -48408,7 +50263,7 @@ var readerValantisWstHype = (entry) => {
48408
50263
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48409
50264
  abis: [TotalSupplyAbi],
48410
50265
  parse: ([supply]) => {
48411
- const totalSupply = toBigInt12(supply);
50266
+ const totalSupply = toBigInt13(supply);
48412
50267
  if (totalSupply === void 0) return void 0;
48413
50268
  return {
48414
50269
  totalAssets: totalSupply,
@@ -48425,8 +50280,8 @@ var readerValantisWstHype = (entry) => {
48425
50280
  ],
48426
50281
  abis: [TotalSupplyAbi, ValantisStHypeAbi],
48427
50282
  parse: ([supply, rate]) => {
48428
- const totalSupply = toBigInt12(supply);
48429
- const exchangeRate = toBigInt12(rate);
50283
+ const totalSupply = toBigInt13(supply);
50284
+ const exchangeRate = toBigInt13(rate);
48430
50285
  if (totalSupply === void 0 || exchangeRate === void 0) {
48431
50286
  return void 0;
48432
50287
  }
@@ -48460,7 +50315,7 @@ var readerVedaAccountant = (entry) => {
48460
50315
  calls: [{ address: entry.address, name: "totalSupply", params: [] }],
48461
50316
  abis: [TotalSupplyAbi],
48462
50317
  parse: ([supply]) => {
48463
- const totalSupply = toBigInt12(supply);
50318
+ const totalSupply = toBigInt13(supply);
48464
50319
  if (totalSupply === void 0) return void 0;
48465
50320
  return {
48466
50321
  totalAssets: rescaleDecimals(totalSupply, shareDec, underlyingDec),
@@ -48478,8 +50333,8 @@ var readerVedaAccountant = (entry) => {
48478
50333
  ],
48479
50334
  abis: [TotalSupplyAbi, VedaAccountantGetRateAbi],
48480
50335
  parse: ([supply, rate]) => {
48481
- const totalSupply = toBigInt12(supply);
48482
- const rawRate = toBigInt12(rate);
50336
+ const totalSupply = toBigInt13(supply);
50337
+ const rawRate = toBigInt13(rate);
48483
50338
  if (totalSupply === void 0 || rawRate === void 0) return void 0;
48484
50339
  const exchangeRate = rawRate * scale;
48485
50340
  return {
@@ -48514,8 +50369,8 @@ var readerAnkrRatio = (entry) => ({
48514
50369
  ],
48515
50370
  abis: [TotalSupplyAbi, AnkrRatioAbi],
48516
50371
  parse: ([supply, ratio]) => {
48517
- const totalSupply = toBigInt12(supply);
48518
- const r = toBigInt12(ratio);
50372
+ const totalSupply = toBigInt13(supply);
50373
+ const r = toBigInt13(ratio);
48519
50374
  if (totalSupply === void 0 || r === void 0 || r === 0n) {
48520
50375
  return void 0;
48521
50376
  }
@@ -48558,8 +50413,8 @@ var readerCoreEarnRate = (entry) => {
48558
50413
  ],
48559
50414
  abis: [CoreEarnRateAbi, TotalSupplyAbi],
48560
50415
  parse: ([rate, supply]) => {
48561
- const r = toBigInt12(rate);
48562
- const totalSupply = toBigInt12(supply);
50416
+ const r = toBigInt13(rate);
50417
+ const totalSupply = toBigInt13(supply);
48563
50418
  if (r === void 0 || r === 0n || totalSupply === void 0) {
48564
50419
  return void 0;
48565
50420
  }
@@ -48580,8 +50435,8 @@ var readerCoreStakedRatio = (entry) => {
48580
50435
  ],
48581
50436
  abis: [CoreTotalStakedAbi, TotalSupplyAbi],
48582
50437
  parse: ([staked, supply]) => {
48583
- const totalStaked = toBigInt12(staked);
48584
- const totalSupply = toBigInt12(supply);
50438
+ const totalStaked = toBigInt13(staked);
50439
+ const totalSupply = toBigInt13(supply);
48585
50440
  if (totalStaked === void 0 || totalSupply === void 0 || totalSupply === 0n) {
48586
50441
  return void 0;
48587
50442
  }
@@ -48625,12 +50480,12 @@ var readerStellaStDot = (entry) => ({
48625
50480
  ],
48626
50481
  abis: [TotalSupplyAbi, StellaStDotAbi, StellaStDotAbi],
48627
50482
  parse: ([supply, rate, pooled]) => {
48628
- const totalSupply = toBigInt12(supply);
48629
- const exchangeRate = toBigInt12(rate);
50483
+ const totalSupply = toBigInt13(supply);
50484
+ const exchangeRate = toBigInt13(rate);
48630
50485
  if (totalSupply === void 0 || exchangeRate === void 0) {
48631
50486
  return void 0;
48632
50487
  }
48633
- const totalAssets = toBigInt12(pooled) ?? totalSupply * exchangeRate / ONE_E187;
50488
+ const totalAssets = toBigInt13(pooled) ?? totalSupply * exchangeRate / ONE_E187;
48634
50489
  return {
48635
50490
  totalAssets,
48636
50491
  totalSupply,
@@ -48665,8 +50520,8 @@ var readerKintsuSMon = (entry) => ({
48665
50520
  ],
48666
50521
  abis: [KintsuSMonAbi, KintsuSMonAbi],
48667
50522
  parse: ([pooled, shares]) => {
48668
- const totalAssets = toBigInt12(pooled);
48669
- const totalSupply = toBigInt12(shares);
50523
+ const totalAssets = toBigInt13(pooled);
50524
+ const totalSupply = toBigInt13(shares);
48670
50525
  if (totalAssets === void 0 || totalSupply === void 0) return void 0;
48671
50526
  const exchangeRate = totalSupply > 0n ? totalAssets * ONE_E187 / totalSupply : ONE_E187;
48672
50527
  return { totalAssets, totalSupply, exchangeRate };
@@ -49187,7 +51042,7 @@ var fetchLstShareTokens = async (chainId, multicallRetry, prices = {}, tokenList
49187
51042
  const validatorsByAddress = new Map(validatorEntries);
49188
51043
  const idleByAddress = /* @__PURE__ */ new Map();
49189
51044
  idleEntries.forEach((e, i) => {
49190
- const bal = toBigInt12(idleResults[i]);
51045
+ const bal = toBigInt13(idleResults[i]);
49191
51046
  if (bal !== void 0) idleByAddress.set(e.address.toLowerCase(), bal);
49192
51047
  });
49193
51048
  const rawResults = new Array(allCalls.length);
@@ -49202,9 +51057,9 @@ var fetchLstShareTokens = async (chainId, multicallRetry, prices = {}, tokenList
49202
51057
  for (let i = 0; i < entries.length; i++) {
49203
51058
  const entry = entries[i];
49204
51059
  const reader = readers[i];
49205
- const slice = rawResults.slice(cursor, cursor + reader.calls.length);
51060
+ const slice2 = rawResults.slice(cursor, cursor + reader.calls.length);
49206
51061
  cursor += reader.calls.length;
49207
- const state = reader.parse(slice);
51062
+ const state = reader.parse(slice2);
49208
51063
  if (!state) continue;
49209
51064
  const addressLc = entry.address.toLowerCase();
49210
51065
  const underlyingLc = entry.underlying.toLowerCase();
@@ -49317,7 +51172,7 @@ var BeetsStSWithdrawalAbi = [
49317
51172
  ];
49318
51173
 
49319
51174
  // src/vaults/lst/withdrawals/readers/shared.ts
49320
- var toBigInt13 = (v) => {
51175
+ var toBigInt14 = (v) => {
49321
51176
  if (v === void 0 || v === null) return void 0;
49322
51177
  if (typeof v === "bigint") return v;
49323
51178
  if (typeof v === "number") return BigInt(v);
@@ -49332,7 +51187,7 @@ var toBigInt13 = (v) => {
49332
51187
  return void 0;
49333
51188
  };
49334
51189
  var toNumber = (v) => {
49335
- const b = toBigInt13(v);
51190
+ const b = toBigInt14(v);
49336
51191
  if (b === void 0) return void 0;
49337
51192
  if (b > BigInt(Number.MAX_SAFE_INTEGER)) return void 0;
49338
51193
  return Number(b);
@@ -49369,7 +51224,7 @@ var readerBeets = {
49369
51224
  const out = [];
49370
51225
  for (let i = 0; i < reqs.length; i++) {
49371
51226
  const r = reqs[i];
49372
- const amount = toBigInt13(r.assetAmount);
51227
+ const amount = toBigInt14(r.assetAmount);
49373
51228
  const ts = toNumber(r.requestTimestamp);
49374
51229
  const isWithdrawn = Boolean(r.isWithdrawn);
49375
51230
  if (amount === void 0 || ts === void 0) continue;
@@ -49461,13 +51316,13 @@ var readerBeHype = {
49461
51316
  const q = stage2[i * 2];
49462
51317
  const canClaim = Boolean(stage2[i * 2 + 1]);
49463
51318
  if (!q) continue;
49464
- const hypeAmount = Array.isArray(q) ? toBigInt13(q[2]) : toBigInt13(q.hypeAmount);
51319
+ const hypeAmount = Array.isArray(q) ? toBigInt14(q[2]) : toBigInt14(q.hypeAmount);
49465
51320
  if (hypeAmount === void 0) continue;
49466
51321
  out.push({
49467
51322
  lst: entry.lst,
49468
51323
  brand: entry.brand,
49469
51324
  symbol: entry.symbol,
49470
- requestId: String(toBigInt13(ids[i]) ?? i),
51325
+ requestId: String(toBigInt14(ids[i]) ?? i),
49471
51326
  amountUnderlying: hypeAmount.toString(),
49472
51327
  status: canClaim ? "claimable" : "pending"
49473
51328
  });
@@ -49570,7 +51425,7 @@ var readerBenqi = {
49570
51425
  for (let i = 0; i < reqs.length; i++) {
49571
51426
  const r = reqs[i];
49572
51427
  const startedAt = toNumber(r.startedAt);
49573
- const shareAmount = toBigInt13(r.shareAmount);
51428
+ const shareAmount = toBigInt14(r.shareAmount);
49574
51429
  if (startedAt === void 0 || shareAmount === void 0) continue;
49575
51430
  const readyAt = startedAt + cooldown;
49576
51431
  const expiresAt = readyAt + claimWindow;
@@ -49633,8 +51488,8 @@ var readerBeraPaw = {
49633
51488
  }
49634
51489
  const pos = res[0];
49635
51490
  if (!pos) return [];
49636
- const queued = Array.isArray(pos) ? toBigInt13(pos[0]) : toBigInt13(pos.queued);
49637
- const available = Array.isArray(pos) ? toBigInt13(pos[1]) : toBigInt13(pos.available);
51491
+ const queued = Array.isArray(pos) ? toBigInt14(pos[0]) : toBigInt14(pos.queued);
51492
+ const available = Array.isArray(pos) ? toBigInt14(pos[1]) : toBigInt14(pos.available);
49638
51493
  const out = [];
49639
51494
  if (available !== void 0 && available > 0n) {
49640
51495
  out.push({
@@ -49716,7 +51571,7 @@ var readerIbera = {
49716
51571
  return [];
49717
51572
  }
49718
51573
  const length = toNumber(stage1[0]) ?? 0;
49719
- const frontier = toBigInt13(stage1[1]) ?? 0n;
51574
+ const frontier = toBigInt14(stage1[1]) ?? 0n;
49720
51575
  if (length === 0) return [];
49721
51576
  const start = length > MAX_SCAN ? length - MAX_SCAN : 0;
49722
51577
  const ids = Array.from({ length: length - start }, (_3, k) => start + k);
@@ -49740,7 +51595,7 @@ var readerIbera = {
49740
51595
  const r = stage2[k];
49741
51596
  if (!r) continue;
49742
51597
  const receiver = Array.isArray(r) ? r[2] : r.receiver;
49743
- const amount = Array.isArray(r) ? toBigInt13(r[3]) : toBigInt13(r.amount);
51598
+ const amount = Array.isArray(r) ? toBigInt14(r[3]) : toBigInt14(r.amount);
49744
51599
  if (typeof receiver !== "string" || receiver.toLowerCase() !== target || amount === void 0 || amount === 0n) {
49745
51600
  continue;
49746
51601
  }
@@ -49813,7 +51668,7 @@ var readerPrimeStaking = {
49813
51668
  return [];
49814
51669
  }
49815
51670
  const length = toNumber(stage1[0]) ?? 0;
49816
- const frontier = toBigInt13(stage1[1]) ?? 0n;
51671
+ const frontier = toBigInt14(stage1[1]) ?? 0n;
49817
51672
  if (length === 0) return [];
49818
51673
  const start = length > MAX_SCAN2 ? length - MAX_SCAN2 : 0;
49819
51674
  const ids = Array.from({ length: length - start }, (_3, k) => start + k);
@@ -49837,7 +51692,7 @@ var readerPrimeStaking = {
49837
51692
  const r = stage2[k];
49838
51693
  if (!r) continue;
49839
51694
  const receiver = Array.isArray(r) ? r[1] : r.receiver;
49840
- const assets = Array.isArray(r) ? toBigInt13(r[3]) : toBigInt13(r.assets);
51695
+ const assets = Array.isArray(r) ? toBigInt14(r[3]) : toBigInt14(r.assets);
49841
51696
  const processed = Array.isArray(r) ? r[4] : r.processed;
49842
51697
  if (typeof receiver !== "string" || receiver.toLowerCase() !== target || assets === void 0 || assets === 0n) {
49843
51698
  continue;
@@ -49907,8 +51762,8 @@ var readerErc7540 = {
49907
51762
  ],
49908
51763
  abi: [Erc7540Abi, Erc7540Abi]
49909
51764
  });
49910
- const pending = toBigInt13(stage1[0]) ?? 0n;
49911
- const claimable = toBigInt13(stage1[1]) ?? 0n;
51765
+ const pending = toBigInt14(stage1[0]) ?? 0n;
51766
+ const claimable = toBigInt14(stage1[1]) ?? 0n;
49912
51767
  const out = [];
49913
51768
  if (claimable > 0n) {
49914
51769
  const stage2 = await multicallRetry({
@@ -49922,7 +51777,7 @@ var readerErc7540 = {
49922
51777
  ],
49923
51778
  abi: [Erc7540Abi]
49924
51779
  });
49925
- const amount = toBigInt13(stage2[0]) ?? claimable;
51780
+ const amount = toBigInt14(stage2[0]) ?? claimable;
49926
51781
  out.push({
49927
51782
  lst: entry.lst,
49928
51783
  brand: entry.brand,
@@ -49976,11 +51831,11 @@ var readerEthenaCooldown = {
49976
51831
  let cooldownEnd;
49977
51832
  let amount;
49978
51833
  if (Array.isArray(cell)) {
49979
- cooldownEnd = toBigInt13(cell[0]);
49980
- amount = toBigInt13(cell[1]);
51834
+ cooldownEnd = toBigInt14(cell[0]);
51835
+ amount = toBigInt14(cell[1]);
49981
51836
  } else if (cell && typeof cell === "object") {
49982
- cooldownEnd = toBigInt13(cell.cooldownEnd);
49983
- amount = toBigInt13(cell.underlyingAmount);
51837
+ cooldownEnd = toBigInt14(cell.cooldownEnd);
51838
+ amount = toBigInt14(cell.underlyingAmount);
49984
51839
  }
49985
51840
  if (!amount || amount === 0n) return [];
49986
51841
  const readyAt = Number(cooldownEnd ?? 0n);
@@ -50075,7 +51930,7 @@ var readerEtherFi = {
50075
51930
  calls: enumCalls,
50076
51931
  abi: enumCalls.map(() => EtherFiWithdrawRequestAbi)
50077
51932
  });
50078
- const ids = stage2.map(toBigInt13).filter((v) => v !== void 0);
51933
+ const ids = stage2.map(toBigInt14).filter((v) => v !== void 0);
50079
51934
  if (ids.length === 0) return [];
50080
51935
  const detailCalls = ids.flatMap((id) => [
50081
51936
  { address: entry.withdrawalContract, name: "getRequest", params: [id] },
@@ -50095,7 +51950,7 @@ var readerEtherFi = {
50095
51950
  const isValid = Boolean(stage3[i * 3 + 2]);
50096
51951
  if (!req) continue;
50097
51952
  if (!isValid) continue;
50098
- const amount = toBigInt13(req.amountOfEEth);
51953
+ const amount = toBigInt14(req.amountOfEEth);
50099
51954
  if (amount === void 0) continue;
50100
51955
  out.push({
50101
51956
  lst: entry.lst,
@@ -50190,7 +52045,7 @@ var readerKelp = {
50190
52045
  }
50191
52046
  ],
50192
52047
  abi: [KelpWithdrawalManagerAbi]
50193
- }).then((res) => toBigInt13(res[0]) ?? 0n)
52048
+ }).then((res) => toBigInt14(res[0]) ?? 0n)
50194
52049
  ]);
50195
52050
  lengths = storageReads;
50196
52051
  currentBlock = block;
@@ -50220,9 +52075,9 @@ var readerKelp = {
50220
52075
  for (let i = 0; i < detailCalls.length; i++) {
50221
52076
  const r = stage2[i];
50222
52077
  if (!r) continue;
50223
- const expected = Array.isArray(r) ? toBigInt13(r[1]) : toBigInt13(r.expectedAssetAmount);
50224
- const startBlock = Array.isArray(r) ? toBigInt13(r[2]) : toBigInt13(r.withdrawalStartBlock);
50225
- const nonce = Array.isArray(r) ? toBigInt13(r[3]) : toBigInt13(r.userNonce);
52078
+ const expected = Array.isArray(r) ? toBigInt14(r[1]) : toBigInt14(r.expectedAssetAmount);
52079
+ const startBlock = Array.isArray(r) ? toBigInt14(r[2]) : toBigInt14(r.withdrawalStartBlock);
52080
+ const nonce = Array.isArray(r) ? toBigInt14(r[3]) : toBigInt14(r.userNonce);
50226
52081
  if (expected === void 0 || startBlock === void 0) continue;
50227
52082
  const claimable = currentBlock >= startBlock + delayBlocks;
50228
52083
  out.push({
@@ -50299,7 +52154,7 @@ var readerLido = {
50299
52154
  abi: [LidoWithdrawalQueueAbi, LidoWithdrawalQueueAbi]
50300
52155
  });
50301
52156
  const ids = stage1[0];
50302
- const frontier = toBigInt13(stage1[1]) ?? 0n;
52157
+ const frontier = toBigInt14(stage1[1]) ?? 0n;
50303
52158
  if (!Array.isArray(ids) || ids.length === 0) return [];
50304
52159
  const stage2 = await multicallRetry({
50305
52160
  chain: chainId,
@@ -50316,10 +52171,10 @@ var readerLido = {
50316
52171
  if (!Array.isArray(statuses)) return [];
50317
52172
  const out = [];
50318
52173
  for (let i = 0; i < ids.length; i++) {
50319
- const id = toBigInt13(ids[i]);
52174
+ const id = toBigInt14(ids[i]);
50320
52175
  const s = statuses[i];
50321
52176
  if (id === void 0 || !s) continue;
50322
- const amountOfStETH = toBigInt13(s.amountOfStETH);
52177
+ const amountOfStETH = toBigInt14(s.amountOfStETH);
50323
52178
  const isFinalized = Boolean(s.isFinalized);
50324
52179
  const isClaimed = Boolean(s.isClaimed);
50325
52180
  if (amountOfStETH === void 0) continue;
@@ -50428,11 +52283,11 @@ var readerLista = {
50428
52283
  const status = stage2[i];
50429
52284
  if (!status) continue;
50430
52285
  const isClaimable = Array.isArray(status) ? Boolean(status[0]) : Boolean(status._isClaimable);
50431
- const bnbAmount = Array.isArray(status) ? toBigInt13(status[1]) : toBigInt13(status._amount);
50432
- const snbnbAmount = Array.isArray(req) ? toBigInt13(req[1]) : toBigInt13(req?.amountInSnBnb);
52286
+ const bnbAmount = Array.isArray(status) ? toBigInt14(status[1]) : toBigInt14(status._amount);
52287
+ const snbnbAmount = Array.isArray(req) ? toBigInt14(req[1]) : toBigInt14(req?.amountInSnBnb);
50433
52288
  const amount = bnbAmount ?? snbnbAmount;
50434
52289
  if (amount === void 0) continue;
50435
- const uuid = Array.isArray(req) ? toBigInt13(req[0]) : toBigInt13(req?.uuid);
52290
+ const uuid = Array.isArray(req) ? toBigInt14(req[0]) : toBigInt14(req?.uuid);
50436
52291
  out.push({
50437
52292
  lst: entry.lst,
50438
52293
  brand: entry.brand,
@@ -50517,7 +52372,7 @@ var readerRenzo = {
50517
52372
  for (let i = 0; i < count; i++) {
50518
52373
  const tup = stage2[i];
50519
52374
  if (!Array.isArray(tup) || tup.length < 5) continue;
50520
- const amountToRedeem = toBigInt13(tup[2]);
52375
+ const amountToRedeem = toBigInt14(tup[2]);
50521
52376
  const createdAt = toNumber(tup[4]);
50522
52377
  if (amountToRedeem === void 0 || createdAt === void 0) continue;
50523
52378
  const readyAt = createdAt + cooldown;
@@ -50590,9 +52445,9 @@ var readerStaderEthx2 = {
50590
52445
  ]
50591
52446
  });
50592
52447
  const ids = stage1[0];
50593
- const frontier = toBigInt13(stage1[1]) ?? 0n;
52448
+ const frontier = toBigInt14(stage1[1]) ?? 0n;
50594
52449
  if (!Array.isArray(ids) || ids.length === 0) return [];
50595
- const idBigInts = ids.map(toBigInt13).filter((v) => v !== void 0);
52450
+ const idBigInts = ids.map(toBigInt14).filter((v) => v !== void 0);
50596
52451
  const detailCalls = idBigInts.map((id) => ({
50597
52452
  address: entry.withdrawalContract,
50598
52453
  name: "userWithdrawRequests",
@@ -50608,8 +52463,8 @@ var readerStaderEthx2 = {
50608
52463
  const id = idBigInts[i];
50609
52464
  const tup = stage2[i];
50610
52465
  if (!Array.isArray(tup) || tup.length < 5) continue;
50611
- const ethExpected = toBigInt13(tup[2]) ?? 0n;
50612
- const ethFinalized = toBigInt13(tup[3]) ?? 0n;
52466
+ const ethExpected = toBigInt14(tup[2]) ?? 0n;
52467
+ const ethFinalized = toBigInt14(tup[3]) ?? 0n;
50613
52468
  const isFinalized = id < frontier && ethFinalized > 0n;
50614
52469
  const queuePosition = isFinalized ? 0 : Number(id - frontier);
50615
52470
  out.push({
@@ -50688,13 +52543,13 @@ var readerStaderMaticX2 = {
50688
52543
  });
50689
52544
  const arr = stage1[0];
50690
52545
  if (!Array.isArray(arr)) return [];
50691
- const currentEpoch = stakeManager ? toBigInt13(stage1[1]) ?? 0n : 0n;
50692
- const delay = stakeManager ? toBigInt13(stage1[2]) ?? 0n : 0n;
52546
+ const currentEpoch = stakeManager ? toBigInt14(stage1[1]) ?? 0n : 0n;
52547
+ const delay = stakeManager ? toBigInt14(stage1[2]) ?? 0n : 0n;
50693
52548
  const out = [];
50694
52549
  for (let i = 0; i < arr.length; i++) {
50695
52550
  const r = arr[i];
50696
- const amount = toBigInt13(r.amount) ?? 0n;
50697
- const requestEpoch = toBigInt13(r.requestEpoch);
52551
+ const amount = toBigInt14(r.amount) ?? 0n;
52552
+ const requestEpoch = toBigInt14(r.requestEpoch);
50698
52553
  if (requestEpoch === void 0) continue;
50699
52554
  const ready = stakeManager ? currentEpoch >= requestEpoch + delay : false;
50700
52555
  out.push({
@@ -50781,9 +52636,9 @@ var readerMantle = {
50781
52636
  if (typeof requester === "string" && requester.toLowerCase() !== lcUser) {
50782
52637
  continue;
50783
52638
  }
50784
- const ethRequested = Array.isArray(detail) ? toBigInt13(detail[3]) : toBigInt13(detail.ethRequested);
52639
+ const ethRequested = Array.isArray(detail) ? toBigInt14(detail[3]) : toBigInt14(detail.ethRequested);
50785
52640
  const isFinalized = Array.isArray(info) ? Boolean(info[0]) : Boolean(info.isFinalized);
50786
- const claimable = Array.isArray(info) ? toBigInt13(info[1]) : toBigInt13(info.claimableAmount);
52641
+ const claimable = Array.isArray(info) ? toBigInt14(info[1]) : toBigInt14(info.claimableAmount);
50787
52642
  if (ethRequested === void 0) continue;
50788
52643
  out.push({
50789
52644
  lst: entry.lst,
@@ -50862,8 +52717,8 @@ var readerPuffer = {
50862
52717
  calls,
50863
52718
  abi: calls.map(() => PufferWithdrawalManagerAbi)
50864
52719
  });
50865
- const finalizedBatch = toBigInt13(results[detailCalls.length]) ?? 0n;
50866
- const batchSize = toBigInt13(results[detailCalls.length + 1]) ?? 0n;
52720
+ const finalizedBatch = toBigInt14(results[detailCalls.length]) ?? 0n;
52721
+ const batchSize = toBigInt14(results[detailCalls.length + 1]) ?? 0n;
50867
52722
  const out = [];
50868
52723
  const lcUser = user.toLowerCase();
50869
52724
  for (let i = 0; i < ids.length; i++) {
@@ -50873,7 +52728,7 @@ var readerPuffer = {
50873
52728
  if (typeof recipient === "string" && recipient.toLowerCase() !== lcUser) {
50874
52729
  continue;
50875
52730
  }
50876
- const pufETHAmount = Array.isArray(d) ? toBigInt13(d[0]) : toBigInt13(d.pufETHAmount);
52731
+ const pufETHAmount = Array.isArray(d) ? toBigInt14(d[0]) : toBigInt14(d.pufETHAmount);
50877
52732
  if (pufETHAmount === void 0) continue;
50878
52733
  const batchIdx = batchSize > 0n ? ids[i] / batchSize : 0n;
50879
52734
  const claimable = batchIdx <= finalizedBatch;
@@ -50971,7 +52826,7 @@ var readerKinetiq = {
50971
52826
  for (let i = 0; i < count; i++) {
50972
52827
  const r = stage2[i];
50973
52828
  if (!r) continue;
50974
- const hypeAmount = Array.isArray(r) ? toBigInt13(r[0]) : toBigInt13(r.hypeAmount);
52829
+ const hypeAmount = Array.isArray(r) ? toBigInt14(r[0]) : toBigInt14(r.hypeAmount);
50975
52830
  const timestamp = Array.isArray(r) ? toNumber(r[4]) : toNumber(r.timestamp);
50976
52831
  if (hypeAmount === void 0 || hypeAmount === 0n || timestamp === void 0) {
50977
52832
  continue;
@@ -51099,7 +52954,7 @@ var readerStakeWise = {
51099
52954
  const claimedByIdx = /* @__PURE__ */ new Map();
51100
52955
  for (let i = 0; i < onChainChecks.length; i++) {
51101
52956
  const cell = checkResults[i];
51102
- const claimed = Array.isArray(cell) ? toBigInt13(cell[2]) : toBigInt13(cell?.claimedAssets);
52957
+ const claimed = Array.isArray(cell) ? toBigInt14(cell[2]) : toBigInt14(cell?.claimedAssets);
51103
52958
  if (claimed !== void 0 && claimed > 0n) {
51104
52959
  claimedByIdx.set(onChainChecks[i].idx, claimed);
51105
52960
  }
@@ -51107,7 +52962,7 @@ var readerStakeWise = {
51107
52962
  const out = [];
51108
52963
  for (let i = 0; i < requests.length; i++) {
51109
52964
  const r = requests[i];
51110
- const amount = toBigInt13(r.totalAssets) ?? 0n;
52965
+ const amount = toBigInt14(r.totalAssets) ?? 0n;
51111
52966
  const onChainClaimed = claimedByIdx.get(i);
51112
52967
  const claimable = onChainClaimed !== void 0 || r.isClaimable;
51113
52968
  out.push({
@@ -51164,7 +53019,7 @@ var readerStCelo2 = {
51164
53019
  const timestamps = cell[1] ?? [];
51165
53020
  const out = [];
51166
53021
  for (let i = 0; i < values.length; i++) {
51167
- const amount = toBigInt13(values[i]);
53022
+ const amount = toBigInt14(values[i]);
51168
53023
  const readyAt = toNumber(timestamps[i]);
51169
53024
  if (amount === void 0 || readyAt === void 0) continue;
51170
53025
  out.push({
@@ -51209,11 +53064,11 @@ var readerStellaUnbond = {
51209
53064
  let waiting;
51210
53065
  let unbonded;
51211
53066
  if (Array.isArray(cell)) {
51212
- waiting = toBigInt13(cell[0]);
51213
- unbonded = toBigInt13(cell[1]);
53067
+ waiting = toBigInt14(cell[0]);
53068
+ unbonded = toBigInt14(cell[1]);
51214
53069
  } else if (cell && typeof cell === "object") {
51215
- waiting = toBigInt13(cell.waiting);
51216
- unbonded = toBigInt13(cell.unbonded);
53070
+ waiting = toBigInt14(cell.waiting);
53071
+ unbonded = toBigInt14(cell.unbonded);
51217
53072
  }
51218
53073
  const out = [];
51219
53074
  if (unbonded && unbonded > 0n) {
@@ -51303,7 +53158,7 @@ var readerSwell = {
51303
53158
  abi: [SwellRswExitAbi, SwellRswExitAbi]
51304
53159
  });
51305
53160
  const count = toNumber(stage1[0]) ?? 0;
51306
- const lastProcessed = toBigInt13(stage1[1]) ?? 0n;
53161
+ const lastProcessed = toBigInt14(stage1[1]) ?? 0n;
51307
53162
  if (count === 0) return [];
51308
53163
  const enumCalls = Array.from({ length: count }, (_3, i) => ({
51309
53164
  address: entry.withdrawalContract,
@@ -51315,7 +53170,7 @@ var readerSwell = {
51315
53170
  calls: enumCalls,
51316
53171
  abi: enumCalls.map(() => SwellRswExitAbi)
51317
53172
  });
51318
- const ids = stage2.map(toBigInt13).filter((v) => v !== void 0);
53173
+ const ids = stage2.map(toBigInt14).filter((v) => v !== void 0);
51319
53174
  if (ids.length === 0) return [];
51320
53175
  const detailCalls = ids.map((id) => ({
51321
53176
  address: entry.withdrawalContract,
@@ -51332,7 +53187,7 @@ var readerSwell = {
51332
53187
  const id = ids[i];
51333
53188
  const r = stage3[i];
51334
53189
  if (!r) continue;
51335
- const amount = toBigInt13(r.amount);
53190
+ const amount = toBigInt14(r.amount);
51336
53191
  if (amount === void 0) continue;
51337
53192
  const claimable = id <= lastProcessed;
51338
53193
  out.push({
@@ -51406,14 +53261,14 @@ var readerValantis = {
51406
53261
  for (let i = 0; i < burns.length; i++) {
51407
53262
  const b = burns[i];
51408
53263
  if (!b) continue;
51409
- const amount = Array.isArray(b) ? toBigInt13(b[0]) : toBigInt13(b.amount);
53264
+ const amount = Array.isArray(b) ? toBigInt14(b[0]) : toBigInt14(b.amount);
51410
53265
  const completed = Array.isArray(b) ? Boolean(b[2]) : Boolean(b.completed);
51411
53266
  if (amount === void 0 || completed) continue;
51412
53267
  out.push({
51413
53268
  lst: entry.lst,
51414
53269
  brand: entry.brand,
51415
53270
  symbol: entry.symbol,
51416
- requestId: String(toBigInt13(ids[i]) ?? i),
53271
+ requestId: String(toBigInt14(ids[i]) ?? i),
51417
53272
  amountUnderlying: amount.toString(),
51418
53273
  status: redeemable[i] ? "claimable" : "pending"
51419
53274
  });
@@ -51486,7 +53341,7 @@ var readerTruFin = {
51486
53341
  if (typeof recipient === "string" && recipient.toLowerCase() !== lcUser) {
51487
53342
  continue;
51488
53343
  }
51489
- const amount = Array.isArray(w) ? toBigInt13(w[1]) : toBigInt13(w.amount);
53344
+ const amount = Array.isArray(w) ? toBigInt14(w[1]) : toBigInt14(w.amount);
51490
53345
  if (amount === void 0 || amount === 0n) continue;
51491
53346
  out.push({
51492
53347
  lst: entry.lst,
@@ -51582,7 +53437,7 @@ var readerYieldNest = {
51582
53437
  calls: enumCalls,
51583
53438
  abi: enumCalls.map(() => YieldNestWithdrawalQueueAbi)
51584
53439
  });
51585
- const ids = stage2.map(toBigInt13).filter((v) => v !== void 0);
53440
+ const ids = stage2.map(toBigInt14).filter((v) => v !== void 0);
51586
53441
  if (ids.length === 0) return [];
51587
53442
  const detailCalls = ids.map((id) => ({
51588
53443
  address: entry.withdrawalContract,
@@ -51601,7 +53456,7 @@ var readerYieldNest = {
51601
53456
  const id = ids[i];
51602
53457
  const r = stage3[i];
51603
53458
  if (!r) continue;
51604
- const amount = toBigInt13(r.amount);
53459
+ const amount = toBigInt14(r.amount);
51605
53460
  const created = toNumber(r.creationTimestamp);
51606
53461
  const processed = Boolean(r.processed);
51607
53462
  if (amount === void 0 || created === void 0) continue;
@@ -52194,7 +54049,7 @@ var getLstWithdrawalRegistry = (chainId, extraEntries) => {
52194
54049
  const extra = extraEntries.filter((e) => !seen.has(e.lst.toLowerCase()));
52195
54050
  return extra.length === 0 ? base : [...base, ...extra];
52196
54051
  };
52197
- var warn5 = (...args) => {
54052
+ var warn7 = (...args) => {
52198
54053
  };
52199
54054
  var getLstWithdrawalRequests = async (user, chainId, multicallRetry, options) => {
52200
54055
  const entries = getLstWithdrawalRegistry(chainId, options?.extraEntries);
@@ -52209,7 +54064,7 @@ var getLstWithdrawalRequests = async (user, chainId, multicallRetry, options) =>
52209
54064
  try {
52210
54065
  return await reader.fetch(lcUser, multicallRetry, chainId, entry, ids);
52211
54066
  } catch (e) {
52212
- warn5(
54067
+ warn7(
52213
54068
  `[lst-withdrawals] ${entry.brand} ${entry.symbol} (${entry.lst}) failed:`,
52214
54069
  e?.message ?? e
52215
54070
  );
@@ -52278,7 +54133,7 @@ var NavOracleReadAbi = [
52278
54133
 
52279
54134
  // src/vaults/savings/readers/shared.ts
52280
54135
  var ONE_E189 = 10n ** 18n;
52281
- var toBigInt14 = (v) => {
54136
+ var toBigInt15 = (v) => {
52282
54137
  if (v === void 0 || v === null) return void 0;
52283
54138
  if (typeof v === "bigint") return v;
52284
54139
  if (typeof v === "number") return BigInt(v);
@@ -52309,9 +54164,9 @@ var readerErc46262 = (entry) => {
52309
54164
  ],
52310
54165
  abis: [Erc4626ReadAbi2, TotalSupplyAbi2, Erc4626ReadAbi2],
52311
54166
  parse: ([assets, supply, rate]) => {
52312
- const totalAssets = toBigInt14(assets);
52313
- const totalSupply = toBigInt14(supply);
52314
- const convertToAssetsRaw = toBigInt14(rate);
54167
+ const totalAssets = toBigInt15(assets);
54168
+ const totalSupply = toBigInt15(supply);
54169
+ const convertToAssetsRaw = toBigInt15(rate);
52315
54170
  if (totalAssets === void 0 || totalSupply === void 0 || convertToAssetsRaw === void 0) {
52316
54171
  return void 0;
52317
54172
  }
@@ -52405,13 +54260,13 @@ var readerErc4626Idle = (entry) => {
52405
54260
  ],
52406
54261
  abis: [Erc4626ReadAbi2, TotalSupplyAbi2, Erc4626ReadAbi2, BalanceOfAbi],
52407
54262
  parse: ([assets, supply, rate, inventoryBalance]) => {
52408
- const totalAssets = toBigInt14(assets);
52409
- const totalSupply = toBigInt14(supply);
52410
- const convertToAssetsRaw = toBigInt14(rate);
54263
+ const totalAssets = toBigInt15(assets);
54264
+ const totalSupply = toBigInt15(supply);
54265
+ const convertToAssetsRaw = toBigInt15(rate);
52411
54266
  if (totalAssets === void 0 || totalSupply === void 0 || convertToAssetsRaw === void 0) {
52412
54267
  return void 0;
52413
54268
  }
52414
- const capacity = toBigInt14(inventoryBalance);
54269
+ const capacity = toBigInt15(inventoryBalance);
52415
54270
  return {
52416
54271
  totalAssets,
52417
54272
  totalSupply,
@@ -52442,10 +54297,10 @@ var readerNavOracle = (entry) => {
52442
54297
  ],
52443
54298
  abis: [TotalSupplyAbi2, NavOracleReadAbi],
52444
54299
  parse: ([supply, round]) => {
52445
- const totalSupply = toBigInt14(supply);
54300
+ const totalSupply = toBigInt15(supply);
52446
54301
  if (totalSupply === void 0) return void 0;
52447
54302
  const raw = Array.isArray(round) ? round[1] : round?.answer;
52448
- const exchangeRate = toBigInt14(raw);
54303
+ const exchangeRate = toBigInt15(raw);
52449
54304
  if (exchangeRate === void 0 || exchangeRate <= 0n) return void 0;
52450
54305
  return {
52451
54306
  totalAssets: totalSupply * exchangeRate * underlyingUnit / (ONE_E189 * shareUnit),
@@ -52487,14 +54342,14 @@ var readerNativeWnlp = (entry) => {
52487
54342
  NativeWithdrawQueueReadAbi
52488
54343
  ],
52489
54344
  parse: ([supply, rate, feeBips, instantEnabled, inventory, window]) => {
52490
- const totalSupply = toBigInt14(supply);
52491
- const exchangeRate = toBigInt14(rate);
54345
+ const totalSupply = toBigInt15(supply);
54346
+ const exchangeRate = toBigInt15(rate);
52492
54347
  if (totalSupply === void 0 || exchangeRate === void 0) {
52493
54348
  return void 0;
52494
54349
  }
52495
- const capacity = toBigInt14(inventory);
52496
- const windowSeconds = toBigInt14(window);
52497
- const bips = toBigInt14(feeBips);
54350
+ const capacity = toBigInt15(inventory);
54351
+ const windowSeconds = toBigInt15(window);
54352
+ const bips = toBigInt15(feeBips);
52498
54353
  return {
52499
54354
  totalAssets: totalSupply * exchangeRate / ONE_E189,
52500
54355
  totalSupply,
@@ -52552,9 +54407,9 @@ var fetchSavingsVaults = async (chainId, multicallRetry, prices = {}, tokenList
52552
54407
  for (let i = 0; i < entries.length; i++) {
52553
54408
  const entry = entries[i];
52554
54409
  const reader = readers[i];
52555
- const slice = rawResults.slice(cursor, cursor + reader.calls.length);
54410
+ const slice2 = rawResults.slice(cursor, cursor + reader.calls.length);
52556
54411
  cursor += reader.calls.length;
52557
- const state = reader.parse(slice);
54412
+ const state = reader.parse(slice2);
52558
54413
  if (!state) continue;
52559
54414
  const addressLc = entry.address.toLowerCase();
52560
54415
  const underlyingLc = entry.underlying.toLowerCase();
@@ -52758,7 +54613,7 @@ var pickApr = (apr) => {
52758
54613
  if (apr.inception != null) return { rate: apr.inception, window: "inception" };
52759
54614
  return { rate: 0, window: "none" };
52760
54615
  };
52761
- var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
54616
+ var num4 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
52762
54617
  function parseVault7(v, chainId, prices, tokenList) {
52763
54618
  const address = (v?.address ?? "").toLowerCase();
52764
54619
  const assetAddr = (v?.asset?.address ?? "").toLowerCase();
@@ -52774,14 +54629,14 @@ function parseVault7(v, chainId, prices, tokenList) {
52774
54629
  parseRawAmount(totalAssetsRaw, assetDecimals)
52775
54630
  );
52776
54631
  const apr = {
52777
- weekly: num(state.weeklyApr?.twrrNetApr),
52778
- monthly: num(state.monthlyApr?.twrrNetApr),
52779
- yearly: num(state.yearlyApr?.twrrNetApr),
52780
- inception: num(state.inceptionApr?.twrrNetApr)
54632
+ weekly: num4(state.weeklyApr?.twrrNetApr),
54633
+ monthly: num4(state.monthlyApr?.twrrNetApr),
54634
+ yearly: num4(state.yearlyApr?.twrrNetApr),
54635
+ inception: num4(state.inceptionApr?.twrrNetApr)
52781
54636
  };
52782
54637
  const { rate: supplyRate, window: aprWindow } = pickApr(apr);
52783
54638
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
52784
- const apiTotalAssetsUsd = num(state.totalAssetsUsd) ?? 0;
54639
+ const apiTotalAssetsUsd = num4(state.totalAssetsUsd) ?? 0;
52785
54640
  const impliedPriceUsd = totalAssetsFormatted > 0 ? apiTotalAssetsUsd / totalAssetsFormatted : 0;
52786
54641
  const priceUsd = prices[oracleKey] ?? prices[assetAddr] ?? impliedPriceUsd;
52787
54642
  const totalAssetsUsd = apiTotalAssetsUsd || totalAssetsFormatted * priceUsd;
@@ -52801,7 +54656,7 @@ function parseVault7(v, chainId, prices, tokenList) {
52801
54656
  totalAssets: totalAssetsRaw,
52802
54657
  totalSupply: totalSupplyRaw,
52803
54658
  pricePerShare: state.pricePerShare?.toString() ?? "0",
52804
- pricePerShareUsd: num(state.pricePerShareUsd) ?? void 0,
54659
+ pricePerShareUsd: num4(state.pricePerShareUsd) ?? void 0,
52805
54660
  supplyRate,
52806
54661
  rewardsRate: 0,
52807
54662
  depositRate: supplyRate,
@@ -52913,9 +54768,9 @@ async function fetchAaveEarnApiVaults(chainId, targets) {
52913
54768
  const target = Number(chainId);
52914
54769
  const byAddress = /* @__PURE__ */ new Map();
52915
54770
  const keep = (it) => {
52916
- const addr = it?.address?.toLowerCase();
52917
- if (!addr || Number(it.chainId) !== target) return;
52918
- if (!byAddress.has(addr)) byAddress.set(addr, it);
54771
+ const addr2 = it?.address?.toLowerCase();
54772
+ if (!addr2 || Number(it.chainId) !== target) return;
54773
+ if (!byAddress.has(addr2)) byAddress.set(addr2, it);
52919
54774
  };
52920
54775
  for (const owner of targets.owners) {
52921
54776
  let cursor = null;
@@ -52984,7 +54839,7 @@ var resolveAaveEarnCuratorName = (chainId, owner) => {
52984
54839
 
52985
54840
  // src/vaults/aave-earn/fetchPublic.ts
52986
54841
  var BRAND2 = "Aave";
52987
- var toBigInt15 = (v) => {
54842
+ var toBigInt16 = (v) => {
52988
54843
  if (v === void 0 || v === null) return void 0;
52989
54844
  if (typeof v === "bigint") return v;
52990
54845
  if (typeof v === "number") return BigInt(v);
@@ -52998,7 +54853,7 @@ var toBigInt15 = (v) => {
52998
54853
  }
52999
54854
  return void 0;
53000
54855
  };
53001
- var num2 = (v) => {
54856
+ var num5 = (v) => {
53002
54857
  const n = Number(v);
53003
54858
  return Number.isFinite(n) ? n : 0;
53004
54859
  };
@@ -53039,28 +54894,28 @@ var fetchAaveEarnVaults = async (chainId, multicallRetry, prices = {}, tokenList
53039
54894
  for (let i = 0; i < usable.length; i++) {
53040
54895
  const v = usable[i];
53041
54896
  const base = i * CALLS_PER_VAULT2;
53042
- const slice = rawResults.slice(base, base + CALLS_PER_VAULT2);
54897
+ const slice2 = rawResults.slice(base, base + CALLS_PER_VAULT2);
53043
54898
  const addressLc = v.address.toLowerCase();
53044
54899
  const token = v.usedReserve.underlyingToken;
53045
54900
  const underlyingLc = token.address.toLowerCase();
53046
54901
  const assetDecimals = token.decimals;
53047
- const shareDecOnChain = toBigInt15(slice[1]);
54902
+ const shareDecOnChain = toBigInt16(slice2[1]);
53048
54903
  const decimals = shareDecOnChain !== void 0 ? Number(shareDecOnChain) : assetDecimals;
53049
- const totalSupply = toBigInt15(slice[2]);
54904
+ const totalSupply = toBigInt16(slice2[2]);
53050
54905
  if (totalSupply === void 0) continue;
53051
54906
  const shareUnit = 10n ** BigInt(decimals);
53052
54907
  const underlyingUnit = 10n ** BigInt(assetDecimals);
53053
- const convertToAssets = toBigInt15(slice[3]) ?? 0n;
54908
+ const convertToAssets = toBigInt16(slice2[3]) ?? 0n;
53054
54909
  const convertToShares = convertToAssets > 0n ? shareUnit * underlyingUnit / convertToAssets : 0n;
53055
- const totalAssets = toBigInt15(slice[0]) ?? totalSupply * convertToAssets / shareUnit;
54910
+ const totalAssets = toBigInt16(slice2[0]) ?? totalSupply * convertToAssets / shareUnit;
53056
54911
  const totalAssetsFormatted = Number(totalAssets) / 10 ** assetDecimals;
53057
54912
  const asset = tokenList[underlyingLc];
53058
- const priceUsd = prices[underlyingLc] ?? (v.balance?.usdPerToken != null ? num2(v.balance.usdPerToken) : void 0);
54913
+ const priceUsd = prices[underlyingLc] ?? (v.balance?.usdPerToken != null ? num5(v.balance.usdPerToken) : void 0);
53059
54914
  const totalAssetsUsd = priceUsd !== void 0 ? totalAssetsFormatted * priceUsd : 0;
53060
- const supplyRate = num2(v.vaultApr?.formatted);
54915
+ const supplyRate = num5(v.vaultApr?.formatted);
53061
54916
  const rewardsRate = 0;
53062
54917
  const depositRate = supplyRate + rewardsRate;
53063
- const fee = num2(v.fee?.value);
54918
+ const fee = num5(v.fee?.value);
53064
54919
  const symbol = (v.shareSymbol ?? "").trim();
53065
54920
  const shareName = (v.shareName ?? "").trim();
53066
54921
  const name = shareName || symbol;
@@ -53097,7 +54952,7 @@ var fetchAaveEarnVaults = async (chainId, multicallRetry, prices = {}, tokenList
53097
54952
  };
53098
54953
 
53099
54954
  // src/vaults/upshift/fetchPublic.ts
53100
- var num3 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
54955
+ var num6 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
53101
54956
  var isEvmAddress = (a) => /^0x[0-9a-fA-F]{40}$/.test(a);
53102
54957
  var derivePricePerShare = (totalAssetsRaw, totalSupplyRaw, shareDecimals) => {
53103
54958
  try {
@@ -53124,12 +54979,12 @@ function parseVault8(v, chainId, prices, tokenList) {
53124
54979
  const totalAssetsFormatted = Number(
53125
54980
  parseRawAmount(totalAssetsRaw, assetDecimals)
53126
54981
  );
53127
- const base = num3(v.apy?.apy) ?? 0;
53128
- const campaign = num3(v.apy?.campaignApy);
54982
+ const base = num6(v.apy?.apy) ?? 0;
54983
+ const campaign = num6(v.apy?.campaignApy);
53129
54984
  const supplyRate = apyToAprPercent(base);
53130
54985
  const rewardsRate = campaign != null ? apyToAprPercent(campaign) : 0;
53131
54986
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
53132
- const apiTvlUsd = num3(v.latest_reported_tvl) ?? 0;
54987
+ const apiTvlUsd = num6(v.latest_reported_tvl) ?? 0;
53133
54988
  const impliedPriceUsd = totalAssetsFormatted > 0 ? apiTvlUsd / totalAssetsFormatted : 0;
53134
54989
  const priceUsd = prices[oracleKey] ?? prices[assetAddr] ?? impliedPriceUsd;
53135
54990
  const totalAssetsUsd = apiTvlUsd || totalAssetsFormatted * priceUsd;
@@ -53154,10 +55009,10 @@ function parseVault8(v, chainId, prices, tokenList) {
53154
55009
  rewardsRate,
53155
55010
  depositRate: supplyRate + rewardsRate,
53156
55011
  apy: {
53157
- base: num3(v.apy?.apy),
55012
+ base: num6(v.apy?.apy),
53158
55013
  campaign,
53159
- points: num3(v.apy?.pointsApy),
53160
- underlying: num3(v.apy?.underlyingApy)
55014
+ points: num6(v.apy?.pointsApy),
55015
+ underlying: num6(v.apy?.underlyingApy)
53161
55016
  },
53162
55017
  isDepositPaused: v.isDepositPaused ?? false,
53163
55018
  isWithdrawalPaused: v.isWithdrawalPaused ?? false,
@@ -53266,9 +55121,9 @@ var asBig = (v) => {
53266
55121
  return null;
53267
55122
  }
53268
55123
  };
53269
- var num4 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
55124
+ var num7 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
53270
55125
  var toPct = (v) => {
53271
- const n = num4(v);
55126
+ const n = num7(v);
53272
55127
  return n == null ? 0 : n * 100;
53273
55128
  };
53274
55129
  var deriveTotalSupply = (totalAssetsRaw, pricePerShareRaw, decimals) => {
@@ -53300,16 +55155,16 @@ function parseVault9(v, chainId, prices, tokenList) {
53300
55155
  const totalAssetsFormatted = Number(
53301
55156
  parseRawAmount(totalAssetsRaw, assetDecimals)
53302
55157
  );
53303
- const realized = num4(v.apr?.netAPR);
53304
- const forward = num4(v.apr?.forwardAPR?.netAPR);
55158
+ const realized = num7(v.apr?.netAPR);
55159
+ const forward = num7(v.apr?.forwardAPR?.netAPR);
53305
55160
  const isForwardApr = realized == null && forward != null;
53306
55161
  const supplyRate = toPct(realized ?? forward);
53307
55162
  const rewardsRate = toPct(v.apr?.extra?.stakingRewardsAPR);
53308
55163
  const fee = toPct(v.apr?.fees?.performance);
53309
55164
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
53310
- const apiPrice = num4(v.tvl?.price) ?? 0;
55165
+ const apiPrice = num7(v.tvl?.price) ?? 0;
53311
55166
  const priceUsd = prices[oracleKey] ?? prices[assetAddr] ?? apiPrice;
53312
- const apiTvlUsd = num4(v.tvl?.tvl) ?? 0;
55167
+ const apiTvlUsd = num7(v.tvl?.tvl) ?? 0;
53313
55168
  const totalAssetsUsd = apiTvlUsd || totalAssetsFormatted * priceUsd;
53314
55169
  const name = (v.name ?? "").trim();
53315
55170
  const symbol = (v.symbol ?? "").trim();
@@ -53745,6 +55600,7 @@ var stampVaultClassification = (data, chainId, tokenList = {}) => {
53745
55600
  stampBag(data.lista, "lista");
53746
55601
  stampBag(data.silo, "silo");
53747
55602
  stampBag(data["euler-earn"], "euler-earn");
55603
+ stampBag(data.termmax, "termmax");
53748
55604
  stampBag(data.lst, "lst");
53749
55605
  stampBag(data.savings, "savings");
53750
55606
  stampBag(data.lagoon, "lagoon");
@@ -54296,23 +56152,23 @@ var priceGmMarkets = async (chainId, multicallRetry, markets, prices) => {
54296
56152
  const indexMax = price(prices, m.indexToken)?.max;
54297
56153
  if (Array.isArray(dsRes) && longMax != null && shortMax != null) {
54298
56154
  const base = i * SLOTS;
54299
- const big4 = (j) => typeof dsRes[base + j] === "bigint" ? dsRes[base + j] : 0n;
56155
+ const big7 = (j) => typeof dsRes[base + j] === "bigint" ? dsRes[base + j] : 0n;
54300
56156
  const cap = computeDepositCapacityUsd(
54301
- [info?.longTokenAmount, longMax, big4(0), big4(2)],
54302
- [info?.shortTokenAmount, shortMax, big4(1), big4(3)]
56157
+ [info?.longTokenAmount, longMax, big7(0), big7(2)],
56158
+ [info?.shortTokenAmount, shortMax, big7(1), big7(3)]
54303
56159
  );
54304
56160
  if (cap != null) value.depositCapacityUsd = cap;
54305
56161
  if (indexMax != null) {
54306
56162
  const divisor = m.longToken.toLowerCase() === m.shortToken.toLowerCase() ? 2n : 1n;
54307
- const reservedUsdLong = (big4(4) + big4(5)) / divisor * indexMax;
54308
- const reservedUsdShort = (big4(6) + big4(7)) / divisor;
56163
+ const reservedUsdLong = (big7(4) + big7(5)) / divisor * indexMax;
56164
+ const reservedUsdShort = (big7(6) + big7(7)) / divisor;
54309
56165
  const liq = computeLiquidityUsd(
54310
56166
  info?.longTokenUsd,
54311
56167
  info?.shortTokenUsd,
54312
56168
  reservedUsdLong,
54313
56169
  reservedUsdShort,
54314
- big4(8),
54315
- big4(9)
56170
+ big7(8),
56171
+ big7(9)
54316
56172
  );
54317
56173
  if (liq != null)
54318
56174
  value.liquidityUsd = Math.max(0, Math.min(liq, value.tvlUsd));
@@ -54511,27 +56367,27 @@ var fetchGmxExecutionFees = async (chainId, multicallRetry, gasPriceWei) => {
54511
56367
  } catch {
54512
56368
  return void 0;
54513
56369
  }
54514
- const big4 = (i) => typeof res[i] === "bigint" ? res[i] : 0n;
54515
- const base = big4(0);
54516
- const mult = big4(1);
56370
+ const big7 = (i) => typeof res[i] === "bigint" ? res[i] : 0n;
56371
+ const base = big7(0);
56372
+ const mult = big7(1);
54517
56373
  if (base === 0n && mult === 0n) return void 0;
54518
56374
  const PRECISION = 10n ** 30n;
54519
56375
  const adjusted = (opGas) => base + opGas * mult / PRECISION;
54520
56376
  const fee = (opGas) => (adjusted(opGas) * gasPriceWei).toString();
54521
- const glvExtra = big4(6) * GLV_NOMINAL_MARKET_COUNT;
56377
+ const glvExtra = big7(6) * GLV_NOMINAL_MARKET_COUNT;
54522
56378
  return {
54523
56379
  chainId,
54524
56380
  gasPriceWei: gasPriceWei.toString(),
54525
- deposit: fee(big4(2)),
54526
- withdrawal: fee(big4(3)),
54527
- glvDeposit: fee(big4(4) + glvExtra),
54528
- glvWithdrawal: fee(big4(5) + glvExtra)
56381
+ deposit: fee(big7(2)),
56382
+ withdrawal: fee(big7(3)),
56383
+ glvDeposit: fee(big7(4) + glvExtra),
56384
+ glvWithdrawal: fee(big7(5) + glvExtra)
54529
56385
  };
54530
56386
  };
54531
56387
 
54532
56388
  // src/vaults/gmx/fetchPublic.ts
54533
56389
  var GMX_TOKEN_DECIMALS = 18;
54534
- var num5 = (n) => typeof n === "number" && Number.isFinite(n) ? n : 0;
56390
+ var num8 = (n) => typeof n === "number" && Number.isFinite(n) ? n : 0;
54535
56391
  var minDefined = (a, b) => a == null ? b : b == null ? a : Math.min(a, b);
54536
56392
  var glvMarketRoomUsd = (cap, priceUsd) => {
54537
56393
  const currentUsd = Number(cap.balanceAmount) / 1e18 * priceUsd;
@@ -54565,9 +56421,9 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
54565
56421
  indexToken: indexToken ? indexToken.toLowerCase() : void 0,
54566
56422
  longSymbol,
54567
56423
  shortSymbol,
54568
- apy: num5(entry?.apy),
54569
- baseApy: num5(entry?.baseApy),
54570
- bonusApr: num5(entry?.bonusApr),
56424
+ apy: num8(entry?.apy),
56425
+ baseApy: num8(entry?.baseApy),
56426
+ bonusApr: num8(entry?.bonusApr),
54571
56427
  yieldProfile: "volatile",
54572
56428
  denomination: denominationFor(longSymbol, shortSymbol)
54573
56429
  };
@@ -54626,8 +56482,8 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
54626
56482
  marketIndexToken
54627
56483
  )
54628
56484
  ]);
54629
- for (const [addr, v] of gmValues) {
54630
- const e = out[addr];
56485
+ for (const [addr2, v] of gmValues) {
56486
+ const e = out[addr2];
54631
56487
  if (e) {
54632
56488
  e.priceUsd = v.priceUsd;
54633
56489
  e.tvlUsd = v.tvlUsd;
@@ -54635,12 +56491,12 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
54635
56491
  e.depositCapacityUsd = v.depositCapacityUsd;
54636
56492
  }
54637
56493
  }
54638
- for (const [addr, v] of glv.values) {
54639
- const e = out[addr];
56494
+ for (const [addr2, v] of glv.values) {
56495
+ const e = out[addr2];
54640
56496
  if (!e) continue;
54641
56497
  e.priceUsd = v.priceUsd;
54642
56498
  e.tvlUsd = v.tvlUsd;
54643
- const markets2 = glv.glvMarkets.get(addr) ?? [];
56499
+ const markets2 = glv.glvMarkets.get(addr2) ?? [];
54644
56500
  let liqSum = 0;
54645
56501
  let tvlSum = 0;
54646
56502
  for (const m of markets2) {
@@ -54652,7 +56508,7 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
54652
56508
  }
54653
56509
  if (tvlSum > 0 && v.tvlUsd != null)
54654
56510
  e.liquidityUsd = v.tvlUsd * (liqSum / tvlSum);
54655
- const caps = glv.glvCaps.get(addr) ?? [];
56511
+ const caps = glv.glvCaps.get(addr2) ?? [];
54656
56512
  let capacity = 0;
54657
56513
  let known = false;
54658
56514
  for (const cap of caps) {
@@ -54678,7 +56534,7 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
54678
56534
  // src/vaults/gmx/fetchUser.ts
54679
56535
  var DEFAULT_CAP = 50;
54680
56536
  var isBig = (v) => typeof v === "bigint";
54681
- var str = (v) => isBig(v) ? v.toString() : "0";
56537
+ var str2 = (v) => isBig(v) ? v.toString() : "0";
54682
56538
  var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
54683
56539
  const empty = {
54684
56540
  chainId,
@@ -54806,11 +56662,11 @@ var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
54806
56662
  market: a.market.toLowerCase(),
54807
56663
  initialLongToken: a.initialLongToken.toLowerCase(),
54808
56664
  initialShortToken: a.initialShortToken.toLowerCase(),
54809
- initialLongTokenAmount: str(n.initialLongTokenAmount),
54810
- initialShortTokenAmount: str(n.initialShortTokenAmount),
54811
- minOut: str(n.minMarketTokens),
54812
- executionFee: str(n.executionFee),
54813
- updatedAtTime: str(n.updatedAtTime)
56665
+ initialLongTokenAmount: str2(n.initialLongTokenAmount),
56666
+ initialShortTokenAmount: str2(n.initialShortTokenAmount),
56667
+ minOut: str2(n.minMarketTokens),
56668
+ executionFee: str2(n.executionFee),
56669
+ updatedAtTime: str2(n.updatedAtTime)
54814
56670
  });
54815
56671
  });
54816
56672
  withdrawalKeys.forEach((key, i) => {
@@ -54824,11 +56680,11 @@ var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
54824
56680
  account: a.account.toLowerCase(),
54825
56681
  receiver: a.receiver.toLowerCase(),
54826
56682
  market: a.market.toLowerCase(),
54827
- tokenAmount: str(n.marketTokenAmount),
54828
- minLongTokenAmount: str(n.minLongTokenAmount),
54829
- minShortTokenAmount: str(n.minShortTokenAmount),
54830
- executionFee: str(n.executionFee),
54831
- updatedAtTime: str(n.updatedAtTime)
56683
+ tokenAmount: str2(n.marketTokenAmount),
56684
+ minLongTokenAmount: str2(n.minLongTokenAmount),
56685
+ minShortTokenAmount: str2(n.minShortTokenAmount),
56686
+ executionFee: str2(n.executionFee),
56687
+ updatedAtTime: str2(n.updatedAtTime)
54832
56688
  });
54833
56689
  });
54834
56690
  const glvDeposits = Array.isArray(glvRes[0]) ? glvRes[0] : [];
@@ -54845,11 +56701,11 @@ var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
54845
56701
  glv: a.glv.toLowerCase(),
54846
56702
  initialLongToken: a.initialLongToken.toLowerCase(),
54847
56703
  initialShortToken: a.initialShortToken.toLowerCase(),
54848
- initialLongTokenAmount: str(n.initialLongTokenAmount),
54849
- initialShortTokenAmount: str(n.initialShortTokenAmount),
54850
- minOut: str(n.minGlvTokens),
54851
- executionFee: str(n.executionFee),
54852
- updatedAtTime: str(n.updatedAtTime)
56704
+ initialLongTokenAmount: str2(n.initialLongTokenAmount),
56705
+ initialShortTokenAmount: str2(n.initialShortTokenAmount),
56706
+ minOut: str2(n.minGlvTokens),
56707
+ executionFee: str2(n.executionFee),
56708
+ updatedAtTime: str2(n.updatedAtTime)
54853
56709
  });
54854
56710
  }
54855
56711
  for (const w of glvWithdrawals) {
@@ -54862,11 +56718,11 @@ var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
54862
56718
  receiver: a.receiver.toLowerCase(),
54863
56719
  market: a.market.toLowerCase(),
54864
56720
  glv: a.glv.toLowerCase(),
54865
- tokenAmount: str(n.glvTokenAmount),
54866
- minLongTokenAmount: str(n.minLongTokenAmount),
54867
- minShortTokenAmount: str(n.minShortTokenAmount),
54868
- executionFee: str(n.executionFee),
54869
- updatedAtTime: str(n.updatedAtTime)
56721
+ tokenAmount: str2(n.glvTokenAmount),
56722
+ minLongTokenAmount: str2(n.minLongTokenAmount),
56723
+ minShortTokenAmount: str2(n.minShortTokenAmount),
56724
+ executionFee: str2(n.executionFee),
56725
+ updatedAtTime: str2(n.updatedAtTime)
54870
56726
  });
54871
56727
  }
54872
56728
  return {
@@ -54957,11 +56813,11 @@ function buildVaultLookup(data) {
54957
56813
  const addEntries = (bag, provider) => {
54958
56814
  if (!bag) return;
54959
56815
  for (const v of Object.values(bag)) {
54960
- const addr = v.address.toLowerCase();
54961
- if (map.has(addr)) continue;
54962
- map.set(addr, {
56816
+ const addr2 = v.address.toLowerCase();
56817
+ if (map.has(addr2)) continue;
56818
+ map.set(addr2, {
54963
56819
  provider,
54964
- address: addr,
56820
+ address: addr2,
54965
56821
  underlying: v.underlying.toLowerCase(),
54966
56822
  symbol: v.symbol,
54967
56823
  name: v.name,
@@ -54988,6 +56844,7 @@ function buildVaultLookup(data) {
54988
56844
  addEntries(data.lista, "lista");
54989
56845
  addEntries(data.silo, "silo");
54990
56846
  addEntries(data["euler-earn"], "euler-earn");
56847
+ addEntries(data.termmax, "termmax");
54991
56848
  addEntries(data.lst, "lst");
54992
56849
  addEntries(data.savings, "savings");
54993
56850
  addEntries(data.lagoon, "lagoon");
@@ -54996,7 +56853,7 @@ function buildVaultLookup(data) {
54996
56853
  addEntries(data.yearn, "yearn");
54997
56854
  return map;
54998
56855
  }
54999
- var warn6 = (...args) => {
56856
+ var warn8 = (...args) => {
55000
56857
  };
55001
56858
  var HYPERCORE_PROVIDER_CHAIN = "999";
55002
56859
  var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices = {}, tokenList = {}, options) => {
@@ -55009,7 +56866,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55009
56866
  fetchFluidFTokens(chainId, multicallRetry, prices, tokenList).then((res) => {
55010
56867
  out.fluid = res;
55011
56868
  }).catch((e) => {
55012
- warn6(
56869
+ warn8(
55013
56870
  `[vaults] fluid fetch failed for chain ${chainId}:`,
55014
56871
  e?.message ?? e
55015
56872
  );
@@ -55021,7 +56878,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55021
56878
  fetchGearboxV3Pools(chainId, multicallRetry, prices, tokenList).then((res) => {
55022
56879
  out.gearbox = res;
55023
56880
  }).catch((e) => {
55024
- warn6(
56881
+ warn8(
55025
56882
  `[vaults] gearbox fetch failed for chain ${chainId}:`,
55026
56883
  e?.message ?? e
55027
56884
  );
@@ -55033,7 +56890,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55033
56890
  fetchMorphoVaults(chainId, multicallRetry, prices, tokenList).then((res) => {
55034
56891
  out.morpho = res;
55035
56892
  }).catch((e) => {
55036
- warn6(
56893
+ warn8(
55037
56894
  `[vaults] morpho fetch failed for chain ${chainId}:`,
55038
56895
  e?.message ?? e
55039
56896
  );
@@ -55045,7 +56902,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55045
56902
  fetchListaVaultsFromChain(chainId, multicallRetry, prices, tokenList).then((res) => {
55046
56903
  out.lista = res;
55047
56904
  }).catch((e) => {
55048
- warn6(
56905
+ warn8(
55049
56906
  `[vaults] lista fetch failed for chain ${chainId}:`,
55050
56907
  e?.message ?? e
55051
56908
  );
@@ -55060,7 +56917,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55060
56917
  }).then((res) => {
55061
56918
  out.silo = res;
55062
56919
  }).catch((e) => {
55063
- warn6(
56920
+ warn8(
55064
56921
  `[vaults] silo fetch failed for chain ${chainId}:`,
55065
56922
  e?.message ?? e
55066
56923
  );
@@ -55072,19 +56929,31 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55072
56929
  fetchEulerEarnVaults(chainId, prices, tokenList, multicallRetry).then((res) => {
55073
56930
  out["euler-earn"] = res;
55074
56931
  }).catch((e) => {
55075
- warn6(
56932
+ warn8(
55076
56933
  `[vaults] euler-earn fetch failed for chain ${chainId}:`,
55077
56934
  e?.message ?? e
55078
56935
  );
55079
56936
  })
55080
56937
  );
55081
56938
  }
56939
+ if (requested.has("termmax")) {
56940
+ tasks.push(
56941
+ fetchTermMaxVaults(chainId, multicallRetry, prices, tokenList).then((res) => {
56942
+ out.termmax = res;
56943
+ }).catch((e) => {
56944
+ warn8(
56945
+ `[vaults] termmax fetch failed for chain ${chainId}:`,
56946
+ e?.message ?? e
56947
+ );
56948
+ })
56949
+ );
56950
+ }
55082
56951
  if (requested.has("lst")) {
55083
56952
  tasks.push(
55084
56953
  fetchLstShareTokens(chainId, multicallRetry, prices, tokenList).then((res) => {
55085
56954
  out.lst = res;
55086
56955
  }).catch((e) => {
55087
- warn6(
56956
+ warn8(
55088
56957
  `[vaults] lst fetch failed for chain ${chainId}:`,
55089
56958
  e?.message ?? e
55090
56959
  );
@@ -55096,7 +56965,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55096
56965
  fetchSavingsVaults(chainId, multicallRetry, prices, tokenList).then((res) => {
55097
56966
  out.savings = res;
55098
56967
  }).catch((e) => {
55099
- warn6(
56968
+ warn8(
55100
56969
  `[vaults] savings fetch failed for chain ${chainId}:`,
55101
56970
  e?.message ?? e
55102
56971
  );
@@ -55108,7 +56977,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55108
56977
  fetchLagoonVaults(chainId, prices, tokenList).then((res) => {
55109
56978
  out.lagoon = res;
55110
56979
  }).catch((e) => {
55111
- warn6(
56980
+ warn8(
55112
56981
  `[vaults] lagoon fetch failed for chain ${chainId}:`,
55113
56982
  e?.message ?? e
55114
56983
  );
@@ -55120,7 +56989,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55120
56989
  fetchAaveEarnVaults(chainId, multicallRetry, prices, tokenList).then((res) => {
55121
56990
  out["aave-earn"] = res;
55122
56991
  }).catch((e) => {
55123
- warn6(
56992
+ warn8(
55124
56993
  `[vaults] aave-earn fetch failed for chain ${chainId}:`,
55125
56994
  e?.message ?? e
55126
56995
  );
@@ -55132,7 +57001,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55132
57001
  fetchUpshiftVaults(chainId, prices, tokenList).then((res) => {
55133
57002
  out.upshift = res;
55134
57003
  }).catch((e) => {
55135
- warn6(
57004
+ warn8(
55136
57005
  `[vaults] upshift fetch failed for chain ${chainId}:`,
55137
57006
  e?.message ?? e
55138
57007
  );
@@ -55144,7 +57013,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55144
57013
  fetchYearnVaults(chainId, multicallRetry, prices, tokenList).then((res) => {
55145
57014
  out.yearn = res;
55146
57015
  }).catch((e) => {
55147
- warn6(
57016
+ warn8(
55148
57017
  `[vaults] yearn fetch failed for chain ${chainId}:`,
55149
57018
  e?.message ?? e
55150
57019
  );
@@ -55156,7 +57025,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55156
57025
  fetchHypercoreVaults().then((res) => {
55157
57026
  out.hypercore = res;
55158
57027
  }).catch((e) => {
55159
- warn6(
57028
+ warn8(
55160
57029
  `[vaults] hypercore fetch failed for chain ${chainId}:`,
55161
57030
  e?.message ?? e
55162
57031
  );
@@ -55168,7 +57037,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55168
57037
  fetchGmxVaults(chainId, multicallRetry).then((res) => {
55169
57038
  out.gmx = res;
55170
57039
  }).catch((e) => {
55171
- warn6(
57040
+ warn8(
55172
57041
  `[vaults] gmx fetch failed for chain ${chainId}:`,
55173
57042
  e?.message ?? e
55174
57043
  );
@@ -55184,7 +57053,7 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
55184
57053
  );
55185
57054
  if (fees) out.gmxExecutionFees = fees;
55186
57055
  })().catch((e) => {
55187
- warn6(
57056
+ warn8(
55188
57057
  `[vaults] gmx execution-fee fetch failed for chain ${chainId}:`,
55189
57058
  e?.message ?? e
55190
57059
  );
@@ -55492,32 +57361,32 @@ async function fetchTokenMetadata(chain, addrs) {
55492
57361
  const results = await client.multicall({
55493
57362
  allowFailure: false,
55494
57363
  batchSize: 300,
55495
- contracts: addrs.map((addr) => [
57364
+ contracts: addrs.map((addr2) => [
55496
57365
  {
55497
57366
  abi: ERC20MetadataAbi,
55498
57367
  functionName: "name",
55499
- address: addr,
57368
+ address: addr2,
55500
57369
  args: []
55501
57370
  },
55502
57371
  {
55503
57372
  abi: ERC20MetadataAbi,
55504
57373
  functionName: "symbol",
55505
- address: addr,
57374
+ address: addr2,
55506
57375
  args: []
55507
57376
  },
55508
57377
  {
55509
57378
  abi: ERC20MetadataAbi,
55510
57379
  functionName: "decimals",
55511
- address: addr,
57380
+ address: addr2,
55512
57381
  args: []
55513
57382
  }
55514
57383
  ]).flat()
55515
57384
  });
55516
- addrs.forEach((addr, i) => {
57385
+ addrs.forEach((addr2, i) => {
55517
57386
  const name = results[i * 3];
55518
57387
  const symbol = results[i * 3 + 1];
55519
57388
  const decimals = results[i * 3 + 2];
55520
- const address = addr.toLowerCase();
57389
+ const address = addr2.toLowerCase();
55521
57390
  tokens[address] = {
55522
57391
  chainId: String(chain),
55523
57392
  decimals,
@@ -55731,6 +57600,6 @@ async function fetchTokenBalances(chainId, account, tokens, options = {}) {
55731
57600
  return parseTokenBalanceResult(rawResult, prepared.query);
55732
57601
  }
55733
57602
 
55734
- export { ApiBookSource, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_STALE_REJECT_SECONDS, EMPTY_BALANCE, GMX_API_HOSTS, GMX_READ_CONTRACTS, GMX_SUPPORTED_CHAINS, HYPERCORE_VAULT_REGISTRY, IDLE_MARKET_ID, INTERFACE_IDS, LAGOON_API_URL, LAGOON_CHAIN_IDS, MORPHO_LENS, MaxParamThresholds, STABLECOIN_SYMBOLS, STCELO_MANAGER_ADDRESS, TELLER_CALLS_PER_BID, TermSubgraphSource, UPSHIFT_CHAIN_IDS, UPSHIFT_VAULTS_URL, VAULT_SHARE_PRICE_PROBE, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, accountDepositListKey, accountWithdrawalListKey, appendSnapshot, applyPositionDelta, attachPricesToFlashLiquidity, buildFluidFTokensCall, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildVaultLookup, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, classifyFreshness, classifyReliability, classifyVault, collectFeedObservations, computeBorrowDelta2 as computeBorrowDelta, computeCloseTradeDeltas, computeCollateralSwapDeltas, computeDebtSwapDeltas, computeDepositDelta2 as computeDepositDelta, computeEModeAnalysis, computeOpenTradeDeltas, computePostTradeMetrics, computeRepayDelta2 as computeRepayDelta, computeSumerBorrowDelta, computeSumerDepositDelta, computeSumerRepayDelta, computeSumerWaterfall, computeSumerWithdrawDelta, computeVaultApr, computeWithdrawDelta2 as computeWithdrawDelta, computeZapTradeDeltas, consensusReference, convertExactlyMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, createMarketUid, createMidnightBookSource, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, detectInterfaceKinds, encodeBalanceFetcherCalldata, exactlyLenderKey, exactlyMarketFromLenderKey, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feedKeyOf, feedStatKey, fetchDolomiteAccountNumbers, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFluidFTokens, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchLagoonApiVaults, fetchLagoonVaults, fetchLiquityMarkets, fetchListaVaultsFromChain, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendlePrices, fetchRiverMarkets, fetchSiloVaults, fetchTellerMarkets, fetchTermMarkets, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchYearnApiVaults, fetchYearnVaults, filterActiveLenders, filterLendersByProtocol, fuseLenderData, generateLendingPools, getAavesForChain, getAssetConfig, getBalanceForMarketUid, getBorrowCapacity, getCachedLiquityTroves, getCachedTellerBids, getCoreValidators, getFluidFTokensConverter, getGmxApiHost, getGmxReadContracts, getGmxUserPositions, getHealthFactor, getHypercoreUserPositions, getHypercoreVaultRegistry, getLenderAssets, getLenderPublicData, getLenderPublicDataAll, getLenderPublicDataViaApi, getLenderUserDataMulti, getLenderUserDataResult, getLendersForChain, getLstDelegation, getLstValidators, getLstWithdrawalRegistry, getLstWithdrawalRequests, getMaxAmountClose, getMaxAmountCollateralSwap, getMaxAmountDebtSwap, getMaxAmountOpen, getMergedUserData, getMorphoTypeMarketConverter, getResolvedDolomiteAccountNumbers, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getVaultPublicDataAll, getVaultWithdrawalRequests, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasUpshiftVaults, hasYearnVaults, isStablecoinSymbol, isYearnV3, keysFromMaps, lenderApiOnly, lenderFamily, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, parseBalanceFetcherResult, parseMergedResult, parseMulticallRpcResponses, parseRawRpcBatchResponses, parseRawRpcResponses, parseTokenBalanceResult, positivePart2 as positivePart, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, pruneFeedStats, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, resolveDerivation, resolveStCeloDepositGroup, riverKeyParts, riverLenderKey, selectAssetGroupPrices, stampVaultClassification, tellerBpsToPercent, tellerImpliedLtv, tellerLenderKey, tellerPoolFromLenderKey, termLenderKey, tickToAprNumber, tickToPrice, unflattenLenderData, updateFeedStats };
57603
+ export { ApiBookSource, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_STALE_REJECT_SECONDS, DEFAULT_TERMMAX_API, EMPTY_BALANCE, GMX_API_HOSTS, GMX_READ_CONTRACTS, GMX_SUPPORTED_CHAINS, HYPERCORE_VAULT_REGISTRY, IDLE_MARKET_ID, INTERFACE_IDS, LAGOON_API_URL, LAGOON_CHAIN_IDS, MORPHO_LENS, MaxParamThresholds, STABLECOIN_SYMBOLS, STCELO_MANAGER_ADDRESS, TELLER_CALLS_PER_BID, TERMMAX_CALLS_PER_ACCOUNT, DECIMAL_BASE as TERMMAX_DECIMAL_BASE, TERMMAX_LIQUIDATION_PENALTY, TERMMAX_LIQUIDATION_WINDOW_SECS, TERMMAX_LIQUIDATOR_BONUS, TERMMAX_PARTIAL_CLOSE_FACTOR, TERMMAX_PARTIAL_LIQUIDATION_THRESHOLD_USD, TermMaxApiSource, TermSubgraphSource, UPSHIFT_CHAIN_IDS, UPSHIFT_VAULTS_URL, VAULT_SHARE_PRICE_PROBE, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, accountDepositListKey, accountWithdrawalListKey, appendSnapshot, applyPositionDelta, attachPricesToFlashLiquidity, buildFluidFTokensCall, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildTermMaxUserCall, buildVaultLookup, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, classifyFreshness, classifyReliability, classifyVault, collectFeedObservations, computeBorrowDelta2 as computeBorrowDelta, computeCloseTradeDeltas, computeCollateralSwapDeltas, computeDebtSwapDeltas, computeDepositDelta2 as computeDepositDelta, computeEModeAnalysis, computeOpenTradeDeltas, computePostTradeMetrics, computeRepayDelta2 as computeRepayDelta, computeSumerBorrowDelta, computeSumerDepositDelta, computeSumerRepayDelta, computeSumerWaterfall, computeSumerWithdrawDelta, computeVaultApr, computeWithdrawDelta2 as computeWithdrawDelta, computeZapTradeDeltas, consensusReference, convertExactlyMarketsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, createMarketUid, createMidnightBookSource, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, detectInterfaceKinds, encodeBalanceFetcherCalldata, exactlyLenderKey, exactlyMarketFromLenderKey, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feedKeyOf, feedStatKey, fetchDolomiteAccountNumbers, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFluidFTokens, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchInverseMarkets, fetchLagoonApiVaults, fetchLagoonVaults, fetchLiquityMarkets, fetchListaVaultsFromChain, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendlePrices, fetchRiverMarkets, fetchSiloVaults, fetchTellerMarkets, fetchTermMarkets, fetchTermMaxMarkets, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchYearnApiVaults, fetchYearnVaults, filterActiveLenders, filterLendersByProtocol, fuseLenderData, generateLendingPools, getAavesForChain, getAssetConfig, getBalanceForMarketUid, getBorrowCapacity, getCachedLiquityTroves, getCachedTellerBids, getCachedTermMaxDiscovery, getCachedTermMaxMarket, getCachedTermMaxMarkets, getCoreValidators, getFluidFTokensConverter, getGmxApiHost, getGmxReadContracts, getGmxUserPositions, getHealthFactor, getHypercoreUserPositions, getHypercoreVaultRegistry, getLenderAssets, getLenderPublicData, getLenderPublicDataAll, getLenderPublicDataViaApi, getLenderUserDataMulti, getLenderUserDataResult, getLendersForChain, getLstDelegation, getLstValidators, getLstWithdrawalRegistry, getLstWithdrawalRequests, getMaxAmountClose, getMaxAmountCollateralSwap, getMaxAmountDebtSwap, getMaxAmountOpen, getMergedUserData, getMorphoTypeMarketConverter, getResolvedDolomiteAccountNumbers, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getVaultPublicDataAll, getVaultWithdrawalRequests, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasUpshiftVaults, hasYearnVaults, inverseKeyParts, inverseLenderKey, isStablecoinSymbol, isYearnV3, keysFromMaps, lenderApiOnly, lenderFamily, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, parseBalanceFetcherResult, parseMergedResult, parseMulticallRpcResponses, parseRawRpcBatchResponses, parseRawRpcResponses, parseTermMaxLtv, parseTokenBalanceResult, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, pruneFeedStats, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, resolveDerivation, resolveStCeloDepositGroup, riverKeyParts, riverLenderKey, selectAssetGroupPrices, stampVaultClassification, tellerBpsToPercent, tellerImpliedLtv, tellerLenderKey, tellerPoolFromLenderKey, termLenderKey, termMaxApiBase, borrowNif as termMaxBorrowNif, curveApr as termMaxCurveApr, curveAprNumber as termMaxCurveAprNumber, daysToMaturity as termMaxDaysToMaturity, lendNif as termMaxLendNif, mintGtFeeRatio as termMaxMintGtFeeRatio, ratioToNumber as termMaxRatioToNumber, ratioToPercent as termMaxRatioToPercent, tickToAprNumber, tickToPrice, unflattenLenderData, updateFeedStats };
55735
57604
  //# sourceMappingURL=index.js.map
55736
57605
  //# sourceMappingURL=index.js.map