@1delta/margin-fetcher 5.0.20 → 5.0.22

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
@@ -10118,11 +10118,11 @@ async function resolveListaBrokers(chainId, marketKeys, getClient = getEvmClient
10118
10118
  const moolah = morphoPools()?.LISTA_DAO?.[chainId];
10119
10119
  const out = {};
10120
10120
  if (!moolah || marketKeys.length === 0) return out;
10121
- const cache = BROKER_CACHE[chainId] ??= {};
10121
+ const cache2 = BROKER_CACHE[chainId] ??= {};
10122
10122
  const missing = [];
10123
10123
  for (const key3 of marketKeys) {
10124
10124
  const id = toBytes32MarketId(key3);
10125
- if (cache[id] === void 0) missing.push(id);
10125
+ if (cache2[id] === void 0) missing.push(id);
10126
10126
  }
10127
10127
  if (missing.length > 0) {
10128
10128
  try {
@@ -10138,15 +10138,15 @@ async function resolveListaBrokers(chainId, marketKeys, getClient = getEvmClient
10138
10138
  });
10139
10139
  results.forEach((r, i) => {
10140
10140
  const id = missing[i];
10141
- const addr2 = r.status === "success" && r.result ? r.result : zeroAddress;
10142
- cache[id] = addr2.toLowerCase();
10141
+ const addr3 = r.status === "success" && r.result ? r.result : zeroAddress;
10142
+ cache2[id] = addr3.toLowerCase();
10143
10143
  });
10144
10144
  } catch {
10145
10145
  }
10146
10146
  }
10147
10147
  for (const key3 of marketKeys) {
10148
10148
  const id = toBytes32MarketId(key3);
10149
- const broker = cache[id];
10149
+ const broker = cache2[id];
10150
10150
  if (broker && broker !== zeroAddress) out[id] = broker;
10151
10151
  }
10152
10152
  return out;
@@ -10167,7 +10167,7 @@ async function fetchListaFixedTerms(chainId, marketKeys) {
10167
10167
  args: []
10168
10168
  }))
10169
10169
  });
10170
- const cache = FIXED_TERMS_CACHE[chainId] ??= {};
10170
+ const cache2 = FIXED_TERMS_CACHE[chainId] ??= {};
10171
10171
  results.forEach((r, i) => {
10172
10172
  const id = ids[i];
10173
10173
  if (r.status !== "success" || !r.result) return;
@@ -10181,7 +10181,7 @@ async function fetchListaFixedTerms(chainId, marketKeys) {
10181
10181
  };
10182
10182
  });
10183
10183
  out[id] = terms;
10184
- cache[id] = terms;
10184
+ cache2[id] = terms;
10185
10185
  });
10186
10186
  } catch {
10187
10187
  }
@@ -10878,9 +10878,9 @@ function applyPositionDelta(positions, targetMarketUid, depositsDeltaUSD, debtDe
10878
10878
  }
10879
10879
 
10880
10880
  // src/lending/margin/base/sumer/deposit.ts
10881
- function computeSumerDepositDelta(amount, price2, targetMarketUid, balanceData2, positions, createNewSubAccount = false, apr, yieldParams) {
10881
+ function computeSumerDepositDelta(amount3, price2, targetMarketUid, balanceData2, positions, createNewSubAccount = false, apr, yieldParams) {
10882
10882
  const base = createNewSubAccount ? EMPTY_BALANCE : balanceData2;
10883
- const dollarAmount = amount * price2;
10883
+ const dollarAmount = amount3 * price2;
10884
10884
  const updatedPositions = applyPositionDelta(
10885
10885
  positions,
10886
10886
  targetMarketUid,
@@ -10946,8 +10946,8 @@ function computeSumerDepositDelta(amount, price2, targetMarketUid, balanceData2,
10946
10946
  }
10947
10947
 
10948
10948
  // src/lending/margin/base/sumer/withdraw.ts
10949
- function computeSumerWithdrawDelta(amount, price2, targetMarketUid, balanceData2, positions, apr, yieldParams) {
10950
- const dollarAmount = amount * price2;
10949
+ function computeSumerWithdrawDelta(amount3, price2, targetMarketUid, balanceData2, positions, apr, yieldParams) {
10950
+ const dollarAmount = amount3 * price2;
10951
10951
  const updatedPositions = applyPositionDelta(
10952
10952
  positions,
10953
10953
  targetMarketUid,
@@ -11013,8 +11013,8 @@ function computeSumerWithdrawDelta(amount, price2, targetMarketUid, balanceData2
11013
11013
  }
11014
11014
 
11015
11015
  // src/lending/margin/base/sumer/borrow.ts
11016
- function computeSumerBorrowDelta(amount, price2, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
11017
- const dollarAmount = amount * price2;
11016
+ function computeSumerBorrowDelta(amount3, price2, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
11017
+ const dollarAmount = amount3 * price2;
11018
11018
  const mode = irMode ?? 2;
11019
11019
  const updatedPositions = applyPositionDelta(
11020
11020
  positions,
@@ -11084,8 +11084,8 @@ function computeSumerBorrowDelta(amount, price2, targetMarketUid, balanceData2,
11084
11084
  }
11085
11085
 
11086
11086
  // src/lending/margin/base/sumer/repay.ts
11087
- function computeSumerRepayDelta(amount, price2, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
11088
- const dollarAmount = amount * price2;
11087
+ function computeSumerRepayDelta(amount3, price2, targetMarketUid, balanceData2, positions, apr, yieldParams, irMode) {
11088
+ const dollarAmount = amount3 * price2;
11089
11089
  const mode = irMode ?? 2;
11090
11090
  const updatedPositions = applyPositionDelta(
11091
11091
  positions,
@@ -11555,12 +11555,12 @@ function rateToApy(rate) {
11555
11555
  );
11556
11556
  }
11557
11557
  function parseLtv(ltv) {
11558
- let str4 = 0;
11558
+ let str5 = 0;
11559
11559
  try {
11560
- str4 = Number(formatUnits(BigInt(ltv), 18));
11560
+ str5 = Number(formatUnits(BigInt(ltv), 18));
11561
11561
  } catch (e) {
11562
11562
  }
11563
- return str4;
11563
+ return str5;
11564
11564
  }
11565
11565
  function liquidationPenaltyFromLltv(lltv) {
11566
11566
  if (!lltv || lltv <= 0) return 0;
@@ -17446,13 +17446,13 @@ function findVaultInfo(normalizedAddr, vaultData) {
17446
17446
  function buildAdjacencyList(vaultData) {
17447
17447
  const adj = /* @__PURE__ */ new Map();
17448
17448
  const knownVaults = /* @__PURE__ */ new Set();
17449
- for (const addr2 of vaultData.keys()) {
17450
- const norm = addr2.toLowerCase();
17449
+ for (const addr3 of vaultData.keys()) {
17450
+ const norm = addr3.toLowerCase();
17451
17451
  knownVaults.add(norm);
17452
17452
  adj.set(norm, /* @__PURE__ */ new Set());
17453
17453
  }
17454
- for (const [addr2, info] of vaultData) {
17455
- const from = addr2.toLowerCase();
17454
+ for (const [addr3, info] of vaultData) {
17455
+ const from = addr3.toLowerCase();
17456
17456
  const activeCollaterals = getActiveCollaterals(info.collateralLTVInfo);
17457
17457
  for (const to of activeCollaterals) {
17458
17458
  if (knownVaults.has(to) && from !== to) {
@@ -17495,8 +17495,8 @@ function findConnectedComponents(adj) {
17495
17495
  function deriveGovernor(vaultAddresses, vaultData) {
17496
17496
  const counts = /* @__PURE__ */ new Map();
17497
17497
  const zeroNorm = zeroAddress;
17498
- for (const addr2 of vaultAddresses) {
17499
- const info = findVaultInfo(addr2, vaultData);
17498
+ for (const addr3 of vaultAddresses) {
17499
+ const info = findVaultInfo(addr3, vaultData);
17500
17500
  if (!info) continue;
17501
17501
  const gov = info.governorAdmin?.toLowerCase();
17502
17502
  if (!gov || gov === zeroNorm) continue;
@@ -17521,8 +17521,8 @@ function deriveClusters(vaultData, includeSingletons = false) {
17521
17521
  if (!includeSingletons && component.length < 2) continue;
17522
17522
  if (!includeSingletons) {
17523
17523
  let hasActiveEdge = false;
17524
- for (const addr2 of component) {
17525
- const neighbors = adj.get(addr2);
17524
+ for (const addr3 of component) {
17525
+ const neighbors = adj.get(addr3);
17526
17526
  if (neighbors && neighbors.size > 0) {
17527
17527
  hasActiveEdge = true;
17528
17528
  break;
@@ -17531,9 +17531,9 @@ function deriveClusters(vaultData, includeSingletons = false) {
17531
17531
  if (!hasActiveEdge) continue;
17532
17532
  }
17533
17533
  const clusterVaultData = /* @__PURE__ */ new Map();
17534
- for (const addr2 of component) {
17535
- const info = findVaultInfo(addr2, vaultData);
17536
- if (info) clusterVaultData.set(addr2, info);
17534
+ for (const addr3 of component) {
17535
+ const info = findVaultInfo(addr3, vaultData);
17536
+ if (info) clusterVaultData.set(addr3, info);
17537
17537
  }
17538
17538
  clusters.push({
17539
17539
  governor: deriveGovernor(component, vaultData),
@@ -17558,21 +17558,21 @@ function toTokenAmount(raw, decimals) {
17558
17558
  }
17559
17559
  function identifyBorrowVaults(cluster) {
17560
17560
  const borrowVaults = /* @__PURE__ */ new Set();
17561
- for (const [addr2, info] of cluster.vaultData) {
17561
+ for (const [addr3, info] of cluster.vaultData) {
17562
17562
  const hasIRM = info.interestRateModel && info.interestRateModel.toLowerCase() !== zeroAddress;
17563
17563
  const hasActiveCollateral = (info.collateralLTVInfo ?? []).some(
17564
17564
  (ltv) => ltv.borrowLTV > 0n
17565
17565
  );
17566
17566
  if (hasIRM && hasActiveCollateral) {
17567
- borrowVaults.add(addr2.toLowerCase());
17567
+ borrowVaults.add(addr3.toLowerCase());
17568
17568
  }
17569
17569
  }
17570
17570
  return borrowVaults;
17571
17571
  }
17572
17572
  function buildReverseLTVIndex(cluster) {
17573
17573
  const index = /* @__PURE__ */ new Map();
17574
- for (const [addr2, info] of cluster.vaultData) {
17575
- const borrowVault = addr2.toLowerCase();
17574
+ for (const [addr3, info] of cluster.vaultData) {
17575
+ const borrowVault = addr3.toLowerCase();
17576
17576
  for (const ltv of info.collateralLTVInfo ?? []) {
17577
17577
  if (ltv.borrowLTV <= 0n) continue;
17578
17578
  const collateral = ltv.collateral.toLowerCase();
@@ -17623,17 +17623,17 @@ function buildTokenConfig(vaultAddr, reverseLTV, borrowVaults, vaultData) {
17623
17623
  }
17624
17624
  function buildEModes(borrowVaults, cluster) {
17625
17625
  const eModes = {};
17626
- for (const addr2 of borrowVaults) {
17627
- const info = findInfo(addr2, cluster.vaultData);
17626
+ for (const addr3 of borrowVaults) {
17627
+ const info = findInfo(addr3, cluster.vaultData);
17628
17628
  if (!info) continue;
17629
17629
  const activeLTVs = info.collateralLTVInfo.filter((l) => l.borrowLTV > 0n);
17630
- const avgBorrowLTV = activeLTVs.length > 0 ? activeLTVs.reduce((sum, l) => sum + ltvToNumber(l.borrowLTV), 0) / activeLTVs.length : 0;
17630
+ const avgBorrowLTV = activeLTVs.length > 0 ? activeLTVs.reduce((sum3, l) => sum3 + ltvToNumber(l.borrowLTV), 0) / activeLTVs.length : 0;
17631
17631
  const avgLiqLTV = activeLTVs.length > 0 ? activeLTVs.reduce(
17632
- (sum, l) => sum + ltvToNumber(l.liquidationLTV),
17632
+ (sum3, l) => sum3 + ltvToNumber(l.liquidationLTV),
17633
17633
  0
17634
17634
  ) / activeLTVs.length : 0;
17635
- eModes[addr2] = {
17636
- category: addr2,
17635
+ eModes[addr3] = {
17636
+ category: addr3,
17637
17637
  label: `${info.assetSymbol} Borrow (${info.vaultSymbol})`,
17638
17638
  borrowCollateralFactor: avgBorrowLTV,
17639
17639
  collateralFactor: avgLiqLTV,
@@ -17666,11 +17666,11 @@ function buildMetadata(info) {
17666
17666
  }
17667
17667
  function buildTokenEntry(info, config, collateralActive, borrowVaults, opts) {
17668
17668
  if (!info.asset) return void 0;
17669
- const addr2 = info.asset.toLowerCase();
17670
- const tokenMeta = opts.tokenList?.[addr2];
17669
+ const addr3 = info.asset.toLowerCase();
17670
+ const tokenMeta = opts.tokenList?.[addr3];
17671
17671
  const asset = {
17672
17672
  chainId: opts.chainId,
17673
- address: addr2,
17673
+ address: addr3,
17674
17674
  name: tokenMeta?.name ?? info.assetName,
17675
17675
  symbol: tokenMeta?.symbol ?? info.assetSymbol,
17676
17676
  decimals: tokenMeta?.decimals ?? Number(info.assetDecimals)
@@ -17750,9 +17750,9 @@ function buildTokenEntry(info, config, collateralActive, borrowVaults, opts) {
17750
17750
  params: { metadata: buildMetadata(info) }
17751
17751
  };
17752
17752
  }
17753
- function findInfo(addr2, vaultData) {
17753
+ function findInfo(addr3, vaultData) {
17754
17754
  for (const [key3, value] of vaultData) {
17755
- if (key3.toLowerCase() === addr2) return value;
17755
+ if (key3.toLowerCase() === addr3) return value;
17756
17756
  }
17757
17757
  return void 0;
17758
17758
  }
@@ -17767,8 +17767,8 @@ function normalizeCluster(cluster, opts) {
17767
17767
  }
17768
17768
  const eModes = buildEModes(borrowVaults, cluster);
17769
17769
  const data = {};
17770
- for (const [addr2, info] of cluster.vaultData) {
17771
- const norm = addr2.toLowerCase();
17770
+ for (const [addr3, info] of cluster.vaultData) {
17771
+ const norm = addr3.toLowerCase();
17772
17772
  const config = buildTokenConfig(
17773
17773
  norm,
17774
17774
  reverseLTV,
@@ -17913,8 +17913,8 @@ var getEulerV2ReservesDataConverter = (lender, chainId, prices, additionalYields
17913
17913
  var BASE_CALLS_PER_RESERVE = 5;
17914
17914
  var CALLS_PER_SPOKE_TAIL = 1;
17915
17915
  var MAX_HUB_ASSETS = 25;
17916
- function isValidAddress(addr2) {
17917
- return !!addr2 && addr2 !== "0x" && addr2.length > 2;
17916
+ function isValidAddress(addr3) {
17917
+ return !!addr3 && addr3 !== "0x" && addr3.length > 2;
17918
17918
  }
17919
17919
  function getDynamicConfigCount(spokeEntry) {
17920
17920
  const max = spokeEntry?.dynamicConfigKeyMax ?? 0;
@@ -18258,8 +18258,8 @@ function normalizeAaveV4(spokeDataList, chainId, spokeLenderKeyArg, prices, addi
18258
18258
  }
18259
18259
 
18260
18260
  // src/lending/public-data/aave-v4-type/publicCallParse.ts
18261
- function isValidAddress2(addr2) {
18262
- return !!addr2 && addr2 !== "0x" && addr2.length > 2;
18261
+ function isValidAddress2(addr3) {
18262
+ return !!addr3 && addr3 !== "0x" && addr3.length > 2;
18263
18263
  }
18264
18264
  var getAaveV4ReservesDataConverter = (lender, chainId, prices, additionalYields, tokenList = {}) => {
18265
18265
  const expectedCalls = getAaveV4ExpectedCallCount(chainId, lender);
@@ -19014,7 +19014,7 @@ var buildFluidCall = (chainId, _lender) => {
19014
19014
 
19015
19015
  // src/lending/public-data/fluid/publicCallParse.ts
19016
19016
  var FLUID_EEE_LOWER = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
19017
- var normalizeUnderlying = (addr2) => addr2 === FLUID_EEE_LOWER ? zeroAddress : addr2;
19017
+ var normalizeUnderlying = (addr3) => addr3 === FLUID_EEE_LOWER ? zeroAddress : addr3;
19018
19018
  var FLUID_RATE_SCALE = 100;
19019
19019
  var scaleFluidRate = (raw) => {
19020
19020
  if (raw === void 0 || raw === null) return 0;
@@ -19517,9 +19517,9 @@ var getGearboxV3PublicDataConverter = (_lender, chainId, prices, additionalYield
19517
19517
  const underlyingPrice = prices[underlyingPriceKey] ?? 0;
19518
19518
  const debtByCm = {};
19519
19519
  for (const dp of pool.creditManagerDebtParams ?? []) {
19520
- const addr2 = (dp?.creditManager ?? "").toString().toLowerCase();
19521
- if (!addr2) continue;
19522
- debtByCm[addr2] = {
19520
+ const addr3 = (dp?.creditManager ?? "").toString().toLowerCase();
19521
+ if (!addr3) continue;
19522
+ debtByCm[addr3] = {
19523
19523
  borrowed: BigInt(dp.borrowed ?? 0),
19524
19524
  limit: BigInt(dp.limit ?? 0),
19525
19525
  available: BigInt(dp.available ?? 0)
@@ -21931,7 +21931,7 @@ async function fetchTellerMarkets(chainId) {
21931
21931
  }
21932
21932
  return null;
21933
21933
  };
21934
- const num12 = (i) => {
21934
+ const num14 = (i) => {
21935
21935
  const b = big16(i);
21936
21936
  return b === null ? null : Number(b);
21937
21937
  };
@@ -21941,9 +21941,9 @@ async function fetchTellerMarkets(chainId) {
21941
21941
  config,
21942
21942
  available: big16(base),
21943
21943
  committed: big16(base + 1),
21944
- minRateBps: num12(base + 2),
21944
+ minRateBps: num14(base + 2),
21945
21945
  collateralPerPrincipal: big16(base + 3),
21946
- maxLoanDuration: num12(base + 4),
21946
+ maxLoanDuration: num14(base + 4),
21947
21947
  marketId: big16(base + 5),
21948
21948
  totalAssets: big16(base + 6)
21949
21949
  };
@@ -22180,9 +22180,9 @@ var TermMaxApiSource = class {
22180
22180
  if (!data) return null;
22181
22181
  const assetDecimals = /* @__PURE__ */ new Map();
22182
22182
  for (const a of Array.isArray(data.assetConfigs) ? data.assetConfigs : []) {
22183
- const addr2 = lower(a?.contractAddress ?? a?.assetAddress);
22183
+ const addr3 = lower(a?.contractAddress ?? a?.assetAddress);
22184
22184
  const dec = Number(a?.decimals ?? a?.assetDecimals);
22185
- if (addr2 && Number.isFinite(dec)) assetDecimals.set(addr2, dec);
22185
+ if (addr3 && Number.isFinite(dec)) assetDecimals.set(addr3, dec);
22186
22186
  }
22187
22187
  const markets = [];
22188
22188
  for (const m of Array.isArray(data.markets) ? data.markets : []) {
@@ -22906,20 +22906,20 @@ async function fetchInverseMarkets(lender, chainId) {
22906
22906
  if (Object.keys(byAddr).length > 0) {
22907
22907
  const rows = markets.map((market) => {
22908
22908
  const m = byAddr[market.address.toLowerCase()];
22909
- const num12 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
22909
+ const num14 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
22910
22910
  return {
22911
22911
  market,
22912
- totalDebt: num12(m?.totalDebt),
22913
- dolaLiquidity: num12(m?.dolaLiquidity),
22914
- leftToBorrow: num12(m?.leftToBorrow),
22915
- price: num12(m?.price),
22912
+ totalDebt: num14(m?.totalDebt),
22913
+ dolaLiquidity: num14(m?.dolaLiquidity),
22914
+ leftToBorrow: num14(m?.leftToBorrow),
22915
+ price: num14(m?.price),
22916
22916
  borrowPaused: typeof m?.borrowPaused === "boolean" ? m.borrowPaused : null,
22917
- dailyBorrows: num12(m?.dailyBorrows),
22917
+ dailyBorrows: num14(m?.dailyBorrows),
22918
22918
  // The API serves it as a DECIMAL (`replenishmentIncentive: 0.1`),
22919
22919
  // unlike the on-chain bps — normalize here, and fall back to the
22920
22920
  // curated metadata value when the field is missing.
22921
22921
  replenishmentIncentiveBps: (() => {
22922
- const dec = num12(m?.replenishmentIncentive);
22922
+ const dec = num14(m?.replenishmentIncentive);
22923
22923
  if (dec !== null) return Math.round(dec * 1e4);
22924
22924
  const meta = Number(market.replenishmentIncentiveBps);
22925
22925
  return Number.isFinite(meta) ? meta : null;
@@ -23395,10 +23395,10 @@ async function fetchResupplyMarkets(lender, chainId) {
23395
23395
  } catch {
23396
23396
  dec = [];
23397
23397
  }
23398
- const addr2 = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{40}$/.test(v) && !/^0x0+$/.test(v) ? v : void 0;
23398
+ const addr3 = (v) => typeof v === "string" && /^0x[0-9a-fA-F]{40}$/.test(v) && !/^0x0+$/.test(v) ? v : void 0;
23399
23399
  const wrapped = pending.map((_3, i) => {
23400
- const curve = addr2(dec[i * 4 + 2]);
23401
- const frax = addr2(dec[i * 4 + 3]);
23400
+ const curve = addr3(dec[i * 4 + 2]);
23401
+ const frax = addr3(dec[i * 4 + 3]);
23402
23402
  return {
23403
23403
  token: curve ?? frax,
23404
23404
  family: curve ? "curvelend" : frax ? "fraxlend" : void 0
@@ -23547,7 +23547,7 @@ async function fetchResupplyMarkets(lender, chainId) {
23547
23547
  return { lender, config, pairs, rsup };
23548
23548
  }
23549
23549
  async function readRewardContext(chainId, registry, utilities) {
23550
- const addr2 = (v) => typeof v === "string" && v.startsWith("0x") && !/^0x0+$/.test(v) ? v : void 0;
23550
+ const addr3 = (v) => typeof v === "string" && v.startsWith("0x") && !/^0x0+$/.test(v) ? v : void 0;
23551
23551
  try {
23552
23552
  const first = await multicallRetryUniversal({
23553
23553
  chain: chainId,
@@ -23563,9 +23563,9 @@ async function readRewardContext(chainId, registry, utilities) {
23563
23563
  ],
23564
23564
  allowFailure: true
23565
23565
  });
23566
- const rewardHandler = addr2(first[0]);
23567
- const govToken = addr2(first[1]);
23568
- const convexPoolUtil = utilities ? addr2(first[2]) : void 0;
23566
+ const rewardHandler = addr3(first[0]);
23567
+ const govToken = addr3(first[1]);
23568
+ const convexPoolUtil = utilities ? addr3(first[2]) : void 0;
23569
23569
  if (!rewardHandler || !govToken) return { convexPoolUtil };
23570
23570
  const [emissions] = await multicallRetryUniversal({
23571
23571
  chain: chainId,
@@ -23573,7 +23573,7 @@ async function readRewardContext(chainId, registry, utilities) {
23573
23573
  abi: ResupplyRewardHandlerAbi,
23574
23574
  allowFailure: true
23575
23575
  });
23576
- const pairEmissions = addr2(emissions);
23576
+ const pairEmissions = addr3(emissions);
23577
23577
  if (!pairEmissions) return { convexPoolUtil };
23578
23578
  const stream = await multicallRetryUniversal({
23579
23579
  chain: chainId,
@@ -27444,8 +27444,8 @@ function getSubAccountAddress(owner, index) {
27444
27444
  const suffix = newLastByte.toString(16).padStart(2, "0");
27445
27445
  return (prefix + suffix).toLowerCase();
27446
27446
  }
27447
- function getSubAccountIndex(addr2, owner) {
27448
- const addrLastByte = parseInt(addr2.slice(40), 16);
27447
+ function getSubAccountIndex(addr3, owner) {
27448
+ const addrLastByte = parseInt(addr3.slice(40), 16);
27449
27449
  if (!owner) return addrLastByte;
27450
27450
  const ownerLastByte = parseInt(owner.slice(40), 16);
27451
27451
  return (addrLastByte ^ ownerLastByte) & 255;
@@ -30593,7 +30593,7 @@ function toBigInt7(v) {
30593
30593
  }
30594
30594
  }
30595
30595
  var FLUID_EEE_LOWER2 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
30596
- var normalizeUnderlying2 = (addr2) => addr2 === FLUID_EEE_LOWER2 ? zeroAddress : addr2;
30596
+ var normalizeUnderlying2 = (addr3) => addr3 === FLUID_EEE_LOWER2 ? zeroAddress : addr3;
30597
30597
  function toBigInt8(v) {
30598
30598
  if (v === void 0 || v === null || v === "0x") return 0n;
30599
30599
  if (typeof v === "bigint") return v;
@@ -30952,10 +30952,10 @@ var getDolomiteUserDataConverter = (lender, chainId, account, metaMap) => {
30952
30952
  const meta = metaMap?.[key3];
30953
30953
  if (!meta) return;
30954
30954
  const decimals = meta.asset?.decimals ?? 18;
30955
- const amount = parseRawAmount(wei.value, decimals);
30955
+ const amount3 = parseRawAmount(wei.value, decimals);
30956
30956
  const isSupply = wei.sign;
30957
- const deposits = isSupply ? amount : "0";
30958
- const debt = isSupply ? "0" : amount;
30957
+ const deposits = isSupply ? amount3 : "0";
30958
+ const debt = isSupply ? "0" : amount3;
30959
30959
  const debtPar = isSupply ? "0" : pars[k]?.value?.toString() ?? "0";
30960
30960
  const price2 = getDisplayPrice(meta);
30961
30961
  const oPrice = getOraclePrice(meta);
@@ -31030,7 +31030,7 @@ function readUpdatedLender(updateResult) {
31030
31030
  var getMidnightUserDataConverter = (_lender, chainId, account, meta) => {
31031
31031
  const markets = midnightMarketsByChain(chainId);
31032
31032
  const totalCalls = markets.reduce(
31033
- (sum, m) => sum + midnightMarketCallCount(m.collateralParams.length),
31033
+ (sum3, m) => sum3 + midnightMarketCallCount(m.collateralParams.length),
31034
31034
  0
31035
31035
  );
31036
31036
  return [
@@ -31154,7 +31154,7 @@ function toBigInt11(v) {
31154
31154
  var getTermUserDataConverter = (_lender, chainId, account, meta) => {
31155
31155
  const markets = termMarketsByChain(chainId);
31156
31156
  const totalCalls = markets.reduce(
31157
- (sum, m) => sum + termMarketCallCount(m.collateralParams.length),
31157
+ (sum3, m) => sum3 + termMarketCallCount(m.collateralParams.length),
31158
31158
  0
31159
31159
  );
31160
31160
  return [
@@ -31375,11 +31375,11 @@ var getExactlyUserDataConverter = (_lender, chainId, account, meta) => {
31375
31375
  for (const p of m.fixedBorrowPositions) {
31376
31376
  const maturity = Number(p.maturity);
31377
31377
  const trancheStr = parseRawAmount(p.previewValue.toString(), decimals);
31378
- const isMatured = maturity < now;
31378
+ const isMatured2 = maturity < now;
31379
31379
  const face = faceOf(p);
31380
31380
  const faceStr = parseRawAmount(face.toString(), decimals);
31381
- const discount = isMatured ? "0" : parseRawAmount((face - p.previewValue).toString(), decimals);
31382
- const penalty = isMatured ? parseRawAmount((p.previewValue - face).toString(), decimals) : "0";
31381
+ const discount = isMatured2 ? "0" : parseRawAmount((face - p.previewValue).toString(), decimals);
31382
+ const penalty = isMatured2 ? parseRawAmount((p.previewValue - face).toString(), decimals) : "0";
31383
31383
  posData[`${loanUid}#${maturity}`] = {
31384
31384
  marketUid: loanUid,
31385
31385
  underlying: assetAddr,
@@ -31408,7 +31408,7 @@ var getExactlyUserDataConverter = (_lender, chainId, account, meta) => {
31408
31408
  p.position.fee.toString(),
31409
31409
  decimals
31410
31410
  ),
31411
- isMatured,
31411
+ isMatured: isMatured2,
31412
31412
  /** rebate if repaid now, before maturity (never a fee) */
31413
31413
  earlyRepayDiscount: discount,
31414
31414
  /** penalty already accrued past maturity */
@@ -31419,7 +31419,7 @@ var getExactlyUserDataConverter = (_lender, chainId, account, meta) => {
31419
31419
  decimals
31420
31420
  ),
31421
31421
  latePenaltyApr: penaltyApr,
31422
- secondsLate: isMatured ? now - maturity : 0
31422
+ secondsLate: isMatured2 ? now - maturity : 0
31423
31423
  }
31424
31424
  };
31425
31425
  }
@@ -32628,7 +32628,7 @@ var getTellerUserDataConverter = (_lender, chainId, account, meta) => {
32628
32628
  const loanDuration = Number(big12(field10(loanDetails, "loanDuration", 6)));
32629
32629
  const aprBps = Number(big12(field10(terms, "APR", 2)));
32630
32630
  const maturity = acceptedTs > 0 ? acceptedTs + loanDuration : void 0;
32631
- const isMatured = defaulted || maturity !== void 0 && maturity < now;
32631
+ const isMatured2 = defaulted || maturity !== void 0 && maturity < now;
32632
32632
  const collStr = parseRawAmount(collAmount.toString(), collDecimals);
32633
32633
  const collNum = Number(collStr);
32634
32634
  const debtStr = parseRawAmount(owedTotal.toString(), principalDecimals);
@@ -32684,7 +32684,7 @@ var getTellerUserDataConverter = (_lender, chainId, account, meta) => {
32684
32684
  apr: aprBps / 100,
32685
32685
  maturity,
32686
32686
  accruedInterest: interestStr,
32687
- isMatured
32687
+ isMatured: isMatured2
32688
32688
  }
32689
32689
  }
32690
32690
  };
@@ -32783,7 +32783,7 @@ var getTermMaxUserDataConverter = (_lender, chainId, account, meta) => {
32783
32783
  const loanDec = loanMeta?.asset?.decimals ?? market.debtDecimals;
32784
32784
  const collDec = collMeta?.asset?.decimals ?? market.collateralDecimals;
32785
32785
  const maturity = Number(market.maturity);
32786
- const isMatured = maturity > 0 && maturity <= now;
32786
+ const isMatured2 = maturity > 0 && maturity <= now;
32787
32787
  const positionsByAccount = {};
32788
32788
  const modes = {};
32789
32789
  const hist = {};
@@ -32859,7 +32859,7 @@ var getTermMaxUserDataConverter = (_lender, chainId, account, meta) => {
32859
32859
  isDynamic: false,
32860
32860
  debt: debtStr,
32861
32861
  maturity: maturity || void 0,
32862
- isMatured
32862
+ isMatured: isMatured2
32863
32863
  }
32864
32864
  }
32865
32865
  };
@@ -38107,29 +38107,29 @@ async function getMergedUserData(chainId, balanceQueries, permissionParams, lend
38107
38107
  });
38108
38108
  return parseMergedResult(chainId, rawResults, prepared, lenderState);
38109
38109
  }
38110
- function toCompoundV2Shares(entry, amount) {
38110
+ function toCompoundV2Shares(entry, amount3) {
38111
38111
  const raw = entry.params?.exchangeRateCurrent;
38112
- if (!raw || raw === "0x") return amount;
38112
+ if (!raw || raw === "0x") return amount3;
38113
38113
  try {
38114
38114
  const exRate = BigInt(raw);
38115
- if (exRate === 0n) return amount;
38116
- return amount * 10n ** 18n / exRate * 1001n / 1000n;
38115
+ if (exRate === 0n) return amount3;
38116
+ return amount3 * 10n ** 18n / exRate * 1001n / 1000n;
38117
38117
  } catch {
38118
- return amount;
38118
+ return amount3;
38119
38119
  }
38120
38120
  }
38121
- function toSiloShares(entry, amount, chainId, lender, tokenAddress) {
38121
+ function toSiloShares(entry, amount3, chainId, lender, tokenAddress) {
38122
38122
  const raw = entry.params?.collateralRate;
38123
- if (!raw || raw === "0x") return amount;
38123
+ if (!raw || raw === "0x") return amount3;
38124
38124
  try {
38125
38125
  const rate = BigInt(raw);
38126
- if (rate === 0n) return amount;
38126
+ if (rate === 0n) return amount3;
38127
38127
  const half = getSiloHalfForUnderlying(chainId, lender, tokenAddress);
38128
- if (!half) return amount;
38128
+ if (!half) return amount3;
38129
38129
  const oneUnit = BigInt(10) ** BigInt(half.decimals);
38130
- return amount * oneUnit / rate * 1001n / 1000n;
38130
+ return amount3 * oneUnit / rate * 1001n / 1000n;
38131
38131
  } catch {
38132
- return amount;
38132
+ return amount3;
38133
38133
  }
38134
38134
  }
38135
38135
  function resolveDebitDataKey(chainId, lender, tokenAddress, cToken, isProtected) {
@@ -38165,7 +38165,7 @@ function resolveDebitDataKey(chainId, lender, tokenAddress, cToken, isProtected)
38165
38165
  return tokenAddress.toLowerCase();
38166
38166
  }
38167
38167
  function needsLenderApproval(params) {
38168
- const { lender, lenderDebitData, tokenAddress, amount, chainId, cToken, isProtected } = params;
38168
+ const { lender, lenderDebitData, tokenAddress, amount: amount3, chainId, cToken, isProtected } = params;
38169
38169
  if (!lenderDebitData) return true;
38170
38170
  if (isAaveV4Type(lender)) {
38171
38171
  const key4 = (params.aaveV4Spoke ?? tokenAddress).toLowerCase();
@@ -38182,33 +38182,33 @@ function needsLenderApproval(params) {
38182
38182
  const entry = lenderDebitData[key3];
38183
38183
  if (!entry || entry.amount === void 0) return true;
38184
38184
  if (isCompoundV2Type(lender) || isVenusType(lender)) {
38185
- const requiredShares = toCompoundV2Shares(entry, amount);
38185
+ const requiredShares = toCompoundV2Shares(entry, amount3);
38186
38186
  return entry.amount < requiredShares;
38187
38187
  }
38188
38188
  if (isSiloV2Type(lender) || isSiloV3Type(lender)) {
38189
- const requiredShares = toSiloShares(entry, amount, chainId, lender, tokenAddress);
38189
+ const requiredShares = toSiloShares(entry, amount3, chainId, lender, tokenAddress);
38190
38190
  return entry.amount < requiredShares;
38191
38191
  }
38192
38192
  if (isCompoundV3(lender)) {
38193
38193
  return entry.amount === 0n;
38194
38194
  }
38195
- return entry.amount < amount;
38195
+ return entry.amount < amount3;
38196
38196
  }
38197
38197
  function needsTokenApproval(params) {
38198
- const { debitData, spender, amount, chainId, usePermit2 } = params;
38198
+ const { debitData, spender, amount: amount3, chainId, usePermit2 } = params;
38199
38199
  if (!debitData) return true;
38200
38200
  const spenderLower = spender.toLowerCase();
38201
38201
  if (usePermit2) {
38202
38202
  const p2 = debitData.permit2?.[spenderLower];
38203
- return !p2 || p2.amount < amount;
38203
+ return !p2 || p2.amount < amount3;
38204
38204
  }
38205
38205
  const permit2Address = getPermit2ContractAddress(chainId).toLowerCase();
38206
38206
  if (spenderLower === permit2Address) {
38207
38207
  const p2 = debitData.permit2?.[spenderLower];
38208
- if (p2 && p2.amount >= amount) return false;
38208
+ if (p2 && p2.amount >= amount3) return false;
38209
38209
  }
38210
38210
  const allowance = debitData.allowances?.[spenderLower] ?? 0n;
38211
- return allowance < amount;
38211
+ return allowance < amount3;
38212
38212
  }
38213
38213
  var MORPHO_USER_SUBGRAPH_URLS = {
38214
38214
  [Chain.SEI_NETWORK]: "https://api.goldsky.com/api/public/project_cmiergfbv4vma01vb642yaeam/subgraphs/morphoblue-sei/1.0.1/gn",
@@ -38412,10 +38412,10 @@ async function fetchBalancesFromApi(chainId, account, proxyConfig) {
38412
38412
 
38413
38413
  // src/lending/user-data/summary/utils.ts
38414
38414
  function calculateWeightedAverage(items) {
38415
- const totalWeight = items.reduce((sum, item) => sum + item.weight, 0);
38415
+ const totalWeight = items.reduce((sum3, item) => sum3 + item.weight, 0);
38416
38416
  if (totalWeight === 0) return 0;
38417
38417
  const weightedSum = items.reduce(
38418
- (sum, item) => sum + item.value * item.weight,
38418
+ (sum3, item) => sum3 + item.value * item.weight,
38419
38419
  0
38420
38420
  );
38421
38421
  return weightedSum / totalWeight;
@@ -38715,10 +38715,10 @@ function fuseLenderData(userDataResult, summary) {
38715
38715
  }
38716
38716
 
38717
38717
  // src/lending/margin/base/standard/deposit.ts
38718
- function computeDepositDelta(amount, price2, balanceData2, config, modeId, createNewSubAccount = false, apr, yieldParams) {
38718
+ function computeDepositDelta(amount3, price2, balanceData2, config, modeId, createNewSubAccount = false, apr, yieldParams) {
38719
38719
  const { borrowCollateralFactor, collateralFactor } = getAssetConfig(config, modeId);
38720
38720
  const base = createNewSubAccount ? EMPTY_BALANCE : balanceData2;
38721
- const dollarAmount = amount * price2;
38721
+ const dollarAmount = amount3 * price2;
38722
38722
  const postTrade = {
38723
38723
  ...base,
38724
38724
  borrowDiscountedCollateral: base.borrowDiscountedCollateral + borrowCollateralFactor * dollarAmount,
@@ -38765,13 +38765,13 @@ function computeDepositDelta(amount, price2, balanceData2, config, modeId, creat
38765
38765
  }
38766
38766
 
38767
38767
  // src/lending/margin/base/deposit.ts
38768
- function computeDepositDelta2(lender, amount, price2, balanceData2, config, modeId, createNewSubAccount, apr, yieldParams, targetMarketUid, positions) {
38768
+ function computeDepositDelta2(lender, amount3, price2, balanceData2, config, modeId, createNewSubAccount, apr, yieldParams, targetMarketUid, positions) {
38769
38769
  if (isSumerType(lender)) {
38770
38770
  if (!positions || targetMarketUid === void 0) {
38771
38771
  throw new Error("Sumer operations require positions and targetMarketUid");
38772
38772
  }
38773
38773
  return computeSumerDepositDelta(
38774
- amount,
38774
+ amount3,
38775
38775
  price2,
38776
38776
  targetMarketUid,
38777
38777
  balanceData2,
@@ -38785,7 +38785,7 @@ function computeDepositDelta2(lender, amount, price2, balanceData2, config, mode
38785
38785
  throw new Error("Standard operations require config and modeId");
38786
38786
  }
38787
38787
  return computeDepositDelta(
38788
- amount,
38788
+ amount3,
38789
38789
  price2,
38790
38790
  balanceData2,
38791
38791
  config,
@@ -38797,9 +38797,9 @@ function computeDepositDelta2(lender, amount, price2, balanceData2, config, mode
38797
38797
  }
38798
38798
 
38799
38799
  // src/lending/margin/base/standard/withdraw.ts
38800
- function computeWithdrawDelta(amount, price2, balanceData2, config, modeId, apr, yieldParams) {
38800
+ function computeWithdrawDelta(amount3, price2, balanceData2, config, modeId, apr, yieldParams) {
38801
38801
  const { borrowCollateralFactor, collateralFactor } = getAssetConfig(config, modeId);
38802
- const dollarAmount = amount * price2;
38802
+ const dollarAmount = amount3 * price2;
38803
38803
  const postTrade = {
38804
38804
  ...balanceData2,
38805
38805
  borrowDiscountedCollateral: balanceData2.borrowDiscountedCollateral - borrowCollateralFactor * dollarAmount,
@@ -38846,13 +38846,13 @@ function computeWithdrawDelta(amount, price2, balanceData2, config, modeId, apr,
38846
38846
  }
38847
38847
 
38848
38848
  // src/lending/margin/base/withdraw.ts
38849
- function computeWithdrawDelta2(lender, amount, price2, balanceData2, config, modeId, apr, yieldParams, targetMarketUid, positions) {
38849
+ function computeWithdrawDelta2(lender, amount3, price2, balanceData2, config, modeId, apr, yieldParams, targetMarketUid, positions) {
38850
38850
  if (isSumerType(lender)) {
38851
38851
  if (!positions || targetMarketUid === void 0) {
38852
38852
  throw new Error("Sumer operations require positions and targetMarketUid");
38853
38853
  }
38854
38854
  return computeSumerWithdrawDelta(
38855
- amount,
38855
+ amount3,
38856
38856
  price2,
38857
38857
  targetMarketUid,
38858
38858
  balanceData2,
@@ -38865,7 +38865,7 @@ function computeWithdrawDelta2(lender, amount, price2, balanceData2, config, mod
38865
38865
  throw new Error("Standard operations require config and modeId");
38866
38866
  }
38867
38867
  return computeWithdrawDelta(
38868
- amount,
38868
+ amount3,
38869
38869
  price2,
38870
38870
  balanceData2,
38871
38871
  config,
@@ -38876,9 +38876,9 @@ function computeWithdrawDelta2(lender, amount, price2, balanceData2, config, mod
38876
38876
  }
38877
38877
 
38878
38878
  // src/lending/margin/base/standard/borrow.ts
38879
- function computeBorrowDelta(amount, price2, balanceData2, config, modeId, apr, yieldParams, irMode) {
38879
+ function computeBorrowDelta(amount3, price2, balanceData2, config, modeId, apr, yieldParams, irMode) {
38880
38880
  const { borrowFactor } = getAssetConfig(config, modeId);
38881
- const dollarAmount = amount * price2;
38881
+ const dollarAmount = amount3 * price2;
38882
38882
  const postTrade = {
38883
38883
  ...balanceData2,
38884
38884
  debt: balanceData2.debt + dollarAmount,
@@ -38927,13 +38927,13 @@ function computeBorrowDelta(amount, price2, balanceData2, config, modeId, apr, y
38927
38927
  }
38928
38928
 
38929
38929
  // src/lending/margin/base/borrow.ts
38930
- function computeBorrowDelta2(lender, amount, price2, balanceData2, config, modeId, apr, yieldParams, irMode, targetMarketUid, positions) {
38930
+ function computeBorrowDelta2(lender, amount3, price2, balanceData2, config, modeId, apr, yieldParams, irMode, targetMarketUid, positions) {
38931
38931
  if (isSumerType(lender)) {
38932
38932
  if (!positions || targetMarketUid === void 0) {
38933
38933
  throw new Error("Sumer operations require positions and targetMarketUid");
38934
38934
  }
38935
38935
  return computeSumerBorrowDelta(
38936
- amount,
38936
+ amount3,
38937
38937
  price2,
38938
38938
  targetMarketUid,
38939
38939
  balanceData2,
@@ -38947,7 +38947,7 @@ function computeBorrowDelta2(lender, amount, price2, balanceData2, config, modeI
38947
38947
  throw new Error("Standard operations require config and modeId");
38948
38948
  }
38949
38949
  return computeBorrowDelta(
38950
- amount,
38950
+ amount3,
38951
38951
  price2,
38952
38952
  balanceData2,
38953
38953
  config,
@@ -38959,9 +38959,9 @@ function computeBorrowDelta2(lender, amount, price2, balanceData2, config, modeI
38959
38959
  }
38960
38960
 
38961
38961
  // src/lending/margin/base/standard/repay.ts
38962
- function computeRepayDelta(amount, price2, balanceData2, config, modeId, apr, yieldParams, irMode) {
38962
+ function computeRepayDelta(amount3, price2, balanceData2, config, modeId, apr, yieldParams, irMode) {
38963
38963
  const { borrowFactor } = getAssetConfig(config, modeId);
38964
- const dollarAmount = amount * price2;
38964
+ const dollarAmount = amount3 * price2;
38965
38965
  const postTrade = {
38966
38966
  ...balanceData2,
38967
38967
  debt: balanceData2.debt - dollarAmount,
@@ -39010,13 +39010,13 @@ function computeRepayDelta(amount, price2, balanceData2, config, modeId, apr, yi
39010
39010
  }
39011
39011
 
39012
39012
  // src/lending/margin/base/repay.ts
39013
- function computeRepayDelta2(lender, amount, price2, balanceData2, config, modeId, apr, yieldParams, irMode, targetMarketUid, positions) {
39013
+ function computeRepayDelta2(lender, amount3, price2, balanceData2, config, modeId, apr, yieldParams, irMode, targetMarketUid, positions) {
39014
39014
  if (isSumerType(lender)) {
39015
39015
  if (!positions || targetMarketUid === void 0) {
39016
39016
  throw new Error("Sumer operations require positions and targetMarketUid");
39017
39017
  }
39018
39018
  return computeSumerRepayDelta(
39019
- amount,
39019
+ amount3,
39020
39020
  price2,
39021
39021
  targetMarketUid,
39022
39022
  balanceData2,
@@ -39030,7 +39030,7 @@ function computeRepayDelta2(lender, amount, price2, balanceData2, config, modeId
39030
39030
  throw new Error("Standard operations require config and modeId");
39031
39031
  }
39032
39032
  return computeRepayDelta(
39033
- amount,
39033
+ amount3,
39034
39034
  price2,
39035
39035
  balanceData2,
39036
39036
  config,
@@ -39564,7 +39564,7 @@ function getMaxAmountClose(borrowDiscountedCollateral, adjustedDebt, ltvIn, bfOu
39564
39564
  function averageDataLastN(arr, n = 7) {
39565
39565
  const last = arr.slice(-n);
39566
39566
  if (last.length === 0) return 0;
39567
- return last.reduce((sum, x) => sum + x.data, 0) / last.length;
39567
+ return last.reduce((sum3, x) => sum3 + x.data, 0) / last.length;
39568
39568
  }
39569
39569
  var safeFetch = async (label, fn) => {
39570
39570
  try {
@@ -39905,7 +39905,7 @@ var hbhypeFetcher = {
39905
39905
  }
39906
39906
  const delegations = result.data.delegations;
39907
39907
  const totalApr = delegations.reduce(
39908
- (sum, validator) => sum + Number(validator.apr ?? 0),
39908
+ (sum3, validator) => sum3 + Number(validator.apr ?? 0),
39909
39909
  0
39910
39910
  );
39911
39911
  const averageApr = totalApr / delegations.length;
@@ -46061,13 +46061,13 @@ var gmxFetcher = {
46061
46061
  fetch: async () => {
46062
46062
  const { apy } = await fetchGmxRawData(GMX_CHAIN, GMX_DEFAULT_APY_PERIOD);
46063
46063
  const rData = {};
46064
- for (const [addr2, d] of Object.entries(apy.markets ?? {})) {
46065
- const a = addr2.toLowerCase();
46064
+ for (const [addr3, d] of Object.entries(apy.markets ?? {})) {
46065
+ const a = addr3.toLowerCase();
46066
46066
  if (a === gmx_eth_usd_address) rData[gmx_eth_usd] = apyToApr(d.apy) * 100;
46067
46067
  if (a === gmx_btc_usd_address) rData[gmx_btc_usd] = apyToApr(d.apy) * 100;
46068
46068
  }
46069
- for (const [addr2, d] of Object.entries(apy.glvs ?? {})) {
46070
- const a = addr2.toLowerCase();
46069
+ for (const [addr3, d] of Object.entries(apy.glvs ?? {})) {
46070
+ const a = addr3.toLowerCase();
46071
46071
  if (a === glv_wbtc_usdc_address)
46072
46072
  rData[glv_wbtc_usdc] = apyToApr(d.apy) * 100;
46073
46073
  if (a === glv_weth_usdc_address)
@@ -46110,8 +46110,8 @@ async function fetchPendlePricesForAllChain(lists = {}, assetType = ["YT", "PT"]
46110
46110
  let prices = {};
46111
46111
  Object.entries(data).forEach(([key3, val]) => {
46112
46112
  const [chainId, address] = key3.split("-");
46113
- const assetKey = lists[chainId]?.list?.[address.toLowerCase()]?.assetGroup ?? key3;
46114
- prices[assetKey] = val;
46113
+ const assetKey2 = lists[chainId]?.list?.[address.toLowerCase()]?.assetGroup ?? key3;
46114
+ prices[assetKey2] = val;
46115
46115
  });
46116
46116
  return prices;
46117
46117
  } catch (error) {
@@ -46158,17 +46158,17 @@ async function fetchPendleYields(lists = {}) {
46158
46158
  const ptPrice = prices[market.pt];
46159
46159
  const ytPrice = prices[market.yt];
46160
46160
  const [chainId, address] = market.pt.split("-");
46161
- const assetKey = lists[chainId]?.list?.[address.toLowerCase()]?.assetGroup;
46162
- if (!assetKey) return;
46161
+ const assetKey2 = lists[chainId]?.list?.[address.toLowerCase()]?.assetGroup;
46162
+ if (!assetKey2) return;
46163
46163
  const expiry = new Date(market.expiry);
46164
46164
  if (expiry <= now) {
46165
- yields[assetKey] = 0;
46165
+ yields[assetKey2] = 0;
46166
46166
  return;
46167
46167
  }
46168
46168
  if (ytPrice && ytPrice > 0) {
46169
46169
  const yearFraction = yearFractionToExpiry(market.expiry, now);
46170
46170
  const apr = ytPrice / ptPrice * 100 / yearFraction;
46171
- yields[assetKey] = apr;
46171
+ yields[assetKey2] = apr;
46172
46172
  }
46173
46173
  });
46174
46174
  });
@@ -46347,7 +46347,7 @@ var capFetcher = {
46347
46347
  const ts = res?.timeseries ?? [];
46348
46348
  const last7 = ts.slice(-7);
46349
46349
  if (last7.length === 0) return { [stcUSD]: 0 };
46350
- const avg = last7.reduce((sum, e) => sum + Number(e.stakingApr), 0) / last7.length;
46350
+ const avg = last7.reduce((sum3, e) => sum3 + Number(e.stakingApr), 0) / last7.length;
46351
46351
  return { [stcUSD]: avg * 100 };
46352
46352
  }
46353
46353
  };
@@ -46602,11 +46602,11 @@ var yearnFetcher = {
46602
46602
  }
46603
46603
  for (const v of vaults) {
46604
46604
  const address = (v.address ?? "").toLowerCase();
46605
- const assetKey = lists[chainId]?.list?.[address]?.assetGroup;
46606
- if (!assetKey) continue;
46605
+ const assetKey2 = lists[chainId]?.list?.[address]?.assetGroup;
46606
+ if (!assetKey2) continue;
46607
46607
  const apr = yearnVaultApr(v);
46608
46608
  if (apr == null) continue;
46609
- out[assetKey] = apr;
46609
+ out[assetKey2] = apr;
46610
46610
  }
46611
46611
  return out;
46612
46612
  })
@@ -47737,7 +47737,7 @@ async function fetchForChain(chainId, nowSeconds) {
47737
47737
  });
47738
47738
  }
47739
47739
  if (streams.length === 0) continue;
47740
- const deposit = streams.reduce((sum, st) => sum + st.apr, 0);
47740
+ const deposit = streams.reduce((sum3, st) => sum3 + st.apr, 0);
47741
47741
  const lenderKey = lenderKeyFor(s.market.controller);
47742
47742
  const asset = s.market.borrowedToken.toLowerCase();
47743
47743
  const reward = {
@@ -48506,9 +48506,9 @@ function getTermCalls(chainId) {
48506
48506
  }
48507
48507
  }
48508
48508
  const results = [];
48509
- for (const [token, { amount, repoKeys }] of byToken) {
48509
+ for (const [token, { amount: amount3, repoKeys }] of byToken) {
48510
48510
  const calls = [
48511
- { address: oracle, name: "usdValueOfTokens", params: [token, amount] }
48511
+ { address: oracle, name: "usdValueOfTokens", params: [token, amount3] }
48512
48512
  ];
48513
48513
  results.push({
48514
48514
  calls,
@@ -49009,9 +49009,9 @@ function parseTellerResults(data, meta, context) {
49009
49009
  const principal = meta.principal;
49010
49010
  const collateral = meta.collateral;
49011
49011
  const lenderKey = tellerLenderKey(meta.pool);
49012
- const usdOf = (addr2) => {
49013
- const key3 = tokenList?.[addr2]?.assetGroup ?? `${chainId}-${addr2}`;
49014
- return usdPrices[key3] ?? usdPrices[addr2];
49012
+ const usdOf = (addr3) => {
49013
+ const key3 = tokenList?.[addr3]?.assetGroup ?? `${chainId}-${addr3}`;
49014
+ return usdPrices[key3] ?? usdPrices[addr3];
49015
49015
  };
49016
49016
  const principalUSD = usdOf(principal);
49017
49017
  const collateralUSD = usdOf(collateral);
@@ -49569,8 +49569,8 @@ var priceLensAbi = [
49569
49569
  // src/prices/oracle-prices/fetchers/euler.ts
49570
49570
  var MAX_VIRTUAL_ADDRESS = 65535;
49571
49571
  var MAX_SANE_PRICE_USD = 1e7;
49572
- function isUsdUnitOfAccount(addr2) {
49573
- const numeric = parseInt(addr2, 16);
49572
+ function isUsdUnitOfAccount(addr3) {
49573
+ const numeric = parseInt(addr3, 16);
49574
49574
  return numeric <= MAX_VIRTUAL_ADDRESS;
49575
49575
  }
49576
49576
  var PRICE_LENS_ADDRESS = "0x6392892f3C57c658d2c748fc64c6fe57680E889F";
@@ -50128,7 +50128,7 @@ var siloV3Fetcher = {
50128
50128
  getAbi: getSiloV3Abi
50129
50129
  };
50130
50130
  var FLUID_EEE_LOWER3 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
50131
- var normalizeUnderlying4 = (addr2) => addr2 === FLUID_EEE_LOWER3 ? zeroAddress : addr2;
50131
+ var normalizeUnderlying4 = (addr3) => addr3 === FLUID_EEE_LOWER3 ? zeroAddress : addr3;
50132
50132
  function priceColInDebt(raw, colDec, debtDec) {
50133
50133
  return formatMorphoPrice(raw, debtDec, colDec + 9);
50134
50134
  }
@@ -51728,11 +51728,11 @@ async function fetchOraclePrices(chainIds, rpcOverrides, lists = {}, retries = 3
51728
51728
  }
51729
51729
  }
51730
51730
  const totalFailedCalls = trackerDiags.reduce(
51731
- (sum, d) => sum + d.failedCalls,
51731
+ (sum3, d) => sum3 + d.failedCalls,
51732
51732
  0
51733
51733
  );
51734
51734
  const totalParsedEntries = trackerDiags.reduce(
51735
- (sum, d) => sum + d.parsedEntries,
51735
+ (sum3, d) => sum3 + d.parsedEntries,
51736
51736
  0
51737
51737
  );
51738
51738
  const diag = {
@@ -52499,7 +52499,7 @@ function attachPricesToFlashLiquidity(chainId, liq, prices, list = {}) {
52499
52499
  var IDLE_MARKET_ID = "idle";
52500
52500
  function withIdleExposure(exposures, totalAssetsFormatted, pricePerUnit) {
52501
52501
  if (!(totalAssetsFormatted > 0)) return exposures;
52502
- const deployed = exposures.reduce((sum, e) => sum + e.assets, 0);
52502
+ const deployed = exposures.reduce((sum3, e) => sum3 + e.assets, 0);
52503
52503
  const idleAssets = totalAssetsFormatted - deployed;
52504
52504
  if (idleAssets <= totalAssetsFormatted * 1e-9) return exposures;
52505
52505
  const out = [
@@ -52541,7 +52541,7 @@ var composeVaultDisplayName = (brand, curatorName, asset, fallbackName) => {
52541
52541
 
52542
52542
  // src/vaults/fluid/publicCallParse.ts
52543
52543
  var FLUID_EEE_LOWER4 = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
52544
- var normalizeUnderlying5 = (addr2) => addr2 === FLUID_EEE_LOWER4 ? zeroAddress : addr2;
52544
+ var normalizeUnderlying5 = (addr3) => addr3 === FLUID_EEE_LOWER4 ? zeroAddress : addr3;
52545
52545
  var FLUID_RATE_SCALE2 = 100;
52546
52546
  var scaleFluidRate2 = (raw) => {
52547
52547
  if (raw === void 0 || raw === null) return 0;
@@ -52782,8 +52782,8 @@ function deriveConvertToAssets(totalAssetsRaw, totalSupplyRaw, shareDecimals) {
52782
52782
 
52783
52783
  // src/vaults/gearbox/publicCallParse.ts
52784
52784
  var WETH_MAINNET = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
52785
- var normalizeUnderlying6 = (addr2, chainId) => {
52786
- const lower3 = addr2.toLowerCase();
52785
+ var normalizeUnderlying6 = (addr3, chainId) => {
52786
+ const lower3 = addr3.toLowerCase();
52787
52787
  if (chainId === "1" && lower3 === WETH_MAINNET) return zeroAddress;
52788
52788
  return lower3;
52789
52789
  };
@@ -53244,9 +53244,9 @@ var VAULT_V2_ADAPTER_ABI = parseAbi([
53244
53244
  ]);
53245
53245
  var PHASE1_ABI = [...MetaMorphoAbi, ...VAULT_V2_PHASE1_ABI];
53246
53246
  var FEE_SCALE = 1e18;
53247
- var isHex40 = (addr2) => typeof addr2 === "string" && /^0x[0-9a-f]{40}$/i.test(addr2);
53247
+ var isHex40 = (addr3) => typeof addr3 === "string" && /^0x[0-9a-f]{40}$/i.test(addr3);
53248
53248
  var isHex64 = (v) => typeof v === "string" && /^0x[0-9a-f]{64}$/i.test(v);
53249
- var lcOrUndefined = (addr2) => isHex40(addr2) ? addr2.toLowerCase() : void 0;
53249
+ var lcOrUndefined = (addr3) => isHex40(addr3) ? addr3.toLowerCase() : void 0;
53250
53250
  var toNumberSafe = (raw, fallback = 0) => {
53251
53251
  if (raw === void 0 || raw === null) return fallback;
53252
53252
  const n = Number(raw);
@@ -53784,10 +53784,10 @@ var PHASE1_CALLS2 = [
53784
53784
  var PHASE1_PER_VAULT2 = PHASE1_CALLS2.length;
53785
53785
  var WITHDRAW_QUEUE_LENGTH_INDEX2 = 8;
53786
53786
  var FEE_SCALE2 = 1e18;
53787
- var isHex402 = (addr2) => typeof addr2 === "string" && /^0x[0-9a-f]{40}$/i.test(addr2);
53788
- var lcOrUndefined2 = (addr2) => {
53789
- if (!isHex402(addr2)) return void 0;
53790
- const lower3 = addr2.toLowerCase();
53787
+ var isHex402 = (addr3) => typeof addr3 === "string" && /^0x[0-9a-f]{40}$/i.test(addr3);
53788
+ var lcOrUndefined2 = (addr3) => {
53789
+ if (!isHex402(addr3)) return void 0;
53790
+ const lower3 = addr3.toLowerCase();
53791
53791
  return lower3 === zeroAddress ? void 0 : lower3;
53792
53792
  };
53793
53793
  var isHex642 = (val) => typeof val === "string" && /^0x[0-9a-f]{64}$/i.test(val);
@@ -57014,17 +57014,17 @@ var readerBeets = {
57014
57014
  const out = [];
57015
57015
  for (let i = 0; i < reqs.length; i++) {
57016
57016
  const r = reqs[i];
57017
- const amount = toBigInt14(r.assetAmount);
57017
+ const amount3 = toBigInt14(r.assetAmount);
57018
57018
  const ts = toNumber(r.requestTimestamp);
57019
57019
  const isWithdrawn = Boolean(r.isWithdrawn);
57020
- if (amount === void 0 || ts === void 0) continue;
57020
+ if (amount3 === void 0 || ts === void 0) continue;
57021
57021
  const readyAt = ts + delay;
57022
57022
  out.push({
57023
57023
  lst: entry.lst,
57024
57024
  brand: entry.brand,
57025
57025
  symbol: entry.symbol,
57026
57026
  requestId: String(i),
57027
- amountUnderlying: amount.toString(),
57027
+ amountUnderlying: amount3.toString(),
57028
57028
  status: isWithdrawn ? "claimed" : computeStatus(readyAt),
57029
57029
  readyAt: isWithdrawn ? void 0 : readyAt
57030
57030
  });
@@ -57475,8 +57475,8 @@ var readerIbera = {
57475
57475
  const r = stage2[k];
57476
57476
  if (!r) continue;
57477
57477
  const receiver = Array.isArray(r) ? r[2] : r.receiver;
57478
- const amount = Array.isArray(r) ? toBigInt14(r[3]) : toBigInt14(r.amount);
57479
- if (typeof receiver !== "string" || receiver.toLowerCase() !== target || amount === void 0 || amount === 0n) {
57478
+ const amount3 = Array.isArray(r) ? toBigInt14(r[3]) : toBigInt14(r.amount);
57479
+ if (typeof receiver !== "string" || receiver.toLowerCase() !== target || amount3 === void 0 || amount3 === 0n) {
57480
57480
  continue;
57481
57481
  }
57482
57482
  const id = BigInt(ids[k]);
@@ -57485,7 +57485,7 @@ var readerIbera = {
57485
57485
  brand: entry.brand,
57486
57486
  symbol: entry.symbol,
57487
57487
  requestId: String(ids[k]),
57488
- amountUnderlying: amount.toString(),
57488
+ amountUnderlying: amount3.toString(),
57489
57489
  status: id < frontier ? "claimable" : "pending"
57490
57490
  });
57491
57491
  }
@@ -57658,13 +57658,13 @@ var readerErc7540 = {
57658
57658
  ],
57659
57659
  abi: [Erc7540Abi]
57660
57660
  });
57661
- const amount = toBigInt14(stage2[0]) ?? claimable;
57661
+ const amount3 = toBigInt14(stage2[0]) ?? claimable;
57662
57662
  out.push({
57663
57663
  lst: entry.lst,
57664
57664
  brand: entry.brand,
57665
57665
  symbol: entry.symbol,
57666
57666
  requestId: "0",
57667
- amountUnderlying: amount.toString(),
57667
+ amountUnderlying: amount3.toString(),
57668
57668
  // The 7540 claim (`redeem`) takes the share amount.
57669
57669
  shares: claimable.toString(),
57670
57670
  status: "claimable"
@@ -57713,15 +57713,15 @@ var readerEthenaCooldown = {
57713
57713
  });
57714
57714
  const cell = res[0];
57715
57715
  let cooldownEnd;
57716
- let amount;
57716
+ let amount3;
57717
57717
  if (Array.isArray(cell)) {
57718
57718
  cooldownEnd = toBigInt14(cell[0]);
57719
- amount = toBigInt14(cell[1]);
57719
+ amount3 = toBigInt14(cell[1]);
57720
57720
  } else if (cell && typeof cell === "object") {
57721
57721
  cooldownEnd = toBigInt14(cell.cooldownEnd);
57722
- amount = toBigInt14(cell.underlyingAmount);
57722
+ amount3 = toBigInt14(cell.underlyingAmount);
57723
57723
  }
57724
- if (!amount || amount === 0n) return [];
57724
+ if (!amount3 || amount3 === 0n) return [];
57725
57725
  const readyAt = Number(cooldownEnd ?? 0n);
57726
57726
  const out = [
57727
57727
  {
@@ -57729,7 +57729,7 @@ var readerEthenaCooldown = {
57729
57729
  brand: entry.brand,
57730
57730
  symbol: entry.symbol,
57731
57731
  requestId: "0",
57732
- amountUnderlying: amount.toString(),
57732
+ amountUnderlying: amount3.toString(),
57733
57733
  status: computeStatus(readyAt),
57734
57734
  readyAt
57735
57735
  }
@@ -57784,7 +57784,7 @@ var readerSusd3Cooldown = {
57784
57784
  shares = toBigInt14(cell.shares);
57785
57785
  }
57786
57786
  if (!shares || shares === 0n) return [];
57787
- let amount = shares;
57787
+ let amount3 = shares;
57788
57788
  try {
57789
57789
  const stage2 = await multicallRetry({
57790
57790
  chain: chainId,
@@ -57793,7 +57793,7 @@ var readerSusd3Cooldown = {
57793
57793
  ],
57794
57794
  abi: [Susd3CooldownStatusAbi]
57795
57795
  });
57796
- amount = toBigInt14(stage2[0]) ?? shares;
57796
+ amount3 = toBigInt14(stage2[0]) ?? shares;
57797
57797
  } catch {
57798
57798
  }
57799
57799
  const readyAt = Number(cooldownEnd ?? 0n);
@@ -57804,7 +57804,7 @@ var readerSusd3Cooldown = {
57804
57804
  brand: entry.brand,
57805
57805
  symbol: entry.symbol,
57806
57806
  requestId: "0",
57807
- amountUnderlying: amount.toString(),
57807
+ amountUnderlying: amount3.toString(),
57808
57808
  shares: shares.toString(),
57809
57809
  status: computeStatus(readyAt, expiresAt),
57810
57810
  readyAt,
@@ -58000,14 +58000,14 @@ var readerEtherFi = {
58000
58000
  const isValid = Boolean(stage3[i * 3 + 2]);
58001
58001
  if (!req) continue;
58002
58002
  if (!isValid) continue;
58003
- const amount = toBigInt14(req.amountOfEEth);
58004
- if (amount === void 0) continue;
58003
+ const amount3 = toBigInt14(req.amountOfEEth);
58004
+ if (amount3 === void 0) continue;
58005
58005
  out.push({
58006
58006
  lst: entry.lst,
58007
58007
  brand: entry.brand,
58008
58008
  symbol: entry.symbol,
58009
58009
  requestId: id.toString(),
58010
- amountUnderlying: amount.toString(),
58010
+ amountUnderlying: amount3.toString(),
58011
58011
  status: isFinalized ? "claimable" : "pending"
58012
58012
  });
58013
58013
  }
@@ -58337,15 +58337,15 @@ var readerLista = {
58337
58337
  const isClaimable = Array.isArray(status) ? Boolean(status[0]) : Boolean(status._isClaimable);
58338
58338
  const bnbAmount = Array.isArray(status) ? toBigInt14(status[1]) : toBigInt14(status._amount);
58339
58339
  const snbnbAmount = Array.isArray(req) ? toBigInt14(req[1]) : toBigInt14(req?.amountInSnBnb);
58340
- const amount = bnbAmount ?? snbnbAmount;
58341
- if (amount === void 0) continue;
58340
+ const amount3 = bnbAmount ?? snbnbAmount;
58341
+ if (amount3 === void 0) continue;
58342
58342
  const uuid = Array.isArray(req) ? toBigInt14(req[0]) : toBigInt14(req?.uuid);
58343
58343
  out.push({
58344
58344
  lst: entry.lst,
58345
58345
  brand: entry.brand,
58346
58346
  symbol: entry.symbol,
58347
58347
  requestId: String(uuid ?? i),
58348
- amountUnderlying: amount.toString(),
58348
+ amountUnderlying: amount3.toString(),
58349
58349
  status: isClaimable ? "claimable" : "pending"
58350
58350
  });
58351
58351
  }
@@ -58600,7 +58600,7 @@ var readerStaderMaticX2 = {
58600
58600
  const out = [];
58601
58601
  for (let i = 0; i < arr.length; i++) {
58602
58602
  const r = arr[i];
58603
- const amount = toBigInt14(r.amount) ?? 0n;
58603
+ const amount3 = toBigInt14(r.amount) ?? 0n;
58604
58604
  const requestEpoch = toBigInt14(r.requestEpoch);
58605
58605
  if (requestEpoch === void 0) continue;
58606
58606
  const ready = stakeManager ? currentEpoch >= requestEpoch + delay : false;
@@ -58611,7 +58611,7 @@ var readerStaderMaticX2 = {
58611
58611
  // Use array index as the request id (consistent with
58612
58612
  // `claimWithdrawal(uint256 _idx)`).
58613
58613
  requestId: String(i),
58614
- amountUnderlying: amount.toString(),
58614
+ amountUnderlying: amount3.toString(),
58615
58615
  status: ready ? "claimable" : "pending"
58616
58616
  });
58617
58617
  }
@@ -59012,7 +59012,7 @@ var readerStakeWise = {
59012
59012
  const out = [];
59013
59013
  for (let i = 0; i < requests.length; i++) {
59014
59014
  const r = requests[i];
59015
- const amount = toBigInt14(r.totalAssets) ?? 0n;
59015
+ const amount3 = toBigInt14(r.totalAssets) ?? 0n;
59016
59016
  const onChainClaimed = claimedByIdx.get(i);
59017
59017
  const claimable = onChainClaimed !== void 0 || r.isClaimable;
59018
59018
  out.push({
@@ -59020,7 +59020,7 @@ var readerStakeWise = {
59020
59020
  brand: entry.brand,
59021
59021
  symbol: entry.symbol,
59022
59022
  requestId: r.positionTicket,
59023
- amountUnderlying: (onChainClaimed ?? amount).toString(),
59023
+ amountUnderlying: (onChainClaimed ?? amount3).toString(),
59024
59024
  status: claimable ? "claimable" : "pending"
59025
59025
  });
59026
59026
  }
@@ -59069,15 +59069,15 @@ var readerStCelo2 = {
59069
59069
  const timestamps = cell[1] ?? [];
59070
59070
  const out = [];
59071
59071
  for (let i = 0; i < values.length; i++) {
59072
- const amount = toBigInt14(values[i]);
59072
+ const amount3 = toBigInt14(values[i]);
59073
59073
  const readyAt = toNumber(timestamps[i]);
59074
- if (amount === void 0 || readyAt === void 0) continue;
59074
+ if (amount3 === void 0 || readyAt === void 0) continue;
59075
59075
  out.push({
59076
59076
  lst: entry.lst,
59077
59077
  brand: entry.brand,
59078
59078
  symbol: entry.symbol,
59079
59079
  requestId: String(i),
59080
- amountUnderlying: amount.toString(),
59080
+ amountUnderlying: amount3.toString(),
59081
59081
  status: computeStatus(readyAt),
59082
59082
  readyAt
59083
59083
  });
@@ -59178,15 +59178,15 @@ var readerSwell = {
59178
59178
  const id = ids[i];
59179
59179
  const r = stage3[i];
59180
59180
  if (!r) continue;
59181
- const amount = toBigInt14(r.amount);
59182
- if (amount === void 0) continue;
59181
+ const amount3 = toBigInt14(r.amount);
59182
+ if (amount3 === void 0) continue;
59183
59183
  const claimable = id <= lastProcessed;
59184
59184
  out.push({
59185
59185
  lst: entry.lst,
59186
59186
  brand: entry.brand,
59187
59187
  symbol: entry.symbol,
59188
59188
  requestId: id.toString(),
59189
- amountUnderlying: amount.toString(),
59189
+ amountUnderlying: amount3.toString(),
59190
59190
  status: claimable ? "claimable" : "pending"
59191
59191
  });
59192
59192
  }
@@ -59252,15 +59252,15 @@ var readerValantis = {
59252
59252
  for (let i = 0; i < burns.length; i++) {
59253
59253
  const b = burns[i];
59254
59254
  if (!b) continue;
59255
- const amount = Array.isArray(b) ? toBigInt14(b[0]) : toBigInt14(b.amount);
59255
+ const amount3 = Array.isArray(b) ? toBigInt14(b[0]) : toBigInt14(b.amount);
59256
59256
  const completed = Array.isArray(b) ? Boolean(b[2]) : Boolean(b.completed);
59257
- if (amount === void 0 || completed) continue;
59257
+ if (amount3 === void 0 || completed) continue;
59258
59258
  out.push({
59259
59259
  lst: entry.lst,
59260
59260
  brand: entry.brand,
59261
59261
  symbol: entry.symbol,
59262
59262
  requestId: String(toBigInt14(ids[i]) ?? i),
59263
- amountUnderlying: amount.toString(),
59263
+ amountUnderlying: amount3.toString(),
59264
59264
  status: redeemable[i] ? "claimable" : "pending"
59265
59265
  });
59266
59266
  }
@@ -59332,15 +59332,15 @@ var readerTruFin = {
59332
59332
  if (typeof recipient === "string" && recipient.toLowerCase() !== lcUser) {
59333
59333
  continue;
59334
59334
  }
59335
- const amount = Array.isArray(w) ? toBigInt14(w[1]) : toBigInt14(w.amount);
59336
- if (amount === void 0 || amount === 0n) continue;
59335
+ const amount3 = Array.isArray(w) ? toBigInt14(w[1]) : toBigInt14(w.amount);
59336
+ if (amount3 === void 0 || amount3 === 0n) continue;
59337
59337
  out.push({
59338
59338
  lst: entry.lst,
59339
59339
  brand: entry.brand,
59340
59340
  symbol: entry.symbol,
59341
59341
  // Composite id — same shape as the input.
59342
59342
  requestId: `${pairs[i].validator}:${pairs[i].nonce.toString()}`,
59343
- amountUnderlying: amount.toString(),
59343
+ amountUnderlying: amount3.toString(),
59344
59344
  status: claimable ? "claimable" : "pending"
59345
59345
  });
59346
59346
  }
@@ -59447,17 +59447,17 @@ var readerYieldNest = {
59447
59447
  const id = ids[i];
59448
59448
  const r = stage3[i];
59449
59449
  if (!r) continue;
59450
- const amount = toBigInt14(r.amount);
59450
+ const amount3 = toBigInt14(r.amount);
59451
59451
  const created = toNumber(r.creationTimestamp);
59452
59452
  const processed = Boolean(r.processed);
59453
- if (amount === void 0 || created === void 0) continue;
59453
+ if (amount3 === void 0 || created === void 0) continue;
59454
59454
  const readyAt = created + finalizationSeconds;
59455
59455
  out.push({
59456
59456
  lst: entry.lst,
59457
59457
  brand: entry.brand,
59458
59458
  symbol: entry.symbol,
59459
59459
  requestId: id.toString(),
59460
- amountUnderlying: amount.toString(),
59460
+ amountUnderlying: amount3.toString(),
59461
59461
  status: processed ? "claimed" : computeStatus(readyAt),
59462
59462
  readyAt: processed ? void 0 : readyAt
59463
59463
  });
@@ -61179,9 +61179,9 @@ async function fetchAaveEarnApiVaults(chainId, targets) {
61179
61179
  const target = Number(chainId);
61180
61180
  const byAddress = /* @__PURE__ */ new Map();
61181
61181
  const keep = (it) => {
61182
- const addr2 = it?.address?.toLowerCase();
61183
- if (!addr2 || Number(it.chainId) !== target) return;
61184
- if (!byAddress.has(addr2)) byAddress.set(addr2, it);
61182
+ const addr3 = it?.address?.toLowerCase();
61183
+ if (!addr3 || Number(it.chainId) !== target) return;
61184
+ if (!byAddress.has(addr3)) byAddress.set(addr3, it);
61185
61185
  };
61186
61186
  for (const owner of targets.owners) {
61187
61187
  let cursor = null;
@@ -61622,12 +61622,12 @@ var attachYearnLiquidity = async (chainId, multicallRetry, out) => {
61622
61622
  });
61623
61623
  let idx = 0;
61624
61624
  for (const p of pending) {
61625
- let sum = p.idle;
61625
+ let sum3 = p.idle;
61626
61626
  for (let j = 0; j < p.queue.length; j++) {
61627
61627
  const w = asBig(r2[idx++]);
61628
- if (w != null) sum += w;
61628
+ if (w != null) sum3 += w;
61629
61629
  }
61630
- setLiquidity(p.v, sum >= p.totalAssets ? p.totalAssets : sum);
61630
+ setLiquidity(p.v, sum3 >= p.totalAssets ? p.totalAssets : sum3);
61631
61631
  }
61632
61632
  };
61633
61633
  var fetchYearnVaults = async (chainId, multicallRetry, prices = {}, tokenList = {}) => {
@@ -61820,6 +61820,7 @@ var SYNC_REDEMPTION_PROVIDERS = /* @__PURE__ */ new Set([
61820
61820
  ]);
61821
61821
  var ASYNC_REDEMPTION_PROVIDERS = /* @__PURE__ */ new Set(["lagoon", "upshift"]);
61822
61822
  var classifyRedemption = (provider, v) => {
61823
+ if (provider === "pendle") return void 0;
61823
61824
  if (ASYNC_REDEMPTION_PROVIDERS.has(provider)) return "async";
61824
61825
  if (SYNC_REDEMPTION_PROVIDERS.has(provider)) return "sync";
61825
61826
  if (provider === "lst") return "async";
@@ -61939,9 +61940,9 @@ var isStablecoinSymbol = (symbol) => {
61939
61940
  };
61940
61941
  var classifyVault = (input) => {
61941
61942
  const key3 = `${input.chainId}-${input.address.toLowerCase()}`;
61942
- const yieldProfile = VOLATILE_VAULT_OVERRIDES.has(key3) || VOLATILE_PROVIDERS.has(input.provider) ? "volatile" : "yield-bearing";
61943
- const denomination = isStablecoinSymbol(input.underlyingSymbol) ? "stable" : "volatile";
61944
- return { yieldProfile, denomination };
61943
+ const yieldProfile2 = VOLATILE_VAULT_OVERRIDES.has(key3) || VOLATILE_PROVIDERS.has(input.provider) ? "volatile" : "yield-bearing";
61944
+ const denomination2 = isStablecoinSymbol(input.underlyingSymbol) ? "stable" : "volatile";
61945
+ return { yieldProfile: yieldProfile2, denomination: denomination2 };
61945
61946
  };
61946
61947
  var stampVaultClassification = (data, chainId, tokenList = {}) => {
61947
61948
  const stampBag = (bag, provider, classify = true) => {
@@ -61965,7 +61966,8 @@ var stampVaultClassification = (data, chainId, tokenList = {}) => {
61965
61966
  });
61966
61967
  v.yieldProfile = c.yieldProfile;
61967
61968
  v.denomination = c.denomination;
61968
- v.redemptionType = classifyRedemption(provider, v);
61969
+ const redemption = classifyRedemption(provider, v);
61970
+ if (redemption) v.redemptionType = redemption;
61969
61971
  const raw = v.convertToAssets ?? v.pricePerShare;
61970
61972
  if (raw != null) {
61971
61973
  v.sharePriceRaw = raw;
@@ -61993,6 +61995,7 @@ var stampVaultClassification = (data, chainId, tokenList = {}) => {
61993
61995
  stampBag(data["aave-earn"], "aave-earn");
61994
61996
  stampBag(data.upshift, "upshift");
61995
61997
  stampBag(data.yearn, "yearn");
61998
+ stampBag(data.pendle, "pendle");
61996
61999
  stampBag(data.hypercore, "hypercore", false);
61997
62000
  stampBag(data.gmx, "gmx", false);
61998
62001
  };
@@ -62868,8 +62871,8 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
62868
62871
  marketIndexToken
62869
62872
  )
62870
62873
  ]);
62871
- for (const [addr2, v] of gmValues) {
62872
- const e = out[addr2];
62874
+ for (const [addr3, v] of gmValues) {
62875
+ const e = out[addr3];
62873
62876
  if (e) {
62874
62877
  e.priceUsd = v.priceUsd;
62875
62878
  e.tvlUsd = v.tvlUsd;
@@ -62877,12 +62880,12 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
62877
62880
  e.depositCapacityUsd = v.depositCapacityUsd;
62878
62881
  }
62879
62882
  }
62880
- for (const [addr2, v] of glv.values) {
62881
- const e = out[addr2];
62883
+ for (const [addr3, v] of glv.values) {
62884
+ const e = out[addr3];
62882
62885
  if (!e) continue;
62883
62886
  e.priceUsd = v.priceUsd;
62884
62887
  e.tvlUsd = v.tvlUsd;
62885
- const markets2 = glv.glvMarkets.get(addr2) ?? [];
62888
+ const markets2 = glv.glvMarkets.get(addr3) ?? [];
62886
62889
  let liqSum = 0;
62887
62890
  let tvlSum = 0;
62888
62891
  for (const m of markets2) {
@@ -62894,7 +62897,7 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
62894
62897
  }
62895
62898
  if (tvlSum > 0 && v.tvlUsd != null)
62896
62899
  e.liquidityUsd = v.tvlUsd * (liqSum / tvlSum);
62897
- const caps = glv.glvCaps.get(addr2) ?? [];
62900
+ const caps = glv.glvCaps.get(addr3) ?? [];
62898
62901
  let capacity = 0;
62899
62902
  let known = false;
62900
62903
  for (const cap of caps) {
@@ -63120,6 +63123,270 @@ var getGmxUserPositions = async (chainId, account, multicallRetry, options) => {
63120
63123
  };
63121
63124
  };
63122
63125
 
63126
+ // src/vaults/pendle/api.ts
63127
+ var PENDLE_MARKETS_URL = "https://api-v2.pendle.finance/core/v1/markets/all";
63128
+ var PENDLE_ASSETS_URL = "https://api-v2.pendle.finance/core/v1/assets/all";
63129
+ var PENDLE_CHAIN_IDS = /* @__PURE__ */ new Set([
63130
+ "1",
63131
+ // Ethereum
63132
+ "10",
63133
+ // OP Mainnet
63134
+ "56",
63135
+ // BNB Chain
63136
+ "143",
63137
+ // Monad
63138
+ "146",
63139
+ // Sonic
63140
+ "999",
63141
+ // HyperEVM
63142
+ "5000",
63143
+ // Mantle
63144
+ "8453",
63145
+ // Base
63146
+ "9745",
63147
+ // Plasma
63148
+ "42161",
63149
+ // Arbitrum One
63150
+ "80094"
63151
+ // Berachain
63152
+ ]);
63153
+ var hasPendleMarkets = (chainId) => PENDLE_CHAIN_IDS.has(String(chainId));
63154
+ function splitChainScopedAddress(value) {
63155
+ if (!value) return void 0;
63156
+ const idx = value.indexOf("-");
63157
+ if (idx <= 0) return void 0;
63158
+ const chainId = value.slice(0, idx);
63159
+ const address = value.slice(idx + 1).toLowerCase();
63160
+ if (!/^\d+$/.test(chainId)) return void 0;
63161
+ if (!/^0x[0-9a-f]{40}$/.test(address)) return void 0;
63162
+ return { chainId, address };
63163
+ }
63164
+ function parseExpirySeconds(expiry) {
63165
+ if (!expiry) return void 0;
63166
+ const ms = Date.parse(expiry);
63167
+ if (!Number.isFinite(ms)) return void 0;
63168
+ return Math.floor(ms / 1e3);
63169
+ }
63170
+ function isLiveMarket(market, nowSecs = Math.floor(Date.now() / 1e3)) {
63171
+ const expiry = parseExpirySeconds(market.expiry);
63172
+ if (expiry === void 0) return false;
63173
+ return expiry > nowSecs;
63174
+ }
63175
+ var CACHE_TTL_MS6 = 6e4;
63176
+ var marketsCache;
63177
+ var assetsCache;
63178
+ function clearPendleMarketsCache() {
63179
+ marketsCache = void 0;
63180
+ assetsCache = void 0;
63181
+ }
63182
+ async function getJson4(url, label) {
63183
+ const response = await fetch(url, { headers: { Accept: "application/json" } });
63184
+ if (!response.ok) {
63185
+ throw new Error(
63186
+ `Pendle ${label} API failed: ${response.status} - ${response.statusText}`
63187
+ );
63188
+ }
63189
+ return response.json();
63190
+ }
63191
+ function cache(slot, build, store) {
63192
+ const now = Date.now();
63193
+ if (slot && now - slot.at < CACHE_TTL_MS6) return slot.promise;
63194
+ const promise = build();
63195
+ const entry = { at: now, promise };
63196
+ store(entry);
63197
+ promise.catch(() => store(void 0));
63198
+ return promise;
63199
+ }
63200
+ function fetchPendleApiMarkets() {
63201
+ return cache(
63202
+ marketsCache,
63203
+ async () => (await getJson4(PENDLE_MARKETS_URL, "markets"))?.markets ?? [],
63204
+ (c) => {
63205
+ marketsCache = c;
63206
+ }
63207
+ );
63208
+ }
63209
+ var assetKey = (chainId, address) => `${chainId}-${address.toLowerCase()}`;
63210
+ function fetchPendleApiAssets() {
63211
+ return cache(
63212
+ assetsCache,
63213
+ async () => {
63214
+ const json = await getJson4(PENDLE_ASSETS_URL, "assets");
63215
+ const map = /* @__PURE__ */ new Map();
63216
+ for (const a of json?.assets ?? []) {
63217
+ if (a?.chainId == null || !a?.address) continue;
63218
+ map.set(assetKey(a.chainId, a.address), a);
63219
+ }
63220
+ return map;
63221
+ },
63222
+ (c) => {
63223
+ assetsCache = c;
63224
+ }
63225
+ );
63226
+ }
63227
+
63228
+ // src/vaults/pendle/fetchPublic.ts
63229
+ var SECONDS_PER_DAY2 = 86400;
63230
+ var num11 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
63231
+ var fractionToPercent = (v) => {
63232
+ const n = num11(v);
63233
+ return n === null ? null : n * 100;
63234
+ };
63235
+ function resolveToken(address, chainId, tokenList, apiAssets, decimalsOnChain) {
63236
+ const listed = tokenList[address];
63237
+ const api = apiAssets.get(assetKey(chainId, address));
63238
+ const apiDecimals = typeof api?.decimals === "number" && Number.isFinite(api.decimals) ? api.decimals : void 0;
63239
+ return {
63240
+ decimals: listed?.decimals ?? apiDecimals ?? decimalsOnChain.get(address),
63241
+ symbol: listed?.symbol ?? api?.symbol ?? void 0,
63242
+ name: listed?.name ?? api?.name ?? void 0,
63243
+ logoURI: listed?.logoURI ?? api?.proIcon ?? void 0,
63244
+ assetGroup: listed?.assetGroup
63245
+ };
63246
+ }
63247
+ function parseMarket2(m, chainId, prices, tokenList, apiAssets, decimalsOnChain, nowSecs) {
63248
+ const pt = splitChainScopedAddress(m.pt);
63249
+ const underlying = splitChainScopedAddress(m.underlyingAsset);
63250
+ const marketAddress = (m.address ?? "").toLowerCase();
63251
+ if (!pt || !underlying || !marketAddress) return null;
63252
+ const expiry = parseExpirySeconds(m.expiry);
63253
+ if (expiry === void 0) return null;
63254
+ const ptMeta = resolveToken(
63255
+ pt.address,
63256
+ chainId,
63257
+ tokenList,
63258
+ apiAssets,
63259
+ decimalsOnChain
63260
+ );
63261
+ const assetMeta = resolveToken(
63262
+ underlying.address,
63263
+ chainId,
63264
+ tokenList,
63265
+ apiAssets,
63266
+ decimalsOnChain
63267
+ );
63268
+ const decimals = ptMeta.decimals;
63269
+ if (decimals === void 0) return null;
63270
+ const assetDecimals = assetMeta.decimals ?? decimals;
63271
+ const details = m.details ?? {};
63272
+ const impliedApyPercent = fractionToPercent(details.impliedApy) ?? 0;
63273
+ const supplyRate = apyToAprPercent(impliedApyPercent);
63274
+ const underlyingApyPercent = fractionToPercent(details.underlyingApy);
63275
+ const totalAssetsUsd = num11(details.totalTvl) ?? 0;
63276
+ const liquidityUsd = num11(details.liquidity) ?? 0;
63277
+ const priceKey = toOracleKey(assetMeta.assetGroup ?? null) || toGenericPriceKey(underlying.address, chainId);
63278
+ const priceUsd = prices[priceKey] ?? prices[underlying.address];
63279
+ const ptPriceKey = toOracleKey(ptMeta.assetGroup ?? null) || toGenericPriceKey(pt.address, chainId);
63280
+ const ptPriceUsd = prices[ptPriceKey] ?? prices[pt.address];
63281
+ const secondsToExpiry = Math.max(expiry - nowSecs, 0);
63282
+ const yt = splitChainScopedAddress(m.yt);
63283
+ const sy = splitChainScopedAddress(m.sy);
63284
+ return {
63285
+ address: pt.address,
63286
+ marketAddress,
63287
+ underlying: underlying.address,
63288
+ ytAddress: yt?.address,
63289
+ syAddress: sy?.address,
63290
+ symbol: ptMeta.symbol ?? `PT-${m.name ?? ""}`,
63291
+ name: ptMeta.name ?? `PT ${m.name ?? ""}`,
63292
+ decimals,
63293
+ assetDecimals,
63294
+ expiry,
63295
+ expiryIso: m.expiry ?? new Date(expiry * 1e3).toISOString(),
63296
+ secondsToExpiry,
63297
+ daysToExpiry: Math.round(secondsToExpiry / SECONDS_PER_DAY2 * 100) / 100,
63298
+ supplyRate,
63299
+ rewardsRate: 0,
63300
+ depositRate: supplyRate,
63301
+ impliedApyPercent,
63302
+ underlyingApyPercent: underlyingApyPercent ?? void 0,
63303
+ feeRate: num11(details.feeRate) ?? void 0,
63304
+ totalAssetsUsd,
63305
+ totalAssetsFormatted: totalAssetsUsd,
63306
+ liquidityUsd,
63307
+ isMintable: true,
63308
+ withdrawalMode: "market-sale",
63309
+ // Pre-seeded from Pendle's own branded PT icon. `stampVaultClassification`
63310
+ // overwrites it when the token list resolves something, and leaves it
63311
+ // alone otherwise — so a row still renders an icon with no token list.
63312
+ logoURI: ptMeta.logoURI,
63313
+ // Prefer the curated token-list entry (it carries `assetGroup`, tags and
63314
+ // everything else downstream reads); synthesize a minimal one from
63315
+ // Pendle's metadata otherwise, so `stampVaultClassification` still has a
63316
+ // symbol to read for the stable/volatile call.
63317
+ asset: tokenList[underlying.address] ?? (assetMeta.symbol || assetMeta.decimals !== void 0 ? {
63318
+ chainId,
63319
+ address: underlying.address,
63320
+ symbol: assetMeta.symbol,
63321
+ name: assetMeta.name,
63322
+ decimals: assetDecimals,
63323
+ logoURI: assetMeta.logoURI
63324
+ } : void 0),
63325
+ priceUsd,
63326
+ ptPriceUsd,
63327
+ categoryIds: m.categoryIds ?? void 0,
63328
+ protocol: m.protocol ?? void 0
63329
+ };
63330
+ }
63331
+ var fetchPendlePtMarkets = async (chainId, multicallRetry, prices = {}, tokenList = {}, options = {}) => {
63332
+ if (!hasPendleMarkets(chainId)) return {};
63333
+ const nowSecs = options.nowSecs ?? Math.floor(Date.now() / 1e3);
63334
+ const all = await fetchPendleApiMarkets();
63335
+ const want = Number(chainId);
63336
+ const candidates = all.filter((m) => {
63337
+ if (Number(m?.chainId) !== want) return false;
63338
+ return options.includeExpired === true || isLiveMarket(m, nowSecs);
63339
+ });
63340
+ if (candidates.length === 0) return {};
63341
+ const stillUnknown = (known) => {
63342
+ const out2 = /* @__PURE__ */ new Set();
63343
+ for (const m of candidates) {
63344
+ for (const ref of [m.pt, m.underlyingAsset]) {
63345
+ const parsed = splitChainScopedAddress(ref);
63346
+ if (parsed && !known(parsed.address)) out2.add(parsed.address);
63347
+ }
63348
+ }
63349
+ return [...out2];
63350
+ };
63351
+ let apiAssets = /* @__PURE__ */ new Map();
63352
+ const listCovers = (a) => tokenList[a]?.decimals !== void 0;
63353
+ if (stillUnknown(listCovers).length > 0) {
63354
+ try {
63355
+ apiAssets = await fetchPendleApiAssets();
63356
+ } catch {
63357
+ apiAssets = /* @__PURE__ */ new Map();
63358
+ }
63359
+ }
63360
+ const httpCovers = (a) => listCovers(a) || typeof apiAssets.get(assetKey(chainId, a))?.decimals === "number";
63361
+ const unresolved = stillUnknown(httpCovers);
63362
+ let decimalsOnChain = /* @__PURE__ */ new Map();
63363
+ if (unresolved.length > 0) {
63364
+ try {
63365
+ decimalsOnChain = await fetchAssetDecimals(
63366
+ chainId,
63367
+ unresolved,
63368
+ multicallRetry
63369
+ );
63370
+ } catch {
63371
+ decimalsOnChain = /* @__PURE__ */ new Map();
63372
+ }
63373
+ }
63374
+ const out = {};
63375
+ for (const m of candidates) {
63376
+ const parsed = parseMarket2(
63377
+ m,
63378
+ chainId,
63379
+ prices,
63380
+ tokenList,
63381
+ apiAssets,
63382
+ decimalsOnChain,
63383
+ nowSecs
63384
+ );
63385
+ if (parsed) out[parsed.address] = parsed;
63386
+ }
63387
+ return out;
63388
+ };
63389
+
63123
63390
  // src/vaults/yield/sharePrice.ts
63124
63391
  var VAULT_SHARE_PRICE_PROBE = 10n ** 18n;
63125
63392
  var ConvertToAssetsAbi = [
@@ -63199,11 +63466,11 @@ function buildVaultLookup(data) {
63199
63466
  const addEntries = (bag, provider) => {
63200
63467
  if (!bag) return;
63201
63468
  for (const v of Object.values(bag)) {
63202
- const addr2 = v.address.toLowerCase();
63203
- if (map.has(addr2)) continue;
63204
- map.set(addr2, {
63469
+ const addr3 = v.address.toLowerCase();
63470
+ if (map.has(addr3)) continue;
63471
+ map.set(addr3, {
63205
63472
  provider,
63206
- address: addr2,
63473
+ address: addr3,
63207
63474
  underlying: v.underlying.toLowerCase(),
63208
63475
  symbol: v.symbol,
63209
63476
  name: v.name,
@@ -63418,6 +63685,20 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
63418
63685
  })
63419
63686
  );
63420
63687
  }
63688
+ if (requested.has("pendle") && hasPendleMarkets(chainId)) {
63689
+ tasks.push(
63690
+ fetchPendlePtMarkets(chainId, multicallRetry, prices, tokenList, {
63691
+ includeExpired: options?.pendleIncludeExpired
63692
+ }).then((res) => {
63693
+ out.pendle = res;
63694
+ }).catch((e) => {
63695
+ warn8(
63696
+ `[vaults] pendle fetch failed for chain ${chainId}:`,
63697
+ e?.message ?? e
63698
+ );
63699
+ })
63700
+ );
63701
+ }
63421
63702
  if (requested.has("gmx") && getGmxApiHost(chainId)) {
63422
63703
  tasks.push(
63423
63704
  fetchGmxVaults(chainId, multicallRetry).then((res) => {
@@ -63749,32 +64030,32 @@ async function fetchTokenMetadata(chain, addrs) {
63749
64030
  const results = await client.multicall({
63750
64031
  allowFailure: false,
63751
64032
  batchSize: 300,
63752
- contracts: addrs.map((addr2) => [
64033
+ contracts: addrs.map((addr3) => [
63753
64034
  {
63754
64035
  abi: ERC20MetadataAbi,
63755
64036
  functionName: "name",
63756
- address: addr2,
64037
+ address: addr3,
63757
64038
  args: []
63758
64039
  },
63759
64040
  {
63760
64041
  abi: ERC20MetadataAbi,
63761
64042
  functionName: "symbol",
63762
- address: addr2,
64043
+ address: addr3,
63763
64044
  args: []
63764
64045
  },
63765
64046
  {
63766
64047
  abi: ERC20MetadataAbi,
63767
64048
  functionName: "decimals",
63768
- address: addr2,
64049
+ address: addr3,
63769
64050
  args: []
63770
64051
  }
63771
64052
  ]).flat()
63772
64053
  });
63773
- addrs.forEach((addr2, i) => {
64054
+ addrs.forEach((addr3, i) => {
63774
64055
  const name = results[i * 3];
63775
64056
  const symbol = results[i * 3 + 1];
63776
64057
  const decimals = results[i * 3 + 2];
63777
- const address = addr2.toLowerCase();
64058
+ const address = addr3.toLowerCase();
63778
64059
  tokens[address] = {
63779
64060
  chainId: String(chain),
63780
64061
  decimals,
@@ -63992,7 +64273,7 @@ async function fetchTokenBalances(chainId, account, tokens, options = {}) {
63992
64273
  var TERM_SHEET_SCHEMA_VERSION = 1;
63993
64274
 
63994
64275
  // src/terms/input.ts
63995
- var num11 = (v) => {
64276
+ var num12 = (v) => {
63996
64277
  if (v == null) return void 0;
63997
64278
  const n = typeof v === "string" ? Number(v) : v;
63998
64279
  return Number.isFinite(n) ? n : void 0;
@@ -64023,12 +64304,12 @@ function toTermSheetInput(row, ctx = {}) {
64023
64304
  {
64024
64305
  category: v?.category ?? k,
64025
64306
  label: v?.label,
64026
- borrowCollateralFactor: num11(v?.borrowCollateralFactor),
64027
- collateralFactor: num11(v?.collateralFactor),
64028
- borrowFactor: num11(v?.borrowFactor),
64029
- liquidationPenalty: num11(v?.liquidationPenalty),
64030
- closeFactor: num11(v?.closeFactor),
64031
- targetHealthFactor: num11(v?.targetHealthFactor),
64307
+ borrowCollateralFactor: num12(v?.borrowCollateralFactor),
64308
+ collateralFactor: num12(v?.collateralFactor),
64309
+ borrowFactor: num12(v?.borrowFactor),
64310
+ liquidationPenalty: num12(v?.liquidationPenalty),
64311
+ closeFactor: num12(v?.closeFactor),
64312
+ targetHealthFactor: num12(v?.targetHealthFactor),
64032
64313
  collateralDisabled: v?.collateralDisabled === true,
64033
64314
  debtDisabled: v?.debtDisabled === true
64034
64315
  }
@@ -64036,11 +64317,11 @@ function toTermSheetInput(row, ctx = {}) {
64036
64317
  ) : void 0;
64037
64318
  const rewards = pick2(row, "rewards")?.map((r) => ({
64038
64319
  asset: r?.asset,
64039
- depositRate: num11(r?.depositRate),
64040
- variableBorrowRate: num11(r?.variableBorrowRate),
64041
- stableBorrowRate: num11(r?.stableBorrowRate),
64320
+ depositRate: num12(r?.depositRate),
64321
+ variableBorrowRate: num12(r?.variableBorrowRate),
64322
+ stableBorrowRate: num12(r?.stableBorrowRate),
64042
64323
  kind: r?.kind,
64043
- endsAt: num11(r?.endsAt),
64324
+ endsAt: num12(r?.endsAt),
64044
64325
  claim: r?.claim
64045
64326
  }));
64046
64327
  return {
@@ -64053,29 +64334,29 @@ function toTermSheetInput(row, ctx = {}) {
64053
64334
  "underlyingInfo.asset"
64054
64335
  ),
64055
64336
  underlying: pick2(row, "underlying"),
64056
- decimals: num11(pick2(row, "decimals")),
64057
- depositRate: num11(pick2(row, "depositRate")),
64058
- variableBorrowRate: num11(pick2(row, "variableBorrowRate")),
64059
- stableBorrowRate: num11(pick2(row, "stableBorrowRate")),
64060
- intrinsicYield: num11(pick2(row, "intrinsicYield")),
64337
+ decimals: num12(pick2(row, "decimals")),
64338
+ depositRate: num12(pick2(row, "depositRate")),
64339
+ variableBorrowRate: num12(pick2(row, "variableBorrowRate")),
64340
+ stableBorrowRate: num12(pick2(row, "stableBorrowRate")),
64341
+ intrinsicYield: num12(pick2(row, "intrinsicYield")),
64061
64342
  rewards,
64062
64343
  rateModel: pick2(row, "rateModel"),
64063
- originationFee: num11(pick2(row, "originationFee")),
64064
- totalDeposits: num11(pick2(row, "totalDeposits")),
64065
- totalDebt: num11(pick2(row, "totalDebt")),
64066
- totalDebtStable: num11(pick2(row, "totalDebtStable")),
64067
- totalLiquidity: num11(pick2(row, "totalLiquidity")),
64068
- borrowLiquidity: num11(pick2(row, "borrowLiquidity")),
64069
- totalDepositsUsd: num11(pick2(row, "totalDepositsUSD", "totalDepositsUsd")),
64070
- totalDebtUsd: num11(pick2(row, "totalDebtUSD", "totalDebtUsd")),
64071
- totalLiquidityUsd: num11(pick2(row, "totalLiquidityUSD", "totalLiquidityUsd")),
64072
- utilization: num11(pick2(row, "utilization")),
64073
- irmTotalDeposits: num11(pick2(row, "irmTotalDeposits")),
64074
- irmTotalDebt: num11(pick2(row, "irmTotalDebt")),
64075
- lockupRatio: num11(pick2(row, "lockupRatio")),
64344
+ originationFee: num12(pick2(row, "originationFee")),
64345
+ totalDeposits: num12(pick2(row, "totalDeposits")),
64346
+ totalDebt: num12(pick2(row, "totalDebt")),
64347
+ totalDebtStable: num12(pick2(row, "totalDebtStable")),
64348
+ totalLiquidity: num12(pick2(row, "totalLiquidity")),
64349
+ borrowLiquidity: num12(pick2(row, "borrowLiquidity")),
64350
+ totalDepositsUsd: num12(pick2(row, "totalDepositsUSD", "totalDepositsUsd")),
64351
+ totalDebtUsd: num12(pick2(row, "totalDebtUSD", "totalDebtUsd")),
64352
+ totalLiquidityUsd: num12(pick2(row, "totalLiquidityUSD", "totalLiquidityUsd")),
64353
+ utilization: num12(pick2(row, "utilization")),
64354
+ irmTotalDeposits: num12(pick2(row, "irmTotalDeposits")),
64355
+ irmTotalDebt: num12(pick2(row, "irmTotalDebt")),
64356
+ lockupRatio: num12(pick2(row, "lockupRatio")),
64076
64357
  minBorrow: pick2(row, "minBorrow", "caps.minBorrow") ?? void 0,
64077
- supplyCap: num11(pick2(row, "supplyCap", "caps.supplyCap")),
64078
- borrowCap: num11(pick2(row, "borrowCap", "caps.borrowCap")),
64358
+ supplyCap: num12(pick2(row, "supplyCap", "caps.supplyCap")),
64359
+ borrowCap: num12(pick2(row, "borrowCap", "caps.borrowCap")),
64079
64360
  debtCeiling: pick2(row, "debtCeiling", "caps.debtCeiling"),
64080
64361
  isActive: pick2(row, "isActive", "flags.isActive"),
64081
64362
  isFrozen: pick2(row, "isFrozen", "flags.isFrozen"),
@@ -64101,8 +64382,8 @@ function toTermSheetInput(row, ctx = {}) {
64101
64382
  "flags.variableBorrowDisabled"
64102
64383
  ),
64103
64384
  config,
64104
- closeFactor: num11(pick2(row, "closeFactor")),
64105
- targetHealthFactor: num11(pick2(row, "targetHealthFactor")),
64385
+ closeFactor: num12(pick2(row, "closeFactor")),
64386
+ targetHealthFactor: num12(pick2(row, "targetHealthFactor")),
64106
64387
  fixedTerm: pick2(row, "fixedTerm") ?? ctx.fixedTerm,
64107
64388
  terms: pick2(row, "terms"),
64108
64389
  market: resolveMarketDescriptors(row, ctx.market)
@@ -64342,23 +64623,23 @@ function shortDate(unixSecs) {
64342
64623
  }
64343
64624
  function feePhrase(fee) {
64344
64625
  const magnitude = Math.abs(fee.value);
64345
- let amount;
64626
+ let amount3;
64346
64627
  switch (fee.unit) {
64347
64628
  case "bps":
64348
- amount = `${magnitude} bps`;
64629
+ amount3 = `${magnitude} bps`;
64349
64630
  break;
64350
64631
  case "apr-percent":
64351
- amount = `${pct(magnitude)}/yr`;
64632
+ amount3 = `${pct(magnitude)}/yr`;
64352
64633
  break;
64353
64634
  case "percent":
64354
- amount = pct(magnitude);
64635
+ amount3 = pct(magnitude);
64355
64636
  break;
64356
64637
  default:
64357
- amount = String(magnitude);
64638
+ amount3 = String(magnitude);
64358
64639
  }
64359
64640
  const rebate = fee.value < 0 ? " rebate" : "";
64360
64641
  const qualifier = fee.indicative ? " (estimated, resolved at execution)" : "";
64361
- return `${fee.label}: ${amount}${rebate}${qualifier}`;
64642
+ return `${fee.label}: ${amount3}${rebate}${qualifier}`;
64362
64643
  }
64363
64644
  function maturityPhrase(m) {
64364
64645
  if (m.kind === "fixed-date" && m.maturity)
@@ -65072,10 +65353,10 @@ function resolveMinDebt(input) {
65072
65353
  ];
65073
65354
  for (const c of candidates) {
65074
65355
  if (c == null) continue;
65075
- const str4 = String(c);
65076
- if (str4 === "0" || str4 === "") continue;
65077
- if (!/^\d+$/.test(str4)) continue;
65078
- return str4;
65356
+ const str5 = String(c);
65357
+ if (str5 === "0" || str5 === "") continue;
65358
+ if (!/^\d+$/.test(str5)) continue;
65359
+ return str5;
65079
65360
  }
65080
65361
  return void 0;
65081
65362
  }
@@ -65083,9 +65364,9 @@ function resolveMinCollateral(input) {
65083
65364
  const m = input.market ?? {};
65084
65365
  const raw = m.frankencoin?.minimumCollateral;
65085
65366
  if (raw == null) return void 0;
65086
- const str4 = String(raw);
65087
- if (str4 === "0" || str4 === "" || !/^\d+$/.test(str4)) return void 0;
65088
- return str4;
65367
+ const str5 = String(raw);
65368
+ if (str5 === "0" || str5 === "" || !/^\d+$/.test(str5)) return void 0;
65369
+ return str5;
65089
65370
  }
65090
65371
  function capUtil(total, cap) {
65091
65372
  if (!isNum(cap) || cap <= 0 || !isNum(total)) return void 0;
@@ -66849,8 +67130,8 @@ function enrichTermSheet(sheet, index) {
66849
67130
  if (!exp) continue;
66850
67131
  for (const item of exp.items) {
66851
67132
  const chain = item.asset.chainId;
66852
- const addr2 = item.asset.address;
66853
- const q = quality?.[chain]?.[addr2];
67133
+ const addr3 = item.asset.address;
67134
+ const q = quality?.[chain]?.[addr3];
66854
67135
  if (q) {
66855
67136
  item.quality = {
66856
67137
  riskScore: q.riskScore,
@@ -66928,7 +67209,7 @@ function validateTermSheet(sheet) {
66928
67209
  "apr-total",
66929
67210
  `${side}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
66930
67211
  );
66931
- const priceable = (s.rate.rewards ?? []).filter((r) => !r.indicative).reduce((sum, r) => sum + r.apr, 0);
67212
+ const priceable = (s.rate.rewards ?? []).filter((r) => !r.indicative).reduce((sum3, r) => sum3 + r.apr, 0);
66932
67213
  if (s.rate.rewards && !approx(c.rewards ?? 0, priceable, 1e-6))
66933
67214
  fail(
66934
67215
  "rewards-priceable",
@@ -67005,11 +67286,11 @@ function validateTermSheet(sheet) {
67005
67286
  `${label} is unweighted but has topWeightPct`
67006
67287
  );
67007
67288
  } else if (exp.items.length > 0) {
67008
- const sum = exp.items.reduce((s, i) => s + (i.weightPct ?? 0), 0);
67009
- if (Math.abs(sum - 100) > 0.5)
67289
+ const sum3 = exp.items.reduce((s, i) => s + (i.weightPct ?? 0), 0);
67290
+ if (Math.abs(sum3 - 100) > 0.5)
67010
67291
  fail(
67011
67292
  "weight-sum",
67012
- `${label} weights sum to ${sum.toFixed(2)}, expected ~100`
67293
+ `${label} weights sum to ${sum3.toFixed(2)}, expected ~100`
67013
67294
  );
67014
67295
  }
67015
67296
  if (exp.items.length > 0) {
@@ -67089,6 +67370,792 @@ function validateTermSheets(sheets) {
67089
67370
  return sheets.flatMap((s) => validateTermSheet(s));
67090
67371
  }
67091
67372
 
67092
- export { ApiBookSource, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_PROFILE_ID, DEFAULT_STALE_REJECT_SECONDS, DEFAULT_TERMMAX_API, EMPTY_BALANCE, EXACTLY_LENDER_KEY, 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, MULTICALL_FAILURE, 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, TERM_ADAPTERS, TERM_PROFILES, TERM_SHEET_SCHEMA_VERSION, TermMaxApiSource, TermSubgraphSource, UPSHIFT_CHAIN_IDS, UPSHIFT_VAULTS_URL, VAULT_SHARE_PRICE_PROBE, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, __resetResupplyUserCaches, accountDepositListKey, accountWithdrawalListKey, appendSnapshot, applyPositionDelta, attachImplications, attachPricesToFlashLiquidity, borrowDescription, borrowFindings, borrowHeadline, buildExposures2 as buildExposures, buildFluidFTokensCall, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildTermMaxUserCall, buildTermSheet, buildTermSheetsForGroup, 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, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFrankencoinMarketsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, detectInterfaceKinds, dssIlkBytes32, dssKeyParts, dssLenderKey, duration, encodeBalanceFetcherCalldata, enrichTermSheet, enrichmentIndexFromRows, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feePhrase, feedKeyOf, feedStatKey, fetchDolomiteAccountNumbers, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFluidFTokens, fetchFrankencoinMarkets, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchInverseMarkets, fetchLagoonApiVaults, fetchLagoonVaults, fetchLiquityMarkets, fetchListaVaultsFromChain, fetchLlamaLendMarkets, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendlePrices, fetchResupplyMarkets, fetchRiverMarkets, fetchSiloVaults, fetchTellerMarkets, fetchTermMarkets, fetchTermMaxMarkets, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchUsddMarkets, fetchYearnApiVaults, fetchYearnVaults, filterActiveLenders, filterLendersByProtocol, finalizeInfo, findingsFor, frankencoinKeyParts, frankencoinLenderKey, 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, getReadFailurePolicy, getResolvedDolomiteAccountNumbers, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getTermProfile, getVaultPublicDataAll, getVaultWithdrawalRequests, hasCritical, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasUpshiftVaults, hasYearnVaults, ilkToKeySegment, inverseKeyParts, inverseLenderKey, isFailedCall, isStablecoinSymbol, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, llamaLendKeyParts, llamaLendLenderKey, mergeDeep, multicall3Abi2 as multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, parseBalanceFetcherResult, parseMergedResult, parseMulticallRpcResponses, parseRawRpcBatchResponses, parseRawRpcResponses, parseTermMaxLtv, parseTokenBalanceResult, pct, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, pruneFeedStats, rankFindings, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, resolveAdapter, resolveDerivation, resolveStCeloDepositGroup, resupplyKeyParts, resupplyLenderKey, resupplyMarketLabel, riverKeyParts, riverLenderKey, selectAssetGroupPrices, shortDate, stampVaultClassification, supplyDescription, supplyFindings, supplyHeadline, 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, toDigest, toTermSheetInput, unflattenLenderData, updateFeedStats, usddIlkBytes32, usddKeyParts, usddLenderKey, validateTermSheet, validateTermSheets, validateUserData };
67373
+ // src/earn/uid.ts
67374
+ var VAULT_VENUE_PREFIX = "vault.";
67375
+ function isVaultVenue(uidOrVenue) {
67376
+ return uidOrVenue.startsWith(VAULT_VENUE_PREFIX);
67377
+ }
67378
+ function vaultVenue(provider) {
67379
+ return `${VAULT_VENUE_PREFIX}${provider}`;
67380
+ }
67381
+ function buildVaultEarnUid(provider, chainId, address) {
67382
+ if (!provider || !chainId || !address) {
67383
+ throw new Error(
67384
+ `Invalid earnUid parameters: provider=${provider}, chainId=${chainId}, address=${address}`
67385
+ );
67386
+ }
67387
+ return `${vaultVenue(provider)}:${chainId}:${address.toLowerCase()}`;
67388
+ }
67389
+ function earnUidFromMarketUid(marketUid) {
67390
+ const parts = splitUid(marketUid);
67391
+ if (!parts) {
67392
+ throw new Error(
67393
+ `Invalid marketUid: expected 'lender:chainId:ref', got '${marketUid}'`
67394
+ );
67395
+ }
67396
+ if (isVaultVenue(parts.venue)) {
67397
+ throw new Error(
67398
+ `marketUid '${marketUid}' uses the reserved '${VAULT_VENUE_PREFIX}' venue namespace`
67399
+ );
67400
+ }
67401
+ return marketUid;
67402
+ }
67403
+ function parseEarnUid(earnUid, knownProviders) {
67404
+ const parts = splitUid(earnUid);
67405
+ if (!parts) {
67406
+ throw new Error(
67407
+ `Invalid earnUid format: expected '<venue>:<chainId>:<ref>', got '${earnUid}'`
67408
+ );
67409
+ }
67410
+ const { venue, chainId, ref } = parts;
67411
+ if (!isVaultVenue(venue)) {
67412
+ return {
67413
+ kind: "lending",
67414
+ venue,
67415
+ chainId,
67416
+ // Lower-cased to match `normalizeMarketUid` / `createMarketUid`, which
67417
+ // both lowercase the ref segment. Harmless for Dolomite's integer id.
67418
+ ref: ref.toLowerCase(),
67419
+ marketUid: earnUid
67420
+ };
67421
+ }
67422
+ const provider = venue.slice(VAULT_VENUE_PREFIX.length);
67423
+ if (!provider) {
67424
+ throw new Error(`Invalid earnUid: empty vault provider in '${earnUid}'`);
67425
+ }
67426
+ if (knownProviders && !knownProviders.includes(provider)) {
67427
+ throw new Error(
67428
+ `Unknown vault provider '${provider}' in earnUid '${earnUid}'. Expected one of: ${knownProviders.join(",")}`
67429
+ );
67430
+ }
67431
+ return {
67432
+ kind: "vault",
67433
+ venue,
67434
+ provider,
67435
+ chainId,
67436
+ address: ref.toLowerCase()
67437
+ };
67438
+ }
67439
+ function tryParseEarnUid(earnUid, knownProviders) {
67440
+ try {
67441
+ return parseEarnUid(earnUid, knownProviders);
67442
+ } catch {
67443
+ return void 0;
67444
+ }
67445
+ }
67446
+ function earnVenueKind(earnUid) {
67447
+ return isVaultVenue(earnUid) ? "vault" : "lending";
67448
+ }
67449
+ function splitUid(uid) {
67450
+ if (!uid) return void 0;
67451
+ const parts = uid.split(":");
67452
+ if (parts.length !== 3) return void 0;
67453
+ const [venue, chainId, ref] = parts;
67454
+ if (!venue || !chainId || !ref) return void 0;
67455
+ return { venue, chainId, ref };
67456
+ }
67457
+
67458
+ // src/earn/labels.ts
67459
+ var VENUE_KIND_LABELS = {
67460
+ lending: "Lending markets",
67461
+ vault: "Vaults"
67462
+ };
67463
+ var VENUE_KIND_DESCRIPTIONS = {
67464
+ lending: "Supply into a lending market. Same-block exit, bounded by liquidity.",
67465
+ vault: "Deposit into a yield vault. Exit terms vary per vault."
67466
+ };
67467
+ var EXIT_MODE_LABELS = {
67468
+ instant: "Instant",
67469
+ "instant-capped": "Instant (capped)",
67470
+ "instant-or-queued": "Instant or queue",
67471
+ "fee-or-queued": "Fee or queue",
67472
+ "fixed-cooldown": "Cooldown",
67473
+ queued: "Queued",
67474
+ "request-based": "Request",
67475
+ "market-sale": "Market sale",
67476
+ "at-maturity": "At maturity",
67477
+ "off-chain": "Off-chain",
67478
+ "dex-only": "DEX only"
67479
+ };
67480
+ var EXIT_MODE_DESCRIPTIONS = {
67481
+ instant: "Withdraw any time.",
67482
+ "instant-capped": "Withdraw up to the available liquidity.",
67483
+ "instant-or-queued": "Withdraw instantly, or queue for the rest.",
67484
+ "fee-or-queued": "Instant exit for a fee, or queue for free.",
67485
+ "fixed-cooldown": "Request, wait out a cooldown, then claim.",
67486
+ queued: "Withdrawals are queued.",
67487
+ "request-based": "Withdrawals need a request and a later claim.",
67488
+ "market-sale": "Exit by selling the position on a market.",
67489
+ "at-maturity": "Locked until maturity.",
67490
+ "off-chain": "Exit is settled off-chain.",
67491
+ "dex-only": "Exit only by selling on a DEX."
67492
+ };
67493
+ var ACTION_LABELS = {
67494
+ deposit: "Deposit",
67495
+ withdraw: "Withdraw",
67496
+ "request-withdraw": "Request withdrawal",
67497
+ claim: "Claim",
67498
+ cancel: "Cancel request"
67499
+ };
67500
+ var GATING_LABELS = {
67501
+ "allowlist-contract": "Permissioned",
67502
+ kyc: "KYC required",
67503
+ "cap-full": "Cap full",
67504
+ paused: "Paused",
67505
+ frozen: "Frozen",
67506
+ "collateral-only": "No yield",
67507
+ matured: "Matured"
67508
+ };
67509
+ var RATE_KIND_LABELS = {
67510
+ "variable-curve": "Variable (utilization)",
67511
+ "variable-managed": "Variable (managed)",
67512
+ "user-set": "Borrower-set",
67513
+ "fixed-term": "Fixed term",
67514
+ "fixed-open": "Fixed",
67515
+ "zero-interest": "Interest-free",
67516
+ prepaid: "Prepaid",
67517
+ "nav-accrual": "NAV accrual",
67518
+ none: "No rate"
67519
+ };
67520
+ var RATE_SOURCE_LABELS = {
67521
+ chain: "On-chain",
67522
+ api: "Protocol API",
67523
+ oracle: "Oracle",
67524
+ realized: "Realized"
67525
+ };
67526
+ var VENUE_BRANDS = {
67527
+ MORPHO_BLUE: "Morpho Blue",
67528
+ MORPHO_MIDNIGHT: "Morpho Midnight",
67529
+ FLUID: "Fluid",
67530
+ GEARBOX_V3: "Gearbox V3",
67531
+ AAVE_V4: "Aave V4",
67532
+ AAVE_V3: "Aave V3",
67533
+ AAVE_V2: "Aave V2",
67534
+ SKY: "Sky",
67535
+ USDD: "USDD",
67536
+ LIQUITY_V2: "Liquity V2",
67537
+ SILO_V2: "Silo V2",
67538
+ SILO_V3: "Silo V3",
67539
+ EXACTLY: "Exactly",
67540
+ TELLER: "Teller",
67541
+ TERM_FINANCE: "Term Finance",
67542
+ TERMMAX: "TermMax",
67543
+ LLAMALEND: "LlamaLend",
67544
+ CURVANCE: "Curvance",
67545
+ INVERSE: "Inverse",
67546
+ FRANKENCOIN: "Frankencoin",
67547
+ RIVER: "River",
67548
+ RESUPPLY: "Resupply",
67549
+ TANGENT: "Tangent",
67550
+ DOLOMITE: "Dolomite",
67551
+ LISTA_DAO: "Lista",
67552
+ FLUX_FINANCE: "Flux",
67553
+ COMPOUND_V2: "Compound V2",
67554
+ COMPOUND_V3: "Compound V3",
67555
+ EULER_V2: "Euler V2",
67556
+ INIT: "Init"
67557
+ };
67558
+ var VAULT_PROVIDER_BRANDS = {
67559
+ fluid: "Fluid",
67560
+ gearbox: "Gearbox",
67561
+ morpho: "Morpho",
67562
+ lista: "Lista",
67563
+ silo: "Silo",
67564
+ "euler-earn": "Euler",
67565
+ termmax: "TermMax",
67566
+ lst: "Liquid staking",
67567
+ savings: "Savings",
67568
+ lagoon: "Lagoon",
67569
+ "aave-earn": "Aave",
67570
+ upshift: "Upshift",
67571
+ yearn: "Yearn",
67572
+ hypercore: "HyperLiquid",
67573
+ gmx: "GMX",
67574
+ pendle: "Pendle"
67575
+ };
67576
+ function isInstanceSegment(seg) {
67577
+ if (/^\d+$/.test(seg)) return true;
67578
+ if (/^0X[0-9A-F]+$/i.test(seg)) return true;
67579
+ return seg.length >= 8 && /^[0-9A-F]+$/i.test(seg);
67580
+ }
67581
+ function venueBrand(venue) {
67582
+ if (venue.startsWith("vault.")) {
67583
+ const provider = venue.slice("vault.".length);
67584
+ return VAULT_PROVIDER_BRANDS[provider] ?? provider;
67585
+ }
67586
+ const segments = venue.split("_");
67587
+ const cut = segments.findIndex(isInstanceSegment);
67588
+ const family = (cut > 0 ? segments.slice(0, cut) : segments).join("_");
67589
+ if (VENUE_BRANDS[family]) return VENUE_BRANDS[family];
67590
+ let best;
67591
+ for (const key3 of Object.keys(VENUE_BRANDS)) {
67592
+ if (family.startsWith(key3) && (!best || key3.length > best.length))
67593
+ best = key3;
67594
+ }
67595
+ return best ? VENUE_BRANDS[best] : family;
67596
+ }
67597
+ var EARN_LABELS = {
67598
+ venueKind: VENUE_KIND_LABELS,
67599
+ exitMode: EXIT_MODE_LABELS,
67600
+ action: ACTION_LABELS,
67601
+ gating: GATING_LABELS,
67602
+ rateKind: RATE_KIND_LABELS,
67603
+ rateSource: RATE_SOURCE_LABELS
67604
+ };
67605
+ var EARN_DESCRIPTIONS = {
67606
+ venueKind: VENUE_KIND_DESCRIPTIONS,
67607
+ exitMode: EXIT_MODE_DESCRIPTIONS
67608
+ };
67609
+ function earnLabel(dimension, key3) {
67610
+ return EARN_LABELS[dimension][key3] ?? key3;
67611
+ }
67612
+ function earnDescription(dimension, key3) {
67613
+ return EARN_DESCRIPTIONS[dimension][key3];
67614
+ }
67615
+
67616
+ // src/earn/normalize.ts
67617
+ function num13(v) {
67618
+ if (v == null || v === "") return void 0;
67619
+ const n = typeof v === "number" ? v : Number(v);
67620
+ return Number.isFinite(n) ? n : void 0;
67621
+ }
67622
+ function str4(v) {
67623
+ if (typeof v === "string") return v.length > 0 ? v : void 0;
67624
+ if (typeof v === "number" && Number.isFinite(v)) return String(v);
67625
+ return void 0;
67626
+ }
67627
+ function addr2(v) {
67628
+ return str4(v)?.toLowerCase();
67629
+ }
67630
+ function yieldProfile(v) {
67631
+ return v === "yield-bearing" || v === "volatile" ? v : void 0;
67632
+ }
67633
+ function denomination(v) {
67634
+ return v === "stable" || v === "volatile" ? v : void 0;
67635
+ }
67636
+ function usdValue(formatted, priceUsd) {
67637
+ if (formatted === void 0 || priceUsd === void 0) return void 0;
67638
+ const v = formatted * priceUsd;
67639
+ return Number.isFinite(v) ? v : void 0;
67640
+ }
67641
+ function formatRaw(raw, decimals) {
67642
+ if (raw == null || raw === "") return void 0;
67643
+ let value;
67644
+ try {
67645
+ value = BigInt(raw);
67646
+ } catch {
67647
+ return void 0;
67648
+ }
67649
+ if (decimals <= 0) return Number(value);
67650
+ const base = 10n ** BigInt(decimals);
67651
+ const whole = value / base;
67652
+ const frac = value % base;
67653
+ const n = Number(whole) + Number(frac) / Number(base);
67654
+ return Number.isFinite(n) ? n : void 0;
67655
+ }
67656
+
67657
+ // src/earn/fromVault.ts
67658
+ var FRACTION_RATE_PROVIDERS = /* @__PURE__ */ new Set();
67659
+ var SDK_FRACTION_RATE_PROVIDERS = /* @__PURE__ */ new Set([
67660
+ "hypercore",
67661
+ "gmx"
67662
+ ]);
67663
+ var RATE_SOURCE = {
67664
+ morpho: "api",
67665
+ silo: "api",
67666
+ lagoon: "api",
67667
+ hypercore: "api",
67668
+ gmx: "api",
67669
+ upshift: "api",
67670
+ yearn: "api",
67671
+ "aave-earn": "api",
67672
+ pendle: "api",
67673
+ lista: "chain",
67674
+ fluid: "chain",
67675
+ gearbox: "chain",
67676
+ "euler-earn": "chain",
67677
+ termmax: "chain",
67678
+ lst: "chain",
67679
+ savings: "chain"
67680
+ };
67681
+ var RATE_KIND = {
67682
+ morpho: "variable-curve",
67683
+ lista: "variable-curve",
67684
+ silo: "variable-curve",
67685
+ "euler-earn": "variable-curve",
67686
+ fluid: "variable-curve",
67687
+ gearbox: "variable-curve",
67688
+ "aave-earn": "variable-curve",
67689
+ termmax: "fixed-term",
67690
+ // A PT's implied APY is locked in at purchase and realized only by holding
67691
+ // to maturity — the same promise TermMax's FT makes, reached by a different
67692
+ // mechanism (an AMM discount rather than a quoted curve).
67693
+ pendle: "fixed-term",
67694
+ savings: "variable-managed",
67695
+ lst: "variable-managed",
67696
+ lagoon: "variable-managed",
67697
+ upshift: "variable-managed",
67698
+ yearn: "variable-managed",
67699
+ hypercore: "none",
67700
+ gmx: "none"
67701
+ };
67702
+ var DEFAULT_EXIT_MODE = {
67703
+ lagoon: "request-based",
67704
+ gmx: "request-based",
67705
+ hypercore: "queued",
67706
+ // Selling a PT is same-block but at the AMM's price, not at par — the
67707
+ // reported liquidity is pool DEPTH, so a large exit moves against you.
67708
+ pendle: "market-sale"
67709
+ };
67710
+ function earnMarketFromVault(row, chainId, opts = {}) {
67711
+ const provider = str4(row.provider);
67712
+ const address = str4(row.vaultAddress)?.toLowerCase();
67713
+ const underlying = str4(row.underlying)?.toLowerCase();
67714
+ if (!provider || !address || !underlying) return void 0;
67715
+ const meta = row.providerMeta ?? {};
67716
+ const info = row.vaultInfo ?? {};
67717
+ const rates = row.rates ?? {};
67718
+ const tvl = row.tvl ?? {};
67719
+ const liq = row.liquidity ?? {};
67720
+ const shareDecimals = num13(row.decimals) ?? 18;
67721
+ const assetDecimals = num13(row.assetDecimals) ?? num13(row.underlyingInfo?.asset?.decimals) ?? shareDecimals;
67722
+ const toPercent2 = (v) => ratePercent(v, provider, opts.fractionRateProviders);
67723
+ const base = toPercent2(rates.depositRate ?? rates.supplyRate);
67724
+ const rewards = toPercent2(rates.rewardsRate);
67725
+ const total = toPercent2(rates.totalRate) ?? sum(base, rewards) ?? 0;
67726
+ const rate = {
67727
+ total,
67728
+ base,
67729
+ rewards,
67730
+ kind: resolveRateKind(provider, meta),
67731
+ source: RATE_SOURCE[provider] ?? "api"
67732
+ };
67733
+ const maturity = resolveMaturity(meta);
67734
+ const availability = resolveAvailability(meta, maturity);
67735
+ return {
67736
+ earnUid: buildVaultEarnUid(provider, chainId, address),
67737
+ chainId,
67738
+ venue: vaultVenue(provider),
67739
+ venueKind: "vault",
67740
+ // Curator first (it names the actual operator), then the provider brand.
67741
+ brand: str4(row.curatorName) ?? venueBrand(vaultVenue(provider)),
67742
+ name: str4(info.name) ?? str4(row.displayName) ?? str4(row.name),
67743
+ ref: address,
67744
+ logoURI: str4(info.logoURI) ?? str4(row.underlyingInfo?.asset?.logoURI),
67745
+ asset: {
67746
+ address: underlying,
67747
+ symbol: str4(row.underlyingInfo?.asset?.symbol) ?? "",
67748
+ decimals: assetDecimals,
67749
+ assetGroup: str4(info.assetGroup),
67750
+ priceUsd: num13(row.underlyingInfo?.prices?.priceUsd)
67751
+ },
67752
+ // The vault IS a share token by construction; carry it so a withdraw in
67753
+ // share units can be built without a second lookup.
67754
+ shareToken: {
67755
+ address,
67756
+ symbol: str4(info.symbol) ?? str4(row.symbol) ?? "",
67757
+ decimals: shareDecimals
67758
+ },
67759
+ rate,
67760
+ // The vault origin reports RAW base units + a pre-formatted convenience
67761
+ // field. Carry both; fall back to formatting the raw amount ourselves so
67762
+ // `formatted` — the field consumers sort on — is never silently absent.
67763
+ tvl: amount(
67764
+ tvl.totalAssets,
67765
+ tvl.totalAssetsFormatted,
67766
+ tvl.totalAssetsUsd,
67767
+ assetDecimals
67768
+ ),
67769
+ liquidity: liq.liquidity != null || liq.liquidityUsd != null ? amount(
67770
+ liq.liquidity,
67771
+ liq.liquidityFormatted,
67772
+ liq.liquidityUsd,
67773
+ assetDecimals
67774
+ ) : void 0,
67775
+ depositCapacity: str4(meta.depositCapacity) ?? str4(meta.maxDeposit),
67776
+ maturity,
67777
+ exit: {
67778
+ mode: str4(meta.withdrawalMode) ?? DEFAULT_EXIT_MODE[provider] ?? "instant",
67779
+ settlement: str4(meta.redemptionType),
67780
+ cooldownSecs: num13(meta.withdrawalCooldownSeconds),
67781
+ feeBps: num13(meta.withdrawFeeBps)
67782
+ },
67783
+ availability,
67784
+ risk: {
67785
+ yieldProfile: yieldProfile(info.yieldProfile),
67786
+ denomination: denomination(info.denomination)
67787
+ },
67788
+ // Filled by `capabilities.ts` — kept required on the type so a normalizer
67789
+ // that forgets to stamp them is a compile error, not an empty CTA.
67790
+ capabilities: [],
67791
+ providerMeta: row.providerMeta
67792
+ };
67793
+ }
67794
+ function ratePercent(value, provider, fractionProviders = FRACTION_RATE_PROVIDERS) {
67795
+ const n = num13(value);
67796
+ if (n === void 0) return void 0;
67797
+ return fractionProviders.has(provider) ? n * 100 : n;
67798
+ }
67799
+ function implausibleRatePercent(percent) {
67800
+ return !Number.isFinite(percent) || percent < 0 || percent > 1e4;
67801
+ }
67802
+ function resolveRateKind(provider, meta) {
67803
+ if (provider === "savings" && (meta.navOracle || meta.rateKind === "nav")) {
67804
+ return "nav-accrual";
67805
+ }
67806
+ return RATE_KIND[provider] ?? "variable-managed";
67807
+ }
67808
+ function resolveAvailability(meta, maturity) {
67809
+ const isMintable = meta.isMintable;
67810
+ const capacity = str4(meta.depositCapacity) ?? str4(meta.maxDeposit);
67811
+ const capFull = capacity === "0";
67812
+ let gating;
67813
+ let reason;
67814
+ if (isMatured(maturity)) {
67815
+ gating = "matured";
67816
+ reason = "This market has reached maturity";
67817
+ } else if (isMintable === false) {
67818
+ gating = "allowlist-contract";
67819
+ reason = "Deposits are permissioned for this vault";
67820
+ } else if (capFull) {
67821
+ gating = "cap-full";
67822
+ reason = "Deposit cap is full";
67823
+ } else if (meta.paused === true) {
67824
+ gating = "paused";
67825
+ reason = "Vault is paused";
67826
+ }
67827
+ return {
67828
+ canDeposit: gating === void 0,
67829
+ // Exits stay open under a deposit cap, a mint allowlist or a maturity —
67830
+ // every wind-down we have integrated (Lista, dTRINITY/Sonic) keeps the
67831
+ // door open outward, and a matured bond is precisely the case where the
67832
+ // holder still needs out. An explicit pause is the one thing that shuts
67833
+ // both.
67834
+ canWithdraw: meta.paused !== true,
67835
+ gating,
67836
+ reason
67837
+ };
67838
+ }
67839
+ function resolveMaturity(meta) {
67840
+ const expiry = num13(meta.expiry) ?? num13(meta.maturity);
67841
+ if (expiry === void 0 || expiry <= 0) return void 0;
67842
+ const nowSecs = Math.floor(Date.now() / 1e3);
67843
+ return {
67844
+ kind: "fixed-date",
67845
+ maturity: expiry,
67846
+ maturityIso: str4(meta.expiryIso) ?? new Date(expiry * 1e3).toISOString(),
67847
+ // A SNAPSHOT — a cached listing ages, so a countdown must be recomputed
67848
+ // from `maturity` rather than ticked down from this.
67849
+ secondsToMaturity: Math.max(expiry - nowSecs, 0),
67850
+ // A PT simply stops earning: it redeems for the underlying at par and
67851
+ // sits there. No penalty, no liquidation, no auto-roll.
67852
+ atMaturity: str4(meta.atMaturity) ?? "stops-earning"
67853
+ };
67854
+ }
67855
+ function isMatured(maturity) {
67856
+ if (!maturity?.maturity) return false;
67857
+ return maturity.maturity <= Math.floor(Date.now() / 1e3);
67858
+ }
67859
+ function amount(raw, formatted, usd, decimals) {
67860
+ const rawStr = raw != null ? String(raw) : void 0;
67861
+ return {
67862
+ raw: rawStr,
67863
+ formatted: num13(formatted) ?? formatRaw(rawStr, decimals),
67864
+ usd: num13(usd)
67865
+ };
67866
+ }
67867
+ function sum(a, b) {
67868
+ if (a === void 0 && b === void 0) return void 0;
67869
+ return (a ?? 0) + (b ?? 0);
67870
+ }
67871
+
67872
+ // src/earn/fromPool.ts
67873
+ var FIXED_TERM_PREFIXES = [
67874
+ "EXACTLY",
67875
+ "TELLER",
67876
+ "TERM_FINANCE",
67877
+ "TERMMAX",
67878
+ "MORPHO_MIDNIGHT"
67879
+ ];
67880
+ var USER_SET_RATE_PREFIXES = [
67881
+ "LIQUITY",
67882
+ "USDAF",
67883
+ "FELIX",
67884
+ "NERITE",
67885
+ "QUILL",
67886
+ "ENOSYS_LOANS",
67887
+ "SONETA",
67888
+ "EBISU"
67889
+ ];
67890
+ function earnMarketFromPool(row, fallbackChainId) {
67891
+ const marketUid = str4(row.marketUid);
67892
+ if (!marketUid) return void 0;
67893
+ let earnUid;
67894
+ try {
67895
+ earnUid = earnUidFromMarketUid(marketUid);
67896
+ } catch {
67897
+ return void 0;
67898
+ }
67899
+ const chainId = str4(row.chainId) ?? fallbackChainId;
67900
+ const venue = str4(row.lender) ?? str4(row.lenderKey);
67901
+ if (!chainId || !venue) return void 0;
67902
+ const flags = row.flags ?? {};
67903
+ const assetInfo = row.underlyingInfo?.asset ?? row.asset ?? {};
67904
+ const underlying = addr2(assetInfo.address) ?? addr2(row.underlying) ?? addr2(row.poolId);
67905
+ if (!underlying) return void 0;
67906
+ const decimals = num13(assetInfo.decimals) ?? num13(row.decimals) ?? 18;
67907
+ const priceUsd = num13(row.underlyingInfo?.prices?.priceUsd) ?? num13(row.price);
67908
+ const base = num13(row.depositRate);
67909
+ const intrinsic = num13(row.intrinsicYield);
67910
+ const rewards = sumRewardAprs(row.rewards);
67911
+ const marketOwn = sum2(base, rewards);
67912
+ const rate = {
67913
+ // Prefer our own sum over the origin's `apr`, because `apr` is documented
67914
+ // as `depositRate + intrinsicYield` and therefore EXCLUDES incentives —
67915
+ // using it as the headline would under-report every incentivized market.
67916
+ total: sum2(base, intrinsic, rewards) ?? num13(row.apr) ?? 0,
67917
+ base,
67918
+ rewards,
67919
+ intrinsic,
67920
+ marketOwn,
67921
+ passthrough: isPassthrough(marketOwn, intrinsic),
67922
+ kind: resolveRateKind2(venue),
67923
+ source: "chain"
67924
+ };
67925
+ const availability = resolveAvailability2(row, flags, rate.total);
67926
+ return {
67927
+ earnUid,
67928
+ chainId,
67929
+ venue,
67930
+ venueKind: "lending",
67931
+ // The family brand ('Morpho Blue'), not the per-market key. The specific
67932
+ // market identity survives on `name`.
67933
+ brand: venueBrand(venue),
67934
+ name: str4(row.name),
67935
+ // Never re-derived — the uid's third segment as the origin minted it.
67936
+ ref: marketUid.split(":")[2],
67937
+ logoURI: str4(assetInfo.logoURI),
67938
+ asset: {
67939
+ address: underlying,
67940
+ symbol: str4(assetInfo.symbol) ?? "",
67941
+ decimals,
67942
+ assetGroup: str4(row.underlyingInfo?.assetGroup) ?? str4(row.asset?.assetGroup),
67943
+ priceUsd
67944
+ },
67945
+ // A lending supply position is an aToken/cToken/eToken balance, but the
67946
+ // origin listing does not carry that address — and guessing one would be
67947
+ // worse than omitting it. Consumers that need it resolve via `marketUid`.
67948
+ shareToken: void 0,
67949
+ rate,
67950
+ // Lending amounts arrive PRE-FORMATTED (`parseRawAmount` = `formatUnits`),
67951
+ // so `formatted` is populated and `raw` is genuinely absent. Do NOT
67952
+ // back-fill `raw` by re-scaling — the round-trip loses precision and would
67953
+ // fabricate base units the origin never sent.
67954
+ tvl: amount2(
67955
+ row.totalDeposits,
67956
+ row.totalDepositsUSD ?? row.totalDepositsUsd
67957
+ ),
67958
+ liquidity: amount2(
67959
+ row.totalLiquidity,
67960
+ row.totalLiquidityUSD ?? row.totalLiquidityUsd
67961
+ ),
67962
+ depositCapacity: void 0,
67963
+ utilization: num13(row.utilization),
67964
+ // Lending withdrawals are same-block, bounded by available liquidity —
67965
+ // which is exactly `instant-capped`, not `instant`. A pool at 100 %
67966
+ // utilization cannot be exited, and calling that `instant` is the kind of
67967
+ // small lie that produces a stuck user.
67968
+ exit: { mode: "instant-capped", settlement: "sync" },
67969
+ availability,
67970
+ risk: void 0,
67971
+ capabilities: [],
67972
+ refs: {
67973
+ marketUid,
67974
+ borrowable: (flags.borrowingEnabled ?? row.borrowingEnabled) === true
67975
+ }
67976
+ };
67977
+ }
67978
+ var PASSTHROUGH_RATE_EPSILON = 0.01;
67979
+ function isPassthrough(marketOwn, intrinsic) {
67980
+ if (intrinsic === void 0 || intrinsic <= 0) return false;
67981
+ return (marketOwn ?? 0) < PASSTHROUGH_RATE_EPSILON;
67982
+ }
67983
+ function resolveRateKind2(venue) {
67984
+ const key3 = venue.toUpperCase();
67985
+ if (FIXED_TERM_PREFIXES.some((p) => key3.startsWith(p))) return "fixed-term";
67986
+ if (USER_SET_RATE_PREFIXES.some((p) => key3.startsWith(p))) return "user-set";
67987
+ return "variable-curve";
67988
+ }
67989
+ function resolveAvailability2(row, flags, totalRate) {
67990
+ const isActive = flags.isActive ?? row.isActive;
67991
+ const isFrozen = flags.isFrozen ?? row.isFrozen;
67992
+ const depositsEnabled = flags.depositsEnabled ?? row.depositsEnabled;
67993
+ let gating;
67994
+ let reason;
67995
+ if (isActive === false) {
67996
+ gating = "paused";
67997
+ reason = "Market is inactive";
67998
+ } else if (isFrozen === true) {
67999
+ gating = "frozen";
68000
+ reason = "Market is frozen \u2014 no new deposits";
68001
+ } else if (depositsEnabled === false) {
68002
+ gating = "paused";
68003
+ reason = "Deposits are disabled for this market";
68004
+ } else if (isSupplyCapFull(row)) {
68005
+ gating = "cap-full";
68006
+ reason = "Supply cap is full";
68007
+ }
68008
+ const blocked = gating !== void 0;
68009
+ if (!blocked && totalRate === 0) {
68010
+ gating = "collateral-only";
68011
+ reason = "Collateral-only market \u2014 deposits earn no yield";
68012
+ }
68013
+ return {
68014
+ // Withdrawals stay open through a freeze and a full cap; only a hard
68015
+ // inactive market shuts them.
68016
+ canDeposit: !blocked,
68017
+ canWithdraw: isActive !== false,
68018
+ gating,
68019
+ reason
68020
+ };
68021
+ }
68022
+ function isSupplyCapFull(row) {
68023
+ const cap = num13(row.caps?.supplyCap) ?? num13(row.supplyCap);
68024
+ if (cap === void 0 || cap <= 0) return false;
68025
+ const deposits = num13(row.totalDeposits);
68026
+ if (deposits === void 0) return false;
68027
+ return deposits >= cap;
68028
+ }
68029
+ function sumRewardAprs(rewards) {
68030
+ if (!Array.isArray(rewards) || rewards.length === 0) return void 0;
68031
+ let total = 0;
68032
+ let seen = false;
68033
+ for (const r of rewards) {
68034
+ const apr = num13(r?.depositRate);
68035
+ if (apr === void 0) continue;
68036
+ total += apr;
68037
+ seen = true;
68038
+ }
68039
+ return seen ? total : void 0;
68040
+ }
68041
+ function amount2(formatted, usd) {
68042
+ return { formatted: num13(formatted), usd: num13(usd) };
68043
+ }
68044
+ function sum2(...parts) {
68045
+ const present = parts.filter((p) => p !== void 0);
68046
+ return present.length ? present.reduce((a, b) => a + b, 0) : void 0;
68047
+ }
68048
+
68049
+ // src/earn/capabilities.ts
68050
+ var ASYNC_EXIT_MODES = /* @__PURE__ */ new Set([
68051
+ "fixed-cooldown",
68052
+ "request-based",
68053
+ "queued",
68054
+ "fee-or-queued",
68055
+ "instant-or-queued"
68056
+ ]);
68057
+ var ASYNC_PROVIDERS = /* @__PURE__ */ new Set([
68058
+ "lagoon",
68059
+ // ERC-7540 async redeem
68060
+ "gmx"
68061
+ // keeper-executed tickets
68062
+ ]);
68063
+ function stampCapabilities(row) {
68064
+ row.capabilities = row.venueKind === "lending" ? lendingCapabilities(row) : vaultCapabilities(row);
68065
+ return row;
68066
+ }
68067
+ function lendingCapabilities(row) {
68068
+ const caps = [];
68069
+ if (row.availability.canDeposit) {
68070
+ caps.push({ action: "deposit", acceptsPayAsset: true });
68071
+ }
68072
+ if (row.availability.canWithdraw) {
68073
+ caps.push({ action: "withdraw", acceptsReceiveAsset: true });
68074
+ }
68075
+ return caps;
68076
+ }
68077
+ var SWAP_ROUTED_PROVIDERS = /* @__PURE__ */ new Set(["pendle"]);
68078
+ function swapRoutedCapabilities(row) {
68079
+ const caps = [];
68080
+ if (row.availability.canDeposit) {
68081
+ caps.push({
68082
+ action: "deposit",
68083
+ via: "swap",
68084
+ requires: ["slippage"],
68085
+ acceptsPayAsset: true
68086
+ });
68087
+ }
68088
+ if (row.availability.canWithdraw) {
68089
+ caps.push({
68090
+ action: "withdraw",
68091
+ via: "swap",
68092
+ requires: ["slippage"],
68093
+ acceptsReceiveAsset: true
68094
+ });
68095
+ }
68096
+ return caps;
68097
+ }
68098
+ function vaultCapabilities(row) {
68099
+ const provider = row.venue.replace(/^vault\./, "");
68100
+ const meta = row.providerMeta ?? {};
68101
+ const caps = [];
68102
+ if (SWAP_ROUTED_PROVIDERS.has(provider)) return swapRoutedCapabilities(row);
68103
+ if (row.availability.canDeposit) {
68104
+ caps.push({
68105
+ action: "deposit",
68106
+ requires: depositRequires(provider, meta),
68107
+ // Phase 3 flips this to `true` once the `vault.*` venues are registered
68108
+ // with the conversion solver. Advertising it before the route can serve
68109
+ // it would be worse than the current gap — a client would build a zap
68110
+ // input that 400s.
68111
+ acceptsPayAsset: false
68112
+ });
68113
+ }
68114
+ if (!row.availability.canWithdraw) return caps;
68115
+ const mode = row.exit.mode;
68116
+ const isAsync = ASYNC_PROVIDERS.has(provider) || ASYNC_EXIT_MODES.has(mode);
68117
+ if (!isAsync) {
68118
+ caps.push({ action: "withdraw" });
68119
+ return caps;
68120
+ }
68121
+ if (mode === "fee-or-queued" && meta.instantRedeemEnabled !== false) {
68122
+ caps.push({
68123
+ action: "withdraw",
68124
+ feeBps: num13(meta.withdrawFeeBps) ?? row.exit.feeBps
68125
+ });
68126
+ }
68127
+ caps.push({
68128
+ action: "request-withdraw",
68129
+ async: true,
68130
+ requires: requestRequires(provider)
68131
+ });
68132
+ caps.push({
68133
+ action: "claim",
68134
+ async: false,
68135
+ requires: claimRequires()
68136
+ });
68137
+ if (supportsCancel(provider, meta)) {
68138
+ caps.push({ action: "cancel" });
68139
+ }
68140
+ return caps;
68141
+ }
68142
+ function depositRequires(provider, meta) {
68143
+ const requires = [];
68144
+ if (meta.delegation) requires.push("validator");
68145
+ if (provider === "gmx") requires.push("executionFee");
68146
+ return requires.length ? requires : void 0;
68147
+ }
68148
+ function requestRequires(provider) {
68149
+ return provider === "gmx" ? ["executionFee"] : void 0;
68150
+ }
68151
+ function claimRequires(provider) {
68152
+ return void 0;
68153
+ }
68154
+ function supportsCancel(provider, meta) {
68155
+ if (provider === "gmx") return true;
68156
+ return typeof meta.withdrawQueue === "string" && meta.withdrawQueue.length > 0;
68157
+ }
68158
+
68159
+ export { ApiBookSource, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_PROFILE_ID, DEFAULT_STALE_REJECT_SECONDS, DEFAULT_TERMMAX_API, EARN_DESCRIPTIONS, EARN_LABELS, EMPTY_BALANCE, EXACTLY_LENDER_KEY, FRACTION_RATE_PROVIDERS, 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, MULTICALL_FAILURE, MaxParamThresholds, PENDLE_ASSETS_URL, PENDLE_CHAIN_IDS, PENDLE_MARKETS_URL, SDK_FRACTION_RATE_PROVIDERS, 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, TERM_ADAPTERS, TERM_PROFILES, TERM_SHEET_SCHEMA_VERSION, TermMaxApiSource, TermSubgraphSource, UPSHIFT_CHAIN_IDS, UPSHIFT_VAULTS_URL, VAULT_SHARE_PRICE_PROBE, VAULT_VENUE_PREFIX, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, __resetResupplyUserCaches, accountDepositListKey, accountWithdrawalListKey, appendSnapshot, applyPositionDelta, attachImplications, attachPricesToFlashLiquidity, borrowDescription, borrowFindings, borrowHeadline, buildExposures2 as buildExposures, buildFluidFTokensCall, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildTermMaxUserCall, buildTermSheet, buildTermSheetsForGroup, buildVaultEarnUid, buildVaultLookup, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, classifyFreshness, classifyReliability, classifyVault, clearPendleMarketsCache, 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, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFrankencoinMarketsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, detectInterfaceKinds, dssIlkBytes32, dssKeyParts, dssLenderKey, duration, earnDescription, earnLabel, earnMarketFromPool, earnMarketFromVault, earnUidFromMarketUid, earnVenueKind, encodeBalanceFetcherCalldata, enrichTermSheet, enrichmentIndexFromRows, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feePhrase, feedKeyOf, feedStatKey, fetchDolomiteAccountNumbers, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFluidFTokens, fetchFrankencoinMarkets, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchInverseMarkets, fetchLagoonApiVaults, fetchLagoonVaults, fetchLiquityMarkets, fetchListaVaultsFromChain, fetchLlamaLendMarkets, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendleApiAssets, fetchPendleApiMarkets, fetchPendlePrices, fetchPendlePtMarkets, fetchResupplyMarkets, fetchRiverMarkets, fetchSiloVaults, fetchTellerMarkets, fetchTermMarkets, fetchTermMaxMarkets, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchUsddMarkets, fetchYearnApiVaults, fetchYearnVaults, filterActiveLenders, filterLendersByProtocol, finalizeInfo, findingsFor, formatRaw, frankencoinKeyParts, frankencoinLenderKey, 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, getReadFailurePolicy, getResolvedDolomiteAccountNumbers, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getTermProfile, getVaultPublicDataAll, getVaultWithdrawalRequests, hasCritical, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasPendleMarkets, hasUpshiftVaults, hasYearnVaults, ilkToKeySegment, implausibleRatePercent, inverseKeyParts, inverseLenderKey, isFailedCall, isLiveMarket as isLivePendleMarket, isStablecoinSymbol, isVaultVenue, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, llamaLendKeyParts, llamaLendLenderKey, mergeDeep, multicall3Abi2 as multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, parseBalanceFetcherResult, parseEarnUid, parseMergedResult, parseMulticallRpcResponses, parseExpirySeconds as parsePendleExpirySeconds, parseRawRpcBatchResponses, parseRawRpcResponses, parseTermMaxLtv, parseTokenBalanceResult, pct, assetKey as pendleAssetKey, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, pruneFeedStats, rankFindings, ratePercent, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, resolveAdapter, resolveDerivation, resolveStCeloDepositGroup, resupplyKeyParts, resupplyLenderKey, resupplyMarketLabel, riverKeyParts, riverLenderKey, selectAssetGroupPrices, shortDate, splitChainScopedAddress as splitPendleChainScopedAddress, stampCapabilities, stampVaultClassification, supplyDescription, supplyFindings, supplyHeadline, 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, toDigest, toTermSheetInput, tryParseEarnUid, unflattenLenderData, updateFeedStats, usdValue, usddIlkBytes32, usddKeyParts, usddLenderKey, validateTermSheet, validateTermSheets, validateUserData, vaultVenue, venueBrand };
67093
68160
  //# sourceMappingURL=index.js.map
67094
68161
  //# sourceMappingURL=index.js.map