@1delta/margin-fetcher 5.0.136 → 5.0.138

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
@@ -9,7 +9,7 @@ import { Chain, isEvmChainId, isRetiredChain, isSvmChainId } from '@1delta/chain
9
9
  import { multicallRetryUniversal, getEvmClient, getEvmClientWithCustomRpcsUniversal, LIST_OVERRIDES, getEvmChain, createMulticallRetryUniversal, getEvmClientUniversal } from '@1delta/providers';
10
10
  import { LiquityTroveManagerAbi, LiquityActivePoolAbi, LiquityStabilityPoolAbi, LiquityPriceFeedAbi, LiquitySortedTrovesAbi, RiverTroveManagerAbi, RiverStabilityPoolAbi, TellerMarketRegistryAbi, TellerV2Abi, InverseMarketAbi, InverseOracleAbi, InverseDbrAbi, CurveTricryptoOracleAbi, Erc20Abi, CoolerMonoAbi, CoolerLtvOracleAbi, LlamaLendControllerAbi, LlamaLendControllerV1Abi, LlamaLendControllerV2Abi, LlamaLendVaultAbi, LlamaLendAmmAbi, TwyneCollateralVaultAbi, MetaMorphoAbi, FluidDexResolverAbi, ExactlyPreviewerAbi, ExactlyAuditorAbi, FlyingTulipLendingLensAbi, LiquityMultiTroveGetterAbi, LenderCommitmentGroupAbi, ResupplyRegistryAbi, ResupplyPairAbi, ResupplyUtilitiesAbi, ResupplyRewardHandlerAbi, ResupplyPairEmissionsAbi, ConvexPoolUtilAbi, FraxlendPairAbi, FraxlendLeverAbi, RipeMissionControlAbi, RipeLedgerAbi, RipeVaultBookAbi, RipePriceDeskAbi, RipeVaultAbi, RipeCreditEngineAbi, FrankencoinPositionAbi, FluidLendingResolverAbi, FluidVaultResolverAbi, FluidLiquidityResolverAbi, MoolahVaultAbi, UsddVatAbi, UsddJugAbi, UsddSpotAbi, MorphoLensAbi, AaveV4SpokeAbi, AaveV4OracleAbi, AaveV4HubAbi, DolomiteMarginAbi, GearboxMarketCompressorV310Abi, RipeHqAbi, MorphoBlueAbi, MidnightAbi, TermRepoTokenAbi, TermRepoServicerAbi, TermRepoCollateralManagerAbi, LiquityTroveNFTAbi, LiquityCollSurplusPoolAbi, TellerCollateralManagerAbi, TermMaxViewerAbi, InverseEscrowAbi, AlchemixAlchemistAbi, FlexTroveManagerAbi, CurvanceMarketManagerAbi, CurvanceCTokenAbi, GearboxCreditAccountCompressorV310Abi, TwyneVaultManagerAbi, TwyneCollateralVaultFactoryAbi, AaveV2V3Abi, TwyneATokenWrapperAbi, AlchemixPositionNftAbi, UsddCdpManagerAbi, UsddProxyRegistryAbi, CurvanceProtocolReaderAbi, CurvanceCentralRegistryAbi, TermPriceConsumerAbi, CurvanceOracleManagerAbi, FlexPriceOracleAbi, TermMaxOracleAggregatorV2Abi, AlchemixTransmuterAbi, FlexSortedTrovesAbi, FlexTokenizedStrategyAbi } from '@1delta/abis';
11
11
  export { MorphoLensAbi } from '@1delta/abis';
12
- import { NEST_SAVINGS_VAULTS, NEST_PREDICATE_PROXY, NEST_USDC, SUPERFORM_SUPERVAULTS, ROYCO_TRANCHES, STRATA_META_TRANCHES, MIDAS_VAULTS, MORINI_FXARB, EVA_VAULTS, prepareDebitDataMulticall, prepareLenderDebitMulticall, parseDebitDataResult, parseLenderDebitResult, getPermit2ContractAddress, getLstAcceptedInputs, savingsVerbRequires, savingsSupportsVerb, getCompoundV2Comptroller as getCompoundV2Comptroller$1, getCompoundV3CometAddress as getCompoundV3CometAddress$1, getMorphoAddress, FLUID_VAULT_FACTORY, getAaveStyleLenderTokenAddress, LendingMode, getAaveCollateralTokenAddress, getSiloHalfForUnderlying, findSavingsWithdrawEntry, bandLtvCurve, InitMarginAddresses, ignoresReceiver, buildLstWithdrawRequest, SAVINGS_RECEIVER_CAPABILITY } from '@1delta/calldata-sdk';
12
+ import { NEST_SAVINGS_VAULTS, NEST_PREDICATE_PROXY, NEST_USDC, SUPERFORM_SUPERVAULTS, ROYCO_TRANCHES, STRATA_META_TRANCHES, MIDAS_VAULTS, MORINI_FXARB, EMBER_VAULTS, EVA_VAULTS, prepareDebitDataMulticall, prepareLenderDebitMulticall, parseDebitDataResult, parseLenderDebitResult, getPermit2ContractAddress, getLstAcceptedInputs, savingsVerbRequires, savingsSupportsVerb, getCompoundV2Comptroller as getCompoundV2Comptroller$1, getCompoundV3CometAddress as getCompoundV3CometAddress$1, getMorphoAddress, FLUID_VAULT_FACTORY, getAaveStyleLenderTokenAddress, LendingMode, getAaveCollateralTokenAddress, getSiloHalfForUnderlying, findSavingsWithdrawEntry, bandLtvCurve, InitMarginAddresses, ignoresReceiver, buildLstWithdrawRequest, SAVINGS_RECEIVER_CAPABILITY } from '@1delta/calldata-sdk';
13
13
  import { proxyNativeFetch } from '@1delta/proxy-fetch';
14
14
  import { BALANCER_V2_FORKS, BALANCER_V3_FORKS, UNISWAP_V4_FORKS, isFlashLoanSourceExcluded, FLASH_LOAN_IDS } from '@1delta/dex-registry';
15
15
  import { getNativeDecimals, getWrappedNativeAddressSafe, isNativeWrapOneToOne } from '@1delta/wnative';
@@ -7340,15 +7340,15 @@ var getAaveV2ReservesDataConverter = (lender, chainId, prices, additionalYields,
7340
7340
  isActive: configData?.[8 /* isActive */],
7341
7341
  isFrozen: configData?.[9 /* isFrozen */]
7342
7342
  };
7343
- const aaveTokens4 = aaveTokenMap[asset];
7344
- if (!!aaveTokens4) {
7343
+ const aaveTokens6 = aaveTokenMap[asset];
7344
+ if (!!aaveTokens6) {
7345
7345
  resultReserves[marketUid] = {
7346
7346
  ...resultReserves[marketUid],
7347
7347
  params: {
7348
7348
  metadata: {
7349
- aToken: aaveTokens4.aToken,
7350
- vToken: aaveTokens4.vToken,
7351
- sToken: aaveTokens4.sToken
7349
+ aToken: aaveTokens6.aToken,
7350
+ vToken: aaveTokens6.vToken,
7351
+ sToken: aaveTokens6.sToken
7352
7352
  }
7353
7353
  }
7354
7354
  };
@@ -7580,15 +7580,15 @@ var getAaveV3ReservesDataConverter = (lender, chainId, prices, additionalYields,
7580
7580
  };
7581
7581
  })()
7582
7582
  };
7583
- const aaveTokens4 = aaveTokenMap[asset];
7584
- if (!!aaveTokens4) {
7583
+ const aaveTokens6 = aaveTokenMap[asset];
7584
+ if (!!aaveTokens6) {
7585
7585
  resultReserves[marketUid] = {
7586
7586
  ...resultReserves[marketUid],
7587
7587
  params: {
7588
7588
  metadata: {
7589
- aToken: aaveTokens4.aToken,
7590
- vToken: aaveTokens4.vToken,
7591
- sToken: aaveTokens4.sToken
7589
+ aToken: aaveTokens6.aToken,
7590
+ vToken: aaveTokens6.vToken,
7591
+ sToken: aaveTokens6.sToken
7592
7592
  }
7593
7593
  }
7594
7594
  };
@@ -7819,15 +7819,15 @@ function parseYLDRCall(chainId, lender, additionalYields, prices, tokenList) {
7819
7819
  isActive: configData?.[7 /* isActive */],
7820
7820
  isFrozen: configData?.[8 /* isFrozen */]
7821
7821
  };
7822
- const aaveTokens4 = aaveTokenMap[asset];
7823
- if (!!aaveTokens4) {
7822
+ const aaveTokens6 = aaveTokenMap[asset];
7823
+ if (!!aaveTokens6) {
7824
7824
  resultReserves[marketUid] = {
7825
7825
  ...resultReserves[marketUid],
7826
7826
  params: {
7827
7827
  metadata: {
7828
- aToken: aaveTokens4.aToken,
7829
- vToken: aaveTokens4.vToken,
7830
- sToken: aaveTokens4.sToken
7828
+ aToken: aaveTokens6.aToken,
7829
+ vToken: aaveTokens6.vToken,
7830
+ sToken: aaveTokens6.sToken
7831
7831
  }
7832
7832
  }
7833
7833
  };
@@ -8021,15 +8021,15 @@ function parseAave32(chainId, lender, prices, additionalYields, tokenList) {
8021
8021
  };
8022
8022
  })()
8023
8023
  };
8024
- const aaveTokens4 = aaveTokenMap[asset];
8025
- if (!!aaveTokens4) {
8024
+ const aaveTokens6 = aaveTokenMap[asset];
8025
+ if (!!aaveTokens6) {
8026
8026
  resultReserves[marketUid] = {
8027
8027
  ...resultReserves[marketUid],
8028
8028
  params: {
8029
8029
  metadata: {
8030
- aToken: aaveTokens4.aToken,
8031
- vToken: aaveTokens4.vToken,
8032
- sToken: aaveTokens4.sToken
8030
+ aToken: aaveTokens6.aToken,
8031
+ vToken: aaveTokens6.vToken,
8032
+ sToken: aaveTokens6.sToken
8033
8033
  }
8034
8034
  }
8035
8035
  };
@@ -20441,6 +20441,8 @@ var buildFluidCall = (chainId, _lender) => {
20441
20441
  // src/lending/public-data/fluid/apiData.ts
20442
20442
  var FLUID_API_BASE = "https://api.fluid.instadapp.io/v2";
20443
20443
  var SUPPORTED_CHAINS = /* @__PURE__ */ new Set(["1", "56", "137", "8453", "9745", "42161"]);
20444
+ var FLUID_API_CHAINS = [...SUPPORTED_CHAINS];
20445
+ var FLUID_EEE = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
20444
20446
  var TTL_MS2 = 6e4;
20445
20447
  var ZERO_ADDRESS4 = "0x0000000000000000000000000000000000000000";
20446
20448
  var cache2 = {};
@@ -20469,6 +20471,17 @@ var parseSide = (d, sideToken) => {
20469
20471
  token1Decimals: d1
20470
20472
  };
20471
20473
  };
20474
+ var normalizeLeg = (addr5) => {
20475
+ const a = String(addr5 ?? "").toLowerCase();
20476
+ return a === FLUID_EEE ? ZERO_ADDRESS4 : a;
20477
+ };
20478
+ var sideLegs = (side2, isSmart) => {
20479
+ const t0 = normalizeLeg(side2?.token0?.address);
20480
+ if (!t0) return [];
20481
+ if (!isSmart) return [t0];
20482
+ const t1 = normalizeLeg(side2?.token1?.address);
20483
+ return t1 ? [t0, t1] : [t0];
20484
+ };
20472
20485
  var parseChainPayload = (raw) => {
20473
20486
  const out = {};
20474
20487
  for (const v of raw ?? []) {
@@ -20478,6 +20491,15 @@ var parseChainPayload = (raw) => {
20478
20491
  out[vaultId] = {
20479
20492
  vaultId,
20480
20493
  vaultType,
20494
+ address: v?.address ? String(v.address).toLowerCase() : void 0,
20495
+ supplyTokens: sideLegs(
20496
+ v?.supplyToken,
20497
+ vaultType === 2 || vaultType === 4
20498
+ ),
20499
+ borrowTokens: sideLegs(
20500
+ v?.borrowToken,
20501
+ vaultType === 3 || vaultType === 4
20502
+ ),
20481
20503
  supplyShares: parseSide(v?.supplyDexData, v?.supplyToken),
20482
20504
  borrowShares: parseSide(v?.borrowDexData, v?.borrowToken),
20483
20505
  supplyDexTradingRate: Number(v?.supplyRate?.dex?.trading ?? 0),
@@ -24807,7 +24829,7 @@ async function fetchTellerMarkets(chainId, multicallRetry = multicallRetryUniver
24807
24829
  } catch {
24808
24830
  return { chainId, pools: [] };
24809
24831
  }
24810
- const big31 = (i) => {
24832
+ const big32 = (i) => {
24811
24833
  const r = results[i];
24812
24834
  if (typeof r === "bigint") return r;
24813
24835
  if (typeof r === "number") return BigInt(r);
@@ -24820,21 +24842,21 @@ async function fetchTellerMarkets(chainId, multicallRetry = multicallRetryUniver
24820
24842
  }
24821
24843
  return null;
24822
24844
  };
24823
- const num22 = (i) => {
24824
- const b = big31(i);
24845
+ const num23 = (i) => {
24846
+ const b = big32(i);
24825
24847
  return b === null ? null : Number(b);
24826
24848
  };
24827
24849
  const pool0 = pools.map((config, i) => {
24828
24850
  const base = i * READS_PER_POOL;
24829
24851
  return {
24830
24852
  config,
24831
- available: big31(base),
24832
- committed: big31(base + 1),
24833
- minRateBps: num22(base + 2),
24834
- collateralPerPrincipal: big31(base + 3),
24835
- maxLoanDuration: num22(base + 4),
24836
- marketId: big31(base + 5),
24837
- totalAssets: big31(base + 6)
24853
+ available: big32(base),
24854
+ committed: big32(base + 1),
24855
+ minRateBps: num23(base + 2),
24856
+ collateralPerPrincipal: big32(base + 3),
24857
+ maxLoanDuration: num23(base + 4),
24858
+ marketId: big32(base + 5),
24859
+ totalAssets: big32(base + 6)
24838
24860
  };
24839
24861
  });
24840
24862
  const attByMarket = /* @__PURE__ */ new Map();
@@ -26030,20 +26052,20 @@ async function fetchInverseMarkets(lender, chainId, multicallRetry = multicallRe
26030
26052
  if (Object.keys(byAddr).length > 0) {
26031
26053
  const rows = markets.map((market) => {
26032
26054
  const m = byAddr[market.address.toLowerCase()];
26033
- const num22 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
26055
+ const num23 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
26034
26056
  return {
26035
26057
  market,
26036
- totalDebt: num22(m?.totalDebt),
26037
- dolaLiquidity: num22(m?.dolaLiquidity),
26038
- leftToBorrow: num22(m?.leftToBorrow),
26039
- price: num22(m?.price),
26058
+ totalDebt: num23(m?.totalDebt),
26059
+ dolaLiquidity: num23(m?.dolaLiquidity),
26060
+ leftToBorrow: num23(m?.leftToBorrow),
26061
+ price: num23(m?.price),
26040
26062
  borrowPaused: typeof m?.borrowPaused === "boolean" ? m.borrowPaused : null,
26041
- dailyBorrows: num22(m?.dailyBorrows),
26063
+ dailyBorrows: num23(m?.dailyBorrows),
26042
26064
  // The API serves it as a DECIMAL (`replenishmentIncentive: 0.1`),
26043
26065
  // unlike the on-chain bps — normalize here, and fall back to the
26044
26066
  // curated metadata value when the field is missing.
26045
26067
  replenishmentIncentiveBps: (() => {
26046
- const dec2 = num22(m?.replenishmentIncentive);
26068
+ const dec2 = num23(m?.replenishmentIncentive);
26047
26069
  if (dec2 !== null) return Math.round(dec2 * 1e4);
26048
26070
  const meta = Number(market.replenishmentIncentiveBps);
26049
26071
  return Number.isFinite(meta) ? meta : null;
@@ -26052,7 +26074,7 @@ async function fetchInverseMarkets(lender, chainId, multicallRetry = multicallRe
26052
26074
  escrowYieldApy: (() => {
26053
26075
  const escrow = String(m?.escrowImplementation ?? "").toLowerCase();
26054
26076
  if (!escrow || escrow === SIMPLE_ESCROW) return null;
26055
- const apy = (num22(m?.supplyApy) ?? 0) + (num22(m?.extraApy) ?? 0);
26077
+ const apy = (num23(m?.supplyApy) ?? 0) + (num23(m?.extraApy) ?? 0);
26056
26078
  return apy > 0 ? apy : null;
26057
26079
  })()
26058
26080
  };
@@ -30940,12 +30962,12 @@ async function fetchDssMarkets(lender, chainId, multicallRetry = multicallRetryU
30940
30962
  } catch {
30941
30963
  return { lender, config, chainData, markets: [] };
30942
30964
  }
30943
- const big31 = (v) => {
30965
+ const big32 = (v) => {
30944
30966
  if (typeof v === "bigint") return v;
30945
30967
  if (typeof v === "number") return BigInt(v);
30946
30968
  return null;
30947
30969
  };
30948
- const field16 = (res, name, idx) => big31(res?.[name] ?? res?.[idx]);
30970
+ const field16 = (res, name, idx) => big32(res?.[name] ?? res?.[idx]);
30949
30971
  let cursor = 0;
30950
30972
  const out = markets.map((market, i) => {
30951
30973
  const base = cursor;
@@ -30962,7 +30984,7 @@ async function fetchDssMarkets(lender, chainId, multicallRetry = multicallRetryU
30962
30984
  dust: field16(vatIlk, "dust", 4),
30963
30985
  duty: field16(jugIlk, "duty", 0),
30964
30986
  mat: field16(spotIlk, "mat", 1),
30965
- joinBalance: joinReadIndex[i] >= 0 ? big31(results[joinReadIndex[i]]) : null
30987
+ joinBalance: joinReadIndex[i] >= 0 ? big32(results[joinReadIndex[i]]) : null
30966
30988
  };
30967
30989
  });
30968
30990
  return { lender, config, chainData, markets: out };
@@ -31236,26 +31258,26 @@ async function fetchFrankencoinMarkets(lender, chainId, multicallRetry = multica
31236
31258
  } catch {
31237
31259
  return { lender, config, chainData, markets: [] };
31238
31260
  }
31239
- const big31 = (v) => {
31261
+ const big32 = (v) => {
31240
31262
  if (typeof v === "bigint") return v;
31241
31263
  if (typeof v === "number") return BigInt(v);
31242
31264
  return null;
31243
31265
  };
31244
31266
  const out = markets.map((market, i) => {
31245
31267
  const base = i * READS_PER_MARKET3;
31246
- const expiration = big31(results[base + 7]);
31268
+ const expiration = big32(results[base + 7]);
31247
31269
  return {
31248
31270
  market,
31249
- price: big31(results[base]),
31250
- minted: big31(results[base + 1]),
31251
- availableForClones: big31(results[base + 2]),
31252
- annualInterestPPM: big31(results[base + 3]),
31253
- currentFeePPM: big31(results[base + 4]),
31254
- reserveContribution: big31(results[base + 5]),
31255
- challengedAmount: big31(results[base + 6]),
31271
+ price: big32(results[base]),
31272
+ minted: big32(results[base + 1]),
31273
+ availableForClones: big32(results[base + 2]),
31274
+ annualInterestPPM: big32(results[base + 3]),
31275
+ currentFeePPM: big32(results[base + 4]),
31276
+ reserveContribution: big32(results[base + 5]),
31277
+ challengedAmount: big32(results[base + 6]),
31256
31278
  expiration,
31257
31279
  isClosed: typeof results[base + 8] === "boolean" ? results[base + 8] : null,
31258
- collateralBalance: big31(results[base + 9])
31280
+ collateralBalance: big32(results[base + 9])
31259
31281
  };
31260
31282
  });
31261
31283
  return { lender, config, chainData, markets: out };
@@ -38008,7 +38030,7 @@ var getFluidUserDataConverter = (lender, chainId, account, meta) => {
38008
38030
  const constants = vaultData.constantVariables;
38009
38031
  const isSmartCol = !!vaultData.isSmartCol;
38010
38032
  const isSmartDebt = !!vaultData.isSmartDebt;
38011
- const sideLegs = (side2, isSmart, sideContract, perShareOf) => {
38033
+ const sideLegs2 = (side2, isSmart, sideContract, perShareOf) => {
38012
38034
  const raw = side2?.token0 !== void 0 ? side2 : { token0: side2 };
38013
38035
  const tokens = [
38014
38036
  normalizeUnderlying2((raw?.token0 ?? "").toString().toLowerCase())
@@ -38045,13 +38067,13 @@ var getFluidUserDataConverter = (lender, chainId, account, meta) => {
38045
38067
  }
38046
38068
  return legs;
38047
38069
  };
38048
- const colLegs = sideLegs(
38070
+ const colLegs = sideLegs2(
38049
38071
  constants.supplyToken,
38050
38072
  isSmartCol,
38051
38073
  constants.supply,
38052
38074
  (s) => [s.token0PerSupplyShare, s.token1PerSupplyShare]
38053
38075
  );
38054
- const debtLegs = sideLegs(
38076
+ const debtLegs = sideLegs2(
38055
38077
  constants.borrowToken,
38056
38078
  isSmartDebt,
38057
38079
  constants.borrow,
@@ -56957,15 +56979,9 @@ var VAULT_SHARE_RATE_SPECS = [
56957
56979
  ],
56958
56980
  allowNegative: true
56959
56981
  },
56960
- // Ember eEARN — ERC-4626 over USDC, 8.55 %, ~$3.67M.
56961
- erc4626(
56962
- "eEARN",
56963
- "1",
56964
- "0x9be9294722f8aad37b11a9792be2c782182cafa2",
56965
- E6,
56966
- ["Ember Earn::eEARN"],
56967
- { allowNegative: true }
56968
- ),
56982
+ // Ember eEARN moved to `ember.ts` (2026-10-22): it now carries a savings
56983
+ // row, which vault-wires its own fetcher, and its rate is a step function
56984
+ // measured mark to mark.
56969
56985
  // Veda PlasmaUSD (Plasma) — BoringVault; the rate is its accountant's
56970
56986
  // `getRate()` (USDT0 per share, 6 dec). 4.07 %, ~$30.6M.
56971
56987
  {
@@ -58047,6 +58063,148 @@ var entry = (symbol) => {
58047
58063
  var EVA_ENTRIES = {
58048
58064
  "1": [entry("evaUSDC"), entry("evaUSDT")]
58049
58065
  };
58066
+ var RATE = parseAbiItem(
58067
+ "function rate() view returns (uint256 value, uint256 maxRateChangePerUpdate, uint256 rateUpdateInterval, uint256 lastUpdatedAt)"
58068
+ );
58069
+ var EMBER_RATE_SPECS = [
58070
+ {
58071
+ tag: "eEARN",
58072
+ chainId: "1",
58073
+ vault: "0x9be9294722f8aad37b11a9792be2c782182cafa2",
58074
+ keys: ["Ember Earn::eEARN"],
58075
+ windowDays: 30
58076
+ },
58077
+ {
58078
+ tag: "pALPHA",
58079
+ chainId: "1",
58080
+ vault: "0xc3aacb558afb635307b66fdb405188138576fc4c",
58081
+ keys: ["Ember Pharos Alpha::pALPHA"],
58082
+ windowDays: 30
58083
+ },
58084
+ {
58085
+ // Monthly marks (and a missed one): a 30-day window would usually hold none.
58086
+ tag: "tulPRWA",
58087
+ chainId: "1",
58088
+ vault: "0xaa1d6fa2bc21d5518dcbb0fa37e07b44c9899d26",
58089
+ keys: ["Ember TulipaPRWA::tulPRWA"],
58090
+ windowDays: 120
58091
+ }
58092
+ ];
58093
+ var DAY5 = 86400;
58094
+ var PER_REQUEST_TIMEOUT_MS6 = 6e3;
58095
+ var SPEC_DEADLINE_MS2 = 2e4;
58096
+ var BLOCK_TIME_SAMPLE6 = 100000n;
58097
+ var MAX_ABS_APR2 = 1e3;
58098
+ var readRate3 = async (client, vault, blockNumber) => {
58099
+ const r = await client.readContract({
58100
+ address: vault,
58101
+ abi: [RATE],
58102
+ functionName: "rate",
58103
+ blockNumber
58104
+ });
58105
+ return { value: r[0], markedAtMs: r[3] };
58106
+ };
58107
+ var computeEmberApr = async (spec, rpcs = ARCHIVAL_RPCS) => {
58108
+ const roster = rpcs[spec.chainId];
58109
+ if (!roster?.length) throw new Error(`${spec.tag}: no archival roster`);
58110
+ const deadline = Date.now() + SPEC_DEADLINE_MS2;
58111
+ let lastErr;
58112
+ let flat = false;
58113
+ for (let rpcId = 0; rpcId < roster.length; rpcId++) {
58114
+ if (Date.now() > deadline) break;
58115
+ try {
58116
+ const client = getEvmClientWithCustomRpcsUniversal({
58117
+ chain: spec.chainId,
58118
+ rpcId,
58119
+ customRpcs: { [spec.chainId]: roster },
58120
+ timeoutMs: PER_REQUEST_TIMEOUT_MS6
58121
+ });
58122
+ const head = await client.getBlock();
58123
+ const sample = await client.getBlock({
58124
+ blockNumber: head.number - BLOCK_TIME_SAMPLE6
58125
+ });
58126
+ const blockTime = Number(head.timestamp - sample.timestamp) / Number(BLOCK_TIME_SAMPLE6);
58127
+ if (!(blockTime > 0)) throw new Error("bad block-time sample");
58128
+ const back = BigInt(Math.floor(spec.windowDays * DAY5 / blockTime));
58129
+ const [now, then] = await Promise.all([
58130
+ readRate3(client, spec.vault, head.number),
58131
+ // Before the vault existed the read reverts — treat as "no mark".
58132
+ readRate3(client, spec.vault, head.number - back).catch(() => void 0)
58133
+ ]);
58134
+ if (!then || then.value === 0n || now.value === 0n) {
58135
+ flat = true;
58136
+ continue;
58137
+ }
58138
+ if (now.markedAtMs <= then.markedAtMs) {
58139
+ flat = true;
58140
+ continue;
58141
+ }
58142
+ const elapsed = Number(now.markedAtMs - then.markedAtMs) / 1e3;
58143
+ const apr = annualizeRateDeltaPercent(then.value, now.value, elapsed);
58144
+ if (!Number.isFinite(apr) || Math.abs(apr) > MAX_ABS_APR2)
58145
+ throw new Error(`bad apr ${apr}`);
58146
+ return apr;
58147
+ } catch (e) {
58148
+ lastErr = e;
58149
+ }
58150
+ }
58151
+ if (flat) return void 0;
58152
+ throw new Error(`${spec.tag}: no archival read (${String(lastErr)})`);
58153
+ };
58154
+ var emberVaultsFetcher = {
58155
+ label: "EMBER_VAULTS",
58156
+ fetch: async () => {
58157
+ const settled = await Promise.allSettled(
58158
+ EMBER_RATE_SPECS.map((s) => computeEmberApr(s))
58159
+ );
58160
+ const out = {};
58161
+ settled.forEach((s, i) => {
58162
+ if (s.status === "fulfilled") {
58163
+ if (s.value === void 0) return;
58164
+ for (const k of EMBER_RATE_SPECS[i].keys) out[k] = s.value;
58165
+ } else {
58166
+ console.warn(`[EMBER_VAULTS] ${String(s.reason)}`);
58167
+ }
58168
+ });
58169
+ return out;
58170
+ }
58171
+ };
58172
+
58173
+ // src/vaults/savings/registryEmber.ts
58174
+ var DESCRIPTIONS = {
58175
+ eEARN: "eEARN is Ember's flagship USDC vault on Ethereum, run by Ember itself: stablecoin lending spreads, looping on blue-chip lenders and delta-neutral funding capture. Its share price is not accrued on-chain \u2014 Ember's rate manager restates it about once a day, and the rate shown is measured between those restatements. Deposits mint at once; a withdrawal is a request that Ember's operator pays out at the share price of the day it is processed. The USDC is held by Ember's operator accounts, not by the vault.",
58176
+ pALPHA: "pALPHA is Ember's Pharos RealFi vault, listed by third parties as run by Asset Partners across Axil's consumer-credit vault and Janus Henderson's tokenised Treasury fund; the token bridges to Pharos over LayerZero. Ember's rate manager restates the share price, and the rate shown is measured between restatements. Withdrawals settle in periodic windows as a request paid at that day's share price \u2014 and at integration they were paused on Ethereum while deposits stayed open. The USDC is held by Ember's operator accounts, not by the vault.",
58177
+ tulPRWA: "tulPRWA is Tulipa Capital's multi-asset real-world-asset vault (real-estate credit) on Ember's vault infrastructure. Deposits are queued and minted when Ember's operator processes them, about monthly; a withdrawal is a request paid at that day's share price, targeting 45 days (up to 60). Ember's rate manager restates the share price \u2014 once in the first five months, on 29 August 2026 \u2014 so the rate shown is measured between restatements, after Tulipa's 20 % performance fee, and is well below the advertised target. Four wallets held over 99 % at integration."
58178
+ };
58179
+ var COOLDOWN_SECONDS = {
58180
+ tulPRWA: 45 * 86400
58181
+ };
58182
+ var yieldKeyFor = (symbol) => EMBER_RATE_SPECS.find((s) => s.tag === symbol)?.keys[0];
58183
+ var EMBER_ENTRIES = EMBER_VAULTS.reduce(
58184
+ (out, v) => {
58185
+ const description = DESCRIPTIONS[v.symbol];
58186
+ if (!description) return out;
58187
+ const yieldKey = yieldKeyFor(v.symbol);
58188
+ (out[v.chainId] ??= []).push({
58189
+ reader: "ember-vault",
58190
+ address: v.vault,
58191
+ underlying: v.underlying,
58192
+ symbol: v.symbol,
58193
+ brand: v.curator,
58194
+ description,
58195
+ decimals: v.decimals,
58196
+ underlyingDecimals: v.decimals,
58197
+ isRebasing: false,
58198
+ isMintable: true,
58199
+ withdrawalMode: "request-based",
58200
+ withdrawalCooldownSeconds: COOLDOWN_SECONDS[v.symbol],
58201
+ solvency: "nav-attested",
58202
+ ...yieldKey ? { yieldFetcher: emberVaultsFetcher, yieldKey } : {}
58203
+ });
58204
+ return out;
58205
+ },
58206
+ {}
58207
+ );
58050
58208
 
58051
58209
  // src/yields/intrinsic/fetchers/midas.ts
58052
58210
  var MIDAS_APY_URL = "https://api-prod.midas.app/api/data/apys";
@@ -60529,6 +60687,10 @@ var SAVINGS_REGISTRY = (() => {
60529
60687
  if (!out[chainId]) out[chainId] = [];
60530
60688
  out[chainId].push(...entries);
60531
60689
  }
60690
+ for (const [chainId, entries] of Object.entries(EMBER_ENTRIES)) {
60691
+ if (!out[chainId]) out[chainId] = [];
60692
+ out[chainId].push(...entries);
60693
+ }
60532
60694
  for (const [chainId, entries] of Object.entries(MIDAS_ENTRIES)) {
60533
60695
  if (!out[chainId]) out[chainId] = [];
60534
60696
  out[chainId].push(...entries);
@@ -64080,9 +64242,9 @@ var AVKAT = "0x7231dbacdfc968e07656d12389ab20de82fbfceb";
64080
64242
  var AVKAT_YIELD_KEY = "Autocompounding vKAT::avKAT";
64081
64243
  var ONE_E1820 = 10n ** 18n;
64082
64244
  var WINDOW_SECONDS13 = 30 * 86400;
64083
- var BLOCK_TIME_SAMPLE6 = 100000n;
64245
+ var BLOCK_TIME_SAMPLE7 = 100000n;
64084
64246
  var MAX_RPC_TRIES13 = 3;
64085
- var PER_REQUEST_TIMEOUT_MS6 = 6e3;
64247
+ var PER_REQUEST_TIMEOUT_MS7 = 6e3;
64086
64248
  var ABI = [
64087
64249
  {
64088
64250
  name: "convertToAssets",
@@ -64097,13 +64259,13 @@ var computeAvkatApr = async () => {
64097
64259
  for (let rpcId = 0; rpcId < MAX_RPC_TRIES13; rpcId++) {
64098
64260
  try {
64099
64261
  const client = getEvmClient(CHAIN_ID20, rpcId, {
64100
- timeoutMs: PER_REQUEST_TIMEOUT_MS6
64262
+ timeoutMs: PER_REQUEST_TIMEOUT_MS7
64101
64263
  });
64102
64264
  const head = await client.getBlock();
64103
64265
  const sample = await client.getBlock({
64104
- blockNumber: head.number - BLOCK_TIME_SAMPLE6
64266
+ blockNumber: head.number - BLOCK_TIME_SAMPLE7
64105
64267
  });
64106
- const blockTime = Number(head.timestamp - sample.timestamp) / Number(BLOCK_TIME_SAMPLE6);
64268
+ const blockTime = Number(head.timestamp - sample.timestamp) / Number(BLOCK_TIME_SAMPLE7);
64107
64269
  if (!(blockTime > 0)) throw new Error("bad block-time sample");
64108
64270
  const pastBlock = head.number - BigInt(Math.floor(WINDOW_SECONDS13 / blockTime));
64109
64271
  const read = (blockNumber) => client.readContract({
@@ -64295,8 +64457,6 @@ async function fetchIntrinsicYields() {
64295
64457
  await propagateReceiptYields(intrinsicYields);
64296
64458
  return intrinsicYields;
64297
64459
  }
64298
-
64299
- // src/yields/rewards/merkl.ts
64300
64460
  var MERKL_API_BASE = "https://api.merkl.xyz/v4";
64301
64461
  async function fetchMerklOpportunities(protocolId, chainId) {
64302
64462
  const all = [];
@@ -64415,7 +64575,11 @@ function merklSourceRef(opp, merklProtocolId) {
64415
64575
  link: getMerkleUrl(opp),
64416
64576
  platform: "merkl",
64417
64577
  refs: {
64578
+ // `opportunityId` predates the numeric id and is kept for the recorder:
64579
+ // it is the URL `identifier`, NOT what Merkl's user-rewards breakdowns
64580
+ // call `opportunityId`. That one is `merklOpportunityId` below.
64418
64581
  opportunityId: opp.identifier,
64582
+ ...opp.id ? { merklOpportunityId: String(opp.id) } : {},
64419
64583
  opportunityType: opp.type,
64420
64584
  chain: opp.chain?.name ?? String(opp.chainId),
64421
64585
  ...opp.name ? { opportunityName: opp.name } : {},
@@ -64440,18 +64604,63 @@ function resolveUnderlyingFromOpportunity(opp) {
64440
64604
  if (underlying) return underlying.address.toLowerCase();
64441
64605
  return opp.tokens[0].address.toLowerCase();
64442
64606
  }
64443
- function createMerklRewardFetcher(config) {
64607
+ function resolveAaveV3ReserveToken(opp) {
64608
+ const explorer = opp.explorerAddress?.toLowerCase();
64609
+ if (explorer) return { asset: explorer };
64610
+ const underlying = resolveUnderlyingFromOpportunity(opp);
64611
+ const candidates = (opp.tokens ?? []).filter(
64612
+ (t) => t.address.toLowerCase() !== underlying
64613
+ );
64614
+ if (candidates.length !== 1) return void 0;
64615
+ return { asset: candidates[0].address.toLowerCase() };
64616
+ }
64617
+ function collectMerklRewards(oppLists, config) {
64444
64618
  const defaultResolve = (opp) => {
64445
64619
  const asset = resolveUnderlyingFromOpportunity(opp);
64446
64620
  if (!asset) return void 0;
64447
64621
  return { asset };
64448
64622
  };
64449
64623
  const resolve = config.resolveAsset ?? defaultResolve;
64624
+ const result = {};
64625
+ const byReserveToken = {};
64626
+ for (const opps of oppLists) {
64627
+ for (const opp of opps) {
64628
+ if (!opp.apr || opp.apr <= 0) continue;
64629
+ const chainId = String(opp.chainId);
64630
+ const resolvedRaw = resolve(opp);
64631
+ if (!resolvedRaw) continue;
64632
+ const resolutions = (Array.isArray(resolvedRaw) ? resolvedRaw : [resolvedRaw]).filter((r) => Boolean(r?.asset));
64633
+ for (const resolved2 of resolutions) {
64634
+ const bucket = resolved2.bucket ?? (opp.action === "LEND" ? "deposit" : opp.action === "BORROW" ? "borrow" : void 0);
64635
+ if (!bucket) continue;
64636
+ const keyBy = resolved2.keyBy ?? (config.keyByReserveToken ? "reserveToken" : "lender");
64637
+ const reward = keyBy === "reserveToken" ? ensureReserveTokenReward(byReserveToken, chainId, resolved2.asset) : ensureReward(
64638
+ result,
64639
+ chainId,
64640
+ resolved2.lender ?? config.lenderKey,
64641
+ resolved2.asset
64642
+ );
64643
+ const breakdowns = extractRewardBreakdowns(opp);
64644
+ reward.link = getMerkleUrl(opp);
64645
+ const source = merklSourceRef(opp, config.merklProtocolId);
64646
+ if (!reward.streams) reward.streams = [];
64647
+ reward.streams.push(...buildMerklStreams(opp, bucket, opp.apr, source));
64648
+ if (bucket === "deposit") {
64649
+ reward.deposit += opp.apr;
64650
+ reward.additionalDepositData.push(...breakdowns);
64651
+ } else {
64652
+ reward.borrow += opp.apr;
64653
+ reward.additionalBorrowData.push(...breakdowns);
64654
+ }
64655
+ }
64656
+ }
64657
+ }
64658
+ return { byLender: result, byReserveToken };
64659
+ }
64660
+ function createMerklRewardFetcher(config) {
64450
64661
  return {
64451
64662
  label: `MERKL_${config.merklProtocolId.toUpperCase()}`,
64452
64663
  fetch: async () => {
64453
- const result = {};
64454
- const byReserveToken = {};
64455
64664
  const chainResults = config.chainIds ? await Promise.all(
64456
64665
  config.chainIds.map(async (chainId) => {
64457
64666
  try {
@@ -64465,45 +64674,7 @@ function createMerklRewardFetcher(config) {
64465
64674
  }
64466
64675
  })
64467
64676
  ) : [await fetchMerklOpportunities(config.merklProtocolId)];
64468
- for (const opps of chainResults) {
64469
- for (const opp of opps) {
64470
- if (!opp.apr || opp.apr <= 0) continue;
64471
- const chainId = String(opp.chainId);
64472
- const resolvedRaw = resolve(opp);
64473
- if (!resolvedRaw) continue;
64474
- const resolutions = (Array.isArray(resolvedRaw) ? resolvedRaw : [resolvedRaw]).filter((r) => Boolean(r?.asset));
64475
- for (const resolved2 of resolutions) {
64476
- const bucket = resolved2.bucket ?? (opp.action === "LEND" ? "deposit" : opp.action === "BORROW" ? "borrow" : void 0);
64477
- if (!bucket) continue;
64478
- const keyBy = resolved2.keyBy ?? (config.keyByReserveToken ? "reserveToken" : "lender");
64479
- const reward = keyBy === "reserveToken" ? ensureReserveTokenReward(
64480
- byReserveToken,
64481
- chainId,
64482
- resolved2.asset
64483
- ) : ensureReward(
64484
- result,
64485
- chainId,
64486
- resolved2.lender ?? config.lenderKey,
64487
- resolved2.asset
64488
- );
64489
- const breakdowns = extractRewardBreakdowns(opp);
64490
- reward.link = getMerkleUrl(opp);
64491
- const source = merklSourceRef(opp, config.merklProtocolId);
64492
- if (!reward.streams) reward.streams = [];
64493
- reward.streams.push(
64494
- ...buildMerklStreams(opp, bucket, opp.apr, source)
64495
- );
64496
- if (bucket === "deposit") {
64497
- reward.deposit += opp.apr;
64498
- reward.additionalDepositData.push(...breakdowns);
64499
- } else {
64500
- reward.borrow += opp.apr;
64501
- reward.additionalBorrowData.push(...breakdowns);
64502
- }
64503
- }
64504
- }
64505
- }
64506
- return { byLender: result, byReserveToken };
64677
+ return collectMerklRewards(chainResults, config);
64507
64678
  }
64508
64679
  };
64509
64680
  }
@@ -64519,26 +64690,34 @@ var aaveMerklRewardFetcher = createMerklRewardFetcher({
64519
64690
  // (V3 USDC borrow read 5.75% = 1.75 + 2 + 2; V3 USDG read 12% = two V4 hubs)
64520
64691
  // and left the deployments actually running the campaigns at 0%.
64521
64692
  keyByReserveToken: true,
64522
- resolveAsset: (opp) => {
64523
- const explorer = opp.explorerAddress?.toLowerCase();
64524
- if (opp.type?.startsWith("AAVE_V4")) {
64525
- const underlying2 = resolveUnderlyingFromOpportunity(opp);
64526
- if (!explorer || !underlying2) return void 0;
64527
- return {
64528
- asset: underlying2,
64529
- lender: `AAVE_V4_${explorer.slice(2).toUpperCase()}`,
64530
- keyBy: "lender"
64531
- };
64532
- }
64533
- if (explorer) return { asset: explorer };
64534
- const underlying = resolveUnderlyingFromOpportunity(opp);
64535
- const candidates = (opp.tokens ?? []).filter(
64536
- (t) => t.address.toLowerCase() !== underlying
64537
- );
64538
- if (candidates.length !== 1) return void 0;
64539
- return { asset: candidates[0].address.toLowerCase() };
64540
- }
64693
+ resolveAsset: (opp) => resolveAaveOpp(opp)
64694
+ });
64695
+ var neverlandMerklRewardFetcher = createMerklRewardFetcher({
64696
+ merklProtocolId: "neverland",
64697
+ lenderKey: "NEVERLAND",
64698
+ keyByReserveToken: true,
64699
+ resolveAsset: resolveAaveV3ReserveToken
64700
+ });
64701
+ var layerBankMerklRewardFetcher = createMerklRewardFetcher({
64702
+ merklProtocolId: "layerbank",
64703
+ lenderKey: "LAYERBANK_V3",
64704
+ keyByReserveToken: true,
64705
+ resolveAsset: resolveAaveV3ReserveToken
64541
64706
  });
64707
+ var dolomiteMerklRewardFetcher = createMerklRewardFetcher({
64708
+ merklProtocolId: "dolomite",
64709
+ lenderKey: "DOLOMITE",
64710
+ resolveAsset: resolveDolomiteAsset
64711
+ });
64712
+ function resolveDolomiteAsset(opp) {
64713
+ const explorer = opp.explorerAddress?.toLowerCase();
64714
+ const tokens = opp.tokens ?? [];
64715
+ if (explorer && tokens.some((t) => t.address.toLowerCase() === explorer))
64716
+ return { asset: explorer };
64717
+ if (!explorer && tokens.length === 1)
64718
+ return { asset: tokens[0].address.toLowerCase() };
64719
+ return void 0;
64720
+ }
64542
64721
  function parseEulerVaultFromUrl(depositUrl) {
64543
64722
  if (!depositUrl) return void 0;
64544
64723
  try {
@@ -64559,14 +64738,9 @@ function parseEulerVaultFromUrl(depositUrl) {
64559
64738
  var eulerMerklRewardFetcher = createMerklRewardFetcher({
64560
64739
  merklProtocolId: "euler",
64561
64740
  lenderKey: "EULER_V2",
64562
- resolveAsset: (opp) => {
64563
- if (opp.type === "MULTILENDBORROW") {
64564
- return (opp.tokens ?? []).filter((t) => !t.symbol?.endsWith("-DEBT")).map((t) => ({ asset: t.address.toLowerCase() }));
64565
- }
64566
- const vault = (opp.action === "BORROW" ? parseEulerVaultFromUrl(opp.depositUrl) : void 0) ?? opp.explorerAddress?.toLowerCase();
64567
- if (!vault) return void 0;
64568
- return { asset: vault };
64569
- }
64741
+ // Borrow opps point `explorerAddress` at the debt token — the deep link
64742
+ // names the EVault; lend opps' `explorerAddress` already is the EVault.
64743
+ resolveAsset: (opp) => resolveEulerOpp(opp)
64570
64744
  });
64571
64745
  function parseMorphoUniqueKey(depositUrl) {
64572
64746
  if (!depositUrl) return void 0;
@@ -64588,6 +64762,227 @@ var morphoCollateralMerklRewardFetcher = createMerklRewardFetcher({
64588
64762
  };
64589
64763
  }
64590
64764
  });
64765
+ var RATE_CONFIGS = {
64766
+ aave: {
64767
+ merklProtocolId: "aave",
64768
+ lenderKey: "AAVE_V3",
64769
+ keyByReserveToken: true
64770
+ },
64771
+ neverland: {
64772
+ merklProtocolId: "neverland",
64773
+ lenderKey: "NEVERLAND",
64774
+ keyByReserveToken: true
64775
+ },
64776
+ layerbank: {
64777
+ merklProtocolId: "layerbank",
64778
+ lenderKey: "LAYERBANK_V3",
64779
+ keyByReserveToken: true
64780
+ },
64781
+ dolomite: { merklProtocolId: "dolomite", lenderKey: "DOLOMITE" },
64782
+ euler: { merklProtocolId: "euler", lenderKey: "EULER_V2" }
64783
+ };
64784
+ var RATE_RESOLVERS = {
64785
+ aave: resolveAaveOpp,
64786
+ neverland: resolveAaveV3ReserveToken,
64787
+ layerbank: resolveAaveV3ReserveToken,
64788
+ dolomite: resolveDolomiteAsset,
64789
+ euler: resolveEulerOpp
64790
+ };
64791
+ function resolveAaveOpp(opp) {
64792
+ const explorer = opp.explorerAddress?.toLowerCase();
64793
+ if (opp.type?.startsWith("AAVE_V4")) {
64794
+ const underlying = resolveUnderlyingFromOpportunity(opp);
64795
+ if (!explorer || !underlying) return void 0;
64796
+ return {
64797
+ asset: underlying,
64798
+ lender: `AAVE_V4_${explorer.slice(2).toUpperCase()}`,
64799
+ keyBy: "lender"
64800
+ };
64801
+ }
64802
+ return resolveAaveV3ReserveToken(opp);
64803
+ }
64804
+ function resolveEulerOpp(opp) {
64805
+ if (opp.type === "MULTILENDBORROW")
64806
+ return (opp.tokens ?? []).filter((t) => !t.symbol?.endsWith("-DEBT")).map((t) => ({ asset: t.address.toLowerCase() }));
64807
+ const vault = (opp.action === "BORROW" ? parseEulerVaultFromUrl(opp.depositUrl) : void 0) ?? opp.explorerAddress?.toLowerCase();
64808
+ return vault ? [{ asset: vault }] : [];
64809
+ }
64810
+ function aaveReserveOwner(chainId, reserveToken) {
64811
+ const t = reserveToken.toLowerCase();
64812
+ for (const [lender, chains] of Object.entries(aaveTokens() ?? {})) {
64813
+ for (const [underlying, row] of Object.entries(chains?.[chainId] ?? {})) {
64814
+ if (row?.aToken?.toLowerCase() === t || row?.vToken?.toLowerCase() === t)
64815
+ return { lender, underlying: underlying.toLowerCase() };
64816
+ }
64817
+ }
64818
+ return void 0;
64819
+ }
64820
+ var sideOf = (opp) => opp.action === "LEND" ? "deposit" : opp.action === "BORROW" ? "borrow" : void 0;
64821
+ function resolveMerklOpportunityMarkets(opp) {
64822
+ const chainId = String(opp.chainId);
64823
+ const protocol = (opp.protocol?.id ?? "").toLowerCase();
64824
+ const explorer = opp.explorerAddress?.toLowerCase();
64825
+ const side2 = sideOf(opp);
64826
+ if (protocol === "morpho") {
64827
+ const key5 = parseMorphoUniqueKey(opp.depositUrl);
64828
+ const lender = key5 ? `MORPHO_BLUE_${key5.slice(2).toUpperCase()}` : void 0;
64829
+ if (lender && explorer && /^MORPHO(COLLATERAL|SUPPLY|BORROW)$/.test(opp.type ?? ""))
64830
+ return [
64831
+ {
64832
+ chainId,
64833
+ lender,
64834
+ underlying: explorer,
64835
+ side: opp.type === "MORPHOBORROW" ? "borrow" : "deposit",
64836
+ marketUid: createMarketUid(chainId, lender, explorer)
64837
+ }
64838
+ ];
64839
+ return explorer ? [{ chainId, vault: explorer, side: side2 }] : [];
64840
+ }
64841
+ if (protocol === "fluid")
64842
+ return explorer ? [{ chainId, vault: explorer, side: side2 }] : [];
64843
+ const resolve = RATE_RESOLVERS[protocol];
64844
+ const config = RATE_CONFIGS[protocol];
64845
+ if (!resolve || !config)
64846
+ return explorer ? [{ chainId, vault: explorer, side: side2 }] : [];
64847
+ const raw = resolve(opp);
64848
+ const list = (Array.isArray(raw) ? raw : [raw]).filter(
64849
+ (r) => Boolean(r?.asset)
64850
+ );
64851
+ if (!list.length) return explorer ? [{ chainId, vault: explorer, side: side2 }] : [];
64852
+ return list.map((r) => {
64853
+ const keyBy = r.keyBy ?? (config.keyByReserveToken ? "reserveToken" : "lender");
64854
+ const s = r.bucket ?? side2;
64855
+ if (keyBy === "reserveToken") {
64856
+ const owner = aaveReserveOwner(chainId, r.asset);
64857
+ return {
64858
+ chainId,
64859
+ reserveToken: r.asset,
64860
+ side: s,
64861
+ ...owner ? {
64862
+ lender: owner.lender,
64863
+ underlying: owner.underlying,
64864
+ marketUid: createMarketUid(
64865
+ chainId,
64866
+ owner.lender,
64867
+ owner.underlying
64868
+ )
64869
+ } : {}
64870
+ };
64871
+ }
64872
+ const lender = r.lender ?? config.lenderKey;
64873
+ return {
64874
+ chainId,
64875
+ lender,
64876
+ underlying: r.asset,
64877
+ side: s,
64878
+ marketUid: createMarketUid(chainId, lender, r.asset)
64879
+ };
64880
+ });
64881
+ }
64882
+
64883
+ // src/yields/rewards/fluid.ts
64884
+ var MERKL_FLUID_ID = "fluid";
64885
+ var CACHE_TTL_MS10 = 5 * 6e4;
64886
+ var oppCache;
64887
+ var oppInflight;
64888
+ async function fluidMerklOpportunities() {
64889
+ if (oppCache && Date.now() - oppCache.at < CACHE_TTL_MS10) return oppCache.opps;
64890
+ if (oppInflight) return oppInflight;
64891
+ oppInflight = (async () => {
64892
+ try {
64893
+ const opps = await fetchMerklOpportunities(MERKL_FLUID_ID);
64894
+ oppCache = { at: Date.now(), opps };
64895
+ return opps;
64896
+ } finally {
64897
+ oppInflight = void 0;
64898
+ }
64899
+ })();
64900
+ return oppInflight;
64901
+ }
64902
+ function indexFluidVaults(byChain) {
64903
+ const out = {};
64904
+ for (const [chainId, vaults] of Object.entries(byChain)) {
64905
+ if (!vaults) continue;
64906
+ const m = {};
64907
+ for (const v of Object.values(vaults)) if (v.address) m[v.address] = v;
64908
+ out[chainId] = m;
64909
+ }
64910
+ return out;
64911
+ }
64912
+ function resolveFluidVaultRewards(opp, index) {
64913
+ const side2 = opp.type === "FLUIDVAULT_COLLATERAL" ? "deposit" : opp.type === "FLUIDVAULT_BORROW" ? "borrow" : void 0;
64914
+ if (!side2) return [];
64915
+ const chainId = String(opp.chainId);
64916
+ const vault = index[chainId]?.[opp.explorerAddress?.toLowerCase() ?? ""];
64917
+ if (!vault) return [];
64918
+ const legs = (side2 === "deposit" ? vault.supplyTokens : vault.borrowTokens) ?? [];
64919
+ const lender = `FLUID_${chainId}_${vault.vaultId}`;
64920
+ return legs.map((asset) => ({ asset, lender, bucket: side2 }));
64921
+ }
64922
+ var fluidMerklRewardFetcher = {
64923
+ label: "MERKL_FLUID",
64924
+ fetch: async () => {
64925
+ const opps = await fluidMerklOpportunities();
64926
+ const chains = [
64927
+ ...new Set(
64928
+ opps.filter((o) => o.type?.startsWith("FLUIDVAULT_")).map((o) => String(o.chainId)).filter((c) => FLUID_API_CHAINS.includes(c))
64929
+ )
64930
+ ];
64931
+ const apiByChain = {};
64932
+ await Promise.all(
64933
+ chains.map(async (c) => {
64934
+ apiByChain[c] = await fetchFluidApiData(c);
64935
+ })
64936
+ );
64937
+ const index = indexFluidVaults(apiByChain);
64938
+ const { byLender } = collectMerklRewards([opps], {
64939
+ merklProtocolId: MERKL_FLUID_ID,
64940
+ lenderKey: "FLUID",
64941
+ resolveAsset: (opp) => resolveFluidVaultRewards(opp, index)
64942
+ });
64943
+ return { byLender };
64944
+ }
64945
+ };
64946
+ async function fetchFluidFTokenMerklStreams(chainId, timeoutMs = 6e3) {
64947
+ const out = /* @__PURE__ */ new Map();
64948
+ let opps;
64949
+ let timer;
64950
+ try {
64951
+ opps = await Promise.race([
64952
+ fluidMerklOpportunities(),
64953
+ new Promise((_3, reject) => {
64954
+ timer = setTimeout(() => reject(new Error("timeout")), timeoutMs);
64955
+ })
64956
+ ]);
64957
+ } catch {
64958
+ return out;
64959
+ } finally {
64960
+ if (timer) clearTimeout(timer);
64961
+ }
64962
+ return fTokenStreamsFromOpportunities(opps, chainId);
64963
+ }
64964
+ function fTokenStreamsFromOpportunities(opps, chainId) {
64965
+ const out = /* @__PURE__ */ new Map();
64966
+ for (const opp of opps) {
64967
+ if (String(opp.chainId) !== chainId) continue;
64968
+ if (opp.type !== "ERC20LOGPROCESSOR" || opp.action !== "LEND") continue;
64969
+ if (!opp.apr || opp.apr <= 0) continue;
64970
+ const fToken = opp.explorerAddress?.toLowerCase();
64971
+ if (!fToken) continue;
64972
+ const entry2 = out.get(fToken) ?? { apr: 0, streams: [] };
64973
+ entry2.apr += opp.apr;
64974
+ entry2.streams.push(
64975
+ ...buildMerklStreams(
64976
+ opp,
64977
+ "deposit",
64978
+ opp.apr,
64979
+ merklSourceRef(opp, MERKL_FLUID_ID)
64980
+ )
64981
+ );
64982
+ out.set(fToken, entry2);
64983
+ }
64984
+ return out;
64985
+ }
64591
64986
  var DLEND_POOLS = [
64592
64987
  {
64593
64988
  chainId: Chain.ETHEREUM_MAINNET,
@@ -64926,6 +65321,528 @@ var dtrinityRebateRewardFetcher = {
64926
65321
  }
64927
65322
  };
64928
65323
  var SECONDS_PER_YEAR18 = 31536e3;
65324
+ var MAX_EPOCH_AGE_SECONDS = 7 * 86400;
65325
+ var EPOCH_LOOKBACK = 8;
65326
+ var FT_DECIMALS = 18;
65327
+ var LENDER2 = "FLYING_TULIP";
65328
+ var DEPLOYMENTS = {
65329
+ [Chain.ETHEREUM_MAINNET]: {
65330
+ positionsManager: "0xbe4050a73a7Fb384c65E885a15C33461A4B20055",
65331
+ ft: "0x5DD1A7A369e8273371d2DBf9d83356057088082c"
65332
+ },
65333
+ [Chain.SONIC_MAINNET]: {
65334
+ positionsManager: "0xbe4050a73a7Fb384c65E885a15C33461A4B20055",
65335
+ ft: "0x5DD1A7A369e8273371d2DBf9d83356057088082c"
65336
+ },
65337
+ [Chain.BNB_SMART_CHAIN_MAINNET]: {
65338
+ positionsManager: "0xB36d39C72d66153B7f32E1320BEe3280657353Bd",
65339
+ ft: "0x5DD1A7A369e8273371d2DBf9d83356057088082c"
65340
+ }
65341
+ };
65342
+ var LLAMA_CHAIN_SLUG = {
65343
+ [Chain.ETHEREUM_MAINNET]: "ethereum",
65344
+ [Chain.SONIC_MAINNET]: "sonic",
65345
+ [Chain.BNB_SMART_CHAIN_MAINNET]: "bsc"
65346
+ };
65347
+ var FT_API = "https://api.flyingtulip.com/mm/lend";
65348
+ var ABI3 = [
65349
+ {
65350
+ name: "astate",
65351
+ type: "function",
65352
+ stateMutability: "view",
65353
+ inputs: [{ type: "address" }],
65354
+ outputs: [
65355
+ { name: "borrowIndexWad", type: "uint256" },
65356
+ { name: "cash", type: "uint256" },
65357
+ { name: "borrows", type: "uint256" },
65358
+ { name: "totalSupplied", type: "uint256" },
65359
+ { name: "reserves", type: "uint256" },
65360
+ { name: "totalSuppliedTime", type: "uint256" },
65361
+ { name: "lastAccrual", type: "uint40" },
65362
+ { name: "epoch", type: "uint32" }
65363
+ ]
65364
+ },
65365
+ {
65366
+ name: "epochs",
65367
+ type: "function",
65368
+ stateMutability: "view",
65369
+ inputs: [{ type: "address" }, { type: "uint32" }],
65370
+ outputs: [
65371
+ { name: "t_end", type: "uint40" },
65372
+ { name: "S_end", type: "uint256" },
65373
+ { name: "rateRay", type: "uint256" },
65374
+ { name: "X_end", type: "uint256" },
65375
+ { name: "interest", type: "uint256" },
65376
+ { name: "supplyTime", type: "uint256" }
65377
+ ]
65378
+ }
65379
+ ];
65380
+ var FT_SOURCE = {
65381
+ id: "flying-tulip:ft-emission",
65382
+ label: "Flying Tulip FT supply emission",
65383
+ link: "https://flyingtulip.com",
65384
+ platform: "protocol"
65385
+ };
65386
+ function ftEmissionApr(params) {
65387
+ const {
65388
+ epochs,
65389
+ assetDecimals,
65390
+ assetPriceUsd,
65391
+ ftPriceUsd,
65392
+ nowSeconds: nowSeconds2,
65393
+ maxAgeSeconds = MAX_EPOCH_AGE_SECONDS
65394
+ } = params;
65395
+ if (!(assetPriceUsd > 0) || !(ftPriceUsd > 0)) return 0;
65396
+ let ft = 0n;
65397
+ let supplyTime = 0n;
65398
+ for (const e of epochs) {
65399
+ if (e.tEnd <= 0 || nowSeconds2 - e.tEnd > maxAgeSeconds) continue;
65400
+ if (e.supplyTime <= 0n) continue;
65401
+ ft += e.interest;
65402
+ supplyTime += e.supplyTime;
65403
+ }
65404
+ if (ft <= 0n || supplyTime <= 0n) return 0;
65405
+ const ftUsd = Number(ft) / 10 ** FT_DECIMALS * ftPriceUsd;
65406
+ const usdSeconds = Number(supplyTime) / 10 ** assetDecimals * assetPriceUsd;
65407
+ if (!(usdSeconds > 0)) return 0;
65408
+ return ftUsd / usdSeconds * SECONDS_PER_YEAR18 * 100;
65409
+ }
65410
+ async function rosterFor(chainId) {
65411
+ const fromMeta = flyingTulipAssetsFor(LENDER2, chainId)?.assets ?? [];
65412
+ if (fromMeta.length > 0)
65413
+ return fromMeta.map((a) => ({
65414
+ address: a.address,
65415
+ symbol: a.symbol,
65416
+ decimals: a.decimals
65417
+ }));
65418
+ const res = await fetch(`${FT_API}?chainId=${chainId}`, {
65419
+ headers: { accept: "application/json" },
65420
+ signal: AbortSignal.timeout(1e4)
65421
+ });
65422
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
65423
+ const body = await res.json();
65424
+ const chain = (body?.data?.chains ?? []).find(
65425
+ (c) => String(c?.chainId) === chainId
65426
+ );
65427
+ return (chain?.assets ?? []).filter((a) => a?.address && Number.isFinite(Number(a?.decimals))).map((a) => ({
65428
+ address: String(a.address),
65429
+ symbol: String(a.symbol ?? ""),
65430
+ decimals: Number(a.decimals)
65431
+ }));
65432
+ }
65433
+ async function fetchLlamaPrices(ids) {
65434
+ const out = {};
65435
+ const CHUNK = 60;
65436
+ for (let i = 0; i < ids.length; i += CHUNK) {
65437
+ const slice2 = ids.slice(i, i + CHUNK);
65438
+ try {
65439
+ const res = await fetch(
65440
+ `https://coins.llama.fi/prices/current/${slice2.join(",")}`,
65441
+ { signal: AbortSignal.timeout(1e4) }
65442
+ );
65443
+ if (!res.ok) continue;
65444
+ const json = await res.json();
65445
+ for (const [id, v] of Object.entries(json?.coins ?? {})) {
65446
+ if (typeof v?.price === "number") out[id.toLowerCase()] = v.price;
65447
+ }
65448
+ } catch (e) {
65449
+ console.error("[flying-tulip-ft] price fetch failed:", e);
65450
+ }
65451
+ }
65452
+ return out;
65453
+ }
65454
+ function emptyReward3() {
65455
+ return {
65456
+ distribution: "native",
65457
+ deposit: 0,
65458
+ borrow: 0,
65459
+ additionalDepositData: [],
65460
+ additionalBorrowData: []
65461
+ };
65462
+ }
65463
+ async function fetchForChain(chainId, nowSeconds2) {
65464
+ const cfg = flyingTulipConfigFor(LENDER2, chainId);
65465
+ const pm = cfg?.positionsManager || DEPLOYMENTS[chainId]?.positionsManager;
65466
+ const ftToken = (cfg?.ft || DEPLOYMENTS[chainId]?.ft || "").toLowerCase();
65467
+ const slug = LLAMA_CHAIN_SLUG[chainId];
65468
+ if (!pm || !ftToken || !slug) return {};
65469
+ const roster = await rosterFor(chainId);
65470
+ const assets = roster.filter((a) => a.address.toLowerCase() !== ftToken);
65471
+ if (!assets.length) return {};
65472
+ const states = await multicallRetryUniversal({
65473
+ chain: chainId,
65474
+ abi: ABI3,
65475
+ calls: assets.map((a) => ({
65476
+ address: pm,
65477
+ name: "astate",
65478
+ params: [a.address]
65479
+ })),
65480
+ allowFailure: true
65481
+ });
65482
+ const reads = [];
65483
+ assets.forEach((asset, i) => {
65484
+ const epoch = Number(states[i]?.[7] ?? 0);
65485
+ if (!(epoch > 0)) return;
65486
+ const ids = [];
65487
+ for (let id = epoch; id > 0 && ids.length < EPOCH_LOOKBACK; id--)
65488
+ ids.push(id);
65489
+ reads.push({ asset, ids });
65490
+ });
65491
+ if (!reads.length) return {};
65492
+ const epochResults = await multicallRetryUniversal({
65493
+ chain: chainId,
65494
+ abi: ABI3,
65495
+ calls: reads.flatMap(
65496
+ ({ asset, ids }) => ids.map((id) => ({
65497
+ address: pm,
65498
+ name: "epochs",
65499
+ params: [asset.address, id]
65500
+ }))
65501
+ ),
65502
+ allowFailure: true
65503
+ });
65504
+ const ftId = `${slug}:${ftToken}`;
65505
+ const prices = await fetchLlamaPrices([
65506
+ ftId,
65507
+ ...reads.map(({ asset }) => `${slug}:${asset.address.toLowerCase()}`)
65508
+ ]);
65509
+ const ftPriceUsd = prices[ftId] ?? 0;
65510
+ if (!(ftPriceUsd > 0)) {
65511
+ console.warn(`[flying-tulip-ft] no FT price on chain ${chainId}`);
65512
+ return {};
65513
+ }
65514
+ const result = {};
65515
+ let offset = 0;
65516
+ for (const { asset, ids } of reads) {
65517
+ const epochs = ids.map((_3, k) => epochResults[offset + k]).filter((r) => Array.isArray(r)).map((r) => ({
65518
+ tEnd: Number(r[0] ?? 0),
65519
+ interest: BigInt(r[4] ?? 0),
65520
+ supplyTime: BigInt(r[5] ?? 0)
65521
+ }));
65522
+ offset += ids.length;
65523
+ const assetKey2 = asset.address.toLowerCase();
65524
+ const apr = ftEmissionApr({
65525
+ epochs,
65526
+ assetDecimals: asset.decimals,
65527
+ assetPriceUsd: prices[`${slug}:${assetKey2}`] ?? 0,
65528
+ ftPriceUsd,
65529
+ nowSeconds: nowSeconds2
65530
+ });
65531
+ if (!(apr > 0)) continue;
65532
+ const latest = epochs.reduce((m, e) => Math.max(m, e.tEnd), 0);
65533
+ const inWindow = epochs.filter(
65534
+ (e) => e.tEnd > 0 && nowSeconds2 - e.tEnd <= MAX_EPOCH_AGE_SECONDS
65535
+ );
65536
+ const windowStart = inWindow.reduce(
65537
+ (m, e) => Math.min(m, e.tEnd),
65538
+ Number.MAX_SAFE_INTEGER
65539
+ );
65540
+ const ftPaid = inWindow.reduce((s, e) => s + e.interest, 0n);
65541
+ const windowDays = inWindow.length > 1 ? (latest - windowStart) / 86400 : void 0;
65542
+ if (!result[chainId]) result[chainId] = {};
65543
+ if (!result[chainId][LENDER2]) result[chainId][LENDER2] = {};
65544
+ const entry2 = result[chainId][LENDER2][assetKey2] = emptyReward3();
65545
+ entry2.deposit = apr;
65546
+ entry2.link = FT_SOURCE.link;
65547
+ entry2.additionalDepositData.push({
65548
+ tokenAddress: ftToken,
65549
+ distributionType: "flying-tulip-epoch",
65550
+ epochs: inWindow.length,
65551
+ latestEpochEnd: latest
65552
+ });
65553
+ entry2.streams = [
65554
+ {
65555
+ side: "deposit",
65556
+ apr,
65557
+ kind: "token",
65558
+ token: {
65559
+ address: ftToken,
65560
+ chainId,
65561
+ symbol: "FT",
65562
+ decimals: FT_DECIMALS,
65563
+ priceUsd: ftPriceUsd
65564
+ },
65565
+ source: {
65566
+ ...FT_SOURCE,
65567
+ refs: {
65568
+ positionsManager: pm.toLowerCase(),
65569
+ asset: assetKey2,
65570
+ latestEpochEnd: String(latest)
65571
+ }
65572
+ },
65573
+ // Accrues per epoch on the position; claimed from the
65574
+ // PositionsManager, no merkle proof.
65575
+ claim: "accrual",
65576
+ // Daily payout averaged over the settled window (an epoch is not a day).
65577
+ dailyRewardsUsd: windowDays && windowDays > 0 ? Number(ftPaid) / 10 ** FT_DECIMALS * ftPriceUsd / // n settled epochs span (n − 1) gaps between their END times;
65578
+ // scale the paid total to that span.
65579
+ (windowDays * (inWindow.length / (inWindow.length - 1))) : void 0
65580
+ }
65581
+ ];
65582
+ }
65583
+ return result;
65584
+ }
65585
+ var flyingTulipFtRewardFetcher = {
65586
+ label: "FLYING_TULIP_FT",
65587
+ fetch: async () => {
65588
+ const nowSeconds2 = Math.floor(Date.now() / 1e3);
65589
+ const results = await Promise.all(
65590
+ Object.keys(DEPLOYMENTS).map(async (chainId) => {
65591
+ try {
65592
+ return await fetchForChain(chainId, nowSeconds2);
65593
+ } catch (e) {
65594
+ console.error(
65595
+ `[flying-tulip-ft] emission read failed on chain ${chainId}:`,
65596
+ e
65597
+ );
65598
+ return {};
65599
+ }
65600
+ })
65601
+ );
65602
+ const merged = {};
65603
+ for (const r of results) Object.assign(merged, r);
65604
+ return { byLender: merged };
65605
+ }
65606
+ };
65607
+ var LISTA_API = "https://api.lista.org";
65608
+ var PAGE_SIZE2 = 50;
65609
+ var MAX_PAGES2 = 20;
65610
+ var MIN_BASE_USD = 1e4;
65611
+ var MAX_UNVERIFIED_APR = 100;
65612
+ var MAX_BORROWABLE_UTILIZATION = 0.999;
65613
+ var LENDER3 = "LISTA_DAO";
65614
+ var LISTA_API_CHAIN = {
65615
+ [Chain.BNB_SMART_CHAIN_MAINNET]: "bsc",
65616
+ [Chain.ETHEREUM_MAINNET]: "ethereum"
65617
+ };
65618
+ var LISTA_CLAIM_CHAIN = Chain.BNB_SMART_CHAIN_MAINNET;
65619
+ var MOOLAH_FALLBACK = {
65620
+ [Chain.BNB_SMART_CHAIN_MAINNET]: "0x8F73b65B4caAf64FBA2aF91cC5D4a2A1318E5D8C",
65621
+ [Chain.ETHEREUM_MAINNET]: "0xf820fB4680712CD7263a0D3D024D5b5aEA82Fd70"
65622
+ };
65623
+ var LISTA_SOURCE = {
65624
+ id: "lista:emission",
65625
+ label: "Lista emission",
65626
+ link: "https://lista.org/lending",
65627
+ platform: "protocol"
65628
+ };
65629
+ var num5 = (v) => {
65630
+ const n = Number(v);
65631
+ return Number.isFinite(n) ? n : 0;
65632
+ };
65633
+ async function getJson6(path, fetchImpl) {
65634
+ const res = await fetchImpl(`${LISTA_API}${path}`, {
65635
+ headers: { accept: "application/json" },
65636
+ signal: AbortSignal.timeout(8e3)
65637
+ });
65638
+ if (!res.ok) throw new Error(`Lista API ${path}: HTTP ${res.status}`);
65639
+ const body = await res.json();
65640
+ if (body?.code !== "000000000")
65641
+ throw new Error(`Lista API ${path}: ${body?.msg ?? "bad response"}`);
65642
+ return body.data;
65643
+ }
65644
+ async function getPaged(path, fetchImpl) {
65645
+ const out = [];
65646
+ for (let page = 1; page <= MAX_PAGES2; page++) {
65647
+ const sep = path.includes("?") ? "&" : "?";
65648
+ const data = await getJson6(
65649
+ `${path}${sep}page=${page}&pageSize=${PAGE_SIZE2}`,
65650
+ fetchImpl
65651
+ );
65652
+ const list = Array.isArray(data?.list) ? data.list : [];
65653
+ out.push(...list);
65654
+ if (list.length < PAGE_SIZE2 || out.length >= num5(data?.total)) break;
65655
+ }
65656
+ return out;
65657
+ }
65658
+ async function fetchListaRewardTokens(fetchImpl = fetch) {
65659
+ const data = await getJson6("/api/moolah/emission/rewardTokens", fetchImpl);
65660
+ const out = {};
65661
+ for (const t of Array.isArray(data) ? data : [])
65662
+ if (t?.symbol && t?.token)
65663
+ out[String(t.symbol).toUpperCase()] = String(t.token).toLowerCase();
65664
+ return out;
65665
+ }
65666
+ function marketLegs(raw) {
65667
+ if (!Array.isArray(raw)) return [];
65668
+ return raw.map((d) => ({
65669
+ token: d?.token ? String(d.token).toLowerCase() : void 0,
65670
+ symbol: String(d?.symbol ?? ""),
65671
+ apr: num5(d?.apy) * 100,
65672
+ weeklyTotal: d?.total != null ? num5(d.total) : void 0
65673
+ })).filter((l) => l.apr > 0);
65674
+ }
65675
+ function vaultLegs(raw, tokens) {
65676
+ if (!raw || typeof raw !== "object") return [];
65677
+ return Object.entries(raw).map(([symbol, d]) => ({
65678
+ token: tokens[symbol.toUpperCase()],
65679
+ symbol,
65680
+ apr: num5(d?.apy) * 100,
65681
+ weeklyTotal: d?.total != null ? num5(d.total) : void 0
65682
+ })).filter((l) => l.apr > 0);
65683
+ }
65684
+ async function fetchListaVaultEmissions(chainId, fetchImpl = fetch) {
65685
+ const slug = LISTA_API_CHAIN[chainId];
65686
+ if (!slug) return {};
65687
+ const [vaults, tokens] = await Promise.all([
65688
+ getPaged(`/api/moolah/vault/list?chain=${slug}`, fetchImpl),
65689
+ fetchListaRewardTokens(fetchImpl).catch(
65690
+ () => ({})
65691
+ )
65692
+ ]);
65693
+ const out = {};
65694
+ for (const v of vaults) {
65695
+ if (!v?.address || num5(v.emissionEnabled) !== 1) continue;
65696
+ const depositsUsd = num5(v.depositsUsd);
65697
+ if (depositsUsd < MIN_BASE_USD) continue;
65698
+ const legs = vaultLegs(v.emissionDetail, tokens);
65699
+ if (!legs.length) continue;
65700
+ const vault = String(v.address).toLowerCase();
65701
+ out[vault] = { vault, name: String(v.name ?? ""), depositsUsd, legs };
65702
+ }
65703
+ return out;
65704
+ }
65705
+ async function fetchListaMarketEmissions(chainId, fetchImpl = fetch) {
65706
+ const slug = LISTA_API_CHAIN[chainId];
65707
+ if (!slug) return [];
65708
+ const markets = await getPaged(
65709
+ `/api/moolah/borrow/markets?chain=${slug}`,
65710
+ fetchImpl
65711
+ );
65712
+ const out = [];
65713
+ for (const m of markets) {
65714
+ if (!m?.id) continue;
65715
+ const supply = marketLegs(m.emissionDetail);
65716
+ const borrow = marketLegs(m.borrowEmissionDetail);
65717
+ if (!supply.length && !borrow.length) continue;
65718
+ const liquidity = num5(m.liquidity);
65719
+ const price2 = liquidity > 0 ? num5(m.liquidityUsd) / liquidity : void 0;
65720
+ out.push({
65721
+ marketId: String(m.id).toLowerCase(),
65722
+ loanSymbol: String(m.loan ?? ""),
65723
+ supplyUsd: price2 != null ? (liquidity + num5(m.totalBorrowAsset)) * price2 : void 0,
65724
+ borrowUsd: price2 != null ? num5(m.totalBorrowAsset) * price2 : void 0,
65725
+ utilization: num5(m.utilization),
65726
+ supply,
65727
+ borrow
65728
+ });
65729
+ }
65730
+ return out;
65731
+ }
65732
+ function isMeaningfulEmission(apr, baseUsd) {
65733
+ if (!(apr > 0)) return false;
65734
+ if (baseUsd != null) return baseUsd >= MIN_BASE_USD;
65735
+ return apr <= MAX_UNVERIFIED_APR;
65736
+ }
65737
+ async function fetchLlamaBscPrices(tokens, fetchImpl = fetch) {
65738
+ const ids = [...new Set(tokens.filter(Boolean))].map((t) => `bsc:${t}`);
65739
+ if (!ids.length) return {};
65740
+ try {
65741
+ const res = await fetchImpl(
65742
+ `https://coins.llama.fi/prices/current/${ids.join(",")}`,
65743
+ { signal: AbortSignal.timeout(8e3) }
65744
+ );
65745
+ if (!res.ok) return {};
65746
+ const json = await res.json();
65747
+ const out = {};
65748
+ for (const [id, v] of Object.entries(json?.coins ?? {}))
65749
+ if (typeof v?.price === "number") out[id.slice(4).toLowerCase()] = v.price;
65750
+ return out;
65751
+ } catch {
65752
+ return {};
65753
+ }
65754
+ }
65755
+ function listaEmissionStreams(side2, legs, prices, refs) {
65756
+ return legs.map((l) => {
65757
+ const price2 = l.token ? prices[l.token] : void 0;
65758
+ return {
65759
+ side: side2,
65760
+ apr: l.apr,
65761
+ kind: "token",
65762
+ token: l.token ? {
65763
+ address: l.token,
65764
+ chainId: LISTA_CLAIM_CHAIN,
65765
+ symbol: l.symbol,
65766
+ decimals: 18,
65767
+ priceUsd: price2
65768
+ } : void 0,
65769
+ source: { ...LISTA_SOURCE, refs },
65770
+ // A Merkle distributor on BNB, claimed with a Lista-issued proof.
65771
+ claim: "manual",
65772
+ dailyRewardsUsd: price2 != null && l.weeklyTotal != null ? l.weeklyTotal * price2 / 7 : void 0
65773
+ };
65774
+ });
65775
+ }
65776
+ function emptyReward4() {
65777
+ return {
65778
+ distribution: "native",
65779
+ deposit: 0,
65780
+ borrow: 0,
65781
+ additionalDepositData: [],
65782
+ additionalBorrowData: []
65783
+ };
65784
+ }
65785
+ async function fetchMarketRewardsForChain(chainId) {
65786
+ const markets = (await fetchListaMarketEmissions(chainId)).map((m) => ({
65787
+ ...m,
65788
+ supply: m.supply.filter((l) => isMeaningfulEmission(l.apr, m.supplyUsd)),
65789
+ borrow: m.utilization >= MAX_BORROWABLE_UTILIZATION ? [] : m.borrow.filter((l) => isMeaningfulEmission(l.apr, m.borrowUsd))
65790
+ }));
65791
+ const paying = markets.filter((m) => m.supply.length || m.borrow.length);
65792
+ const moolah = morphoPools()?.[LENDER3]?.[chainId] ?? MOOLAH_FALLBACK[chainId];
65793
+ if (!paying.length || !moolah) return {};
65794
+ const params = await multicallRetryUniversal({
65795
+ chain: chainId,
65796
+ abi: MorphoBlueAbi,
65797
+ calls: paying.map((m) => ({
65798
+ address: moolah,
65799
+ name: "idToMarketParams",
65800
+ params: [m.marketId]
65801
+ })),
65802
+ allowFailure: true
65803
+ });
65804
+ const prices = await fetchLlamaBscPrices(
65805
+ paying.flatMap((m) => [...m.supply, ...m.borrow].map((l) => l.token))
65806
+ );
65807
+ const result = { [chainId]: {} };
65808
+ paying.forEach((m, i) => {
65809
+ const loanToken = params[i]?.[0] ?? params[i]?.loanToken;
65810
+ if (!loanToken || /^0x0{40}$/i.test(loanToken)) return;
65811
+ const lender = `${LENDER3}_${m.marketId.slice(2).toUpperCase()}`;
65812
+ const refs = { marketId: m.marketId };
65813
+ const deposit = listaEmissionStreams("deposit", m.supply, prices, refs);
65814
+ const borrow = listaEmissionStreams("borrow", m.borrow, prices, refs);
65815
+ const entry2 = emptyReward4();
65816
+ entry2.deposit = deposit.reduce((s, x) => s + x.apr, 0);
65817
+ entry2.borrow = borrow.reduce((s, x) => s + x.apr, 0);
65818
+ entry2.link = LISTA_SOURCE.link;
65819
+ entry2.additionalDepositData = m.supply;
65820
+ entry2.additionalBorrowData = m.borrow;
65821
+ entry2.streams = [...deposit, ...borrow];
65822
+ result[chainId][lender] = { [loanToken.toLowerCase()]: entry2 };
65823
+ });
65824
+ return result;
65825
+ }
65826
+ var listaEmissionRewardFetcher = {
65827
+ label: "LISTA_EMISSION",
65828
+ fetch: async () => {
65829
+ const results = await Promise.all(
65830
+ Object.keys(LISTA_API_CHAIN).map(
65831
+ (chainId) => fetchMarketRewardsForChain(chainId).catch((e) => {
65832
+ console.error(
65833
+ `[lista-emission] market read failed on chain ${chainId}:`,
65834
+ e
65835
+ );
65836
+ return {};
65837
+ })
65838
+ )
65839
+ );
65840
+ const merged = {};
65841
+ for (const r of results) Object.assign(merged, r);
65842
+ return { byLender: merged };
65843
+ }
65844
+ };
65845
+ var SECONDS_PER_YEAR19 = 31536e3;
64929
65846
  var WAD17 = 10n ** 18n;
64930
65847
  var ZERO6 = "0x0000000000000000000000000000000000000000";
64931
65848
  var UNBOOSTED_FACTOR = 0.4;
@@ -65033,7 +65950,7 @@ function crvGaugeApr(params) {
65033
65950
  return 0;
65034
65951
  }
65035
65952
  if (!(crvPriceUsd > 0) || !(assetPriceUsd > 0)) return 0;
65036
- const crvPerYear = scale2(inflationRate, 18) * scale2(relativeWeight, 18) * SECONDS_PER_YEAR18;
65953
+ const crvPerYear = scale2(inflationRate, 18) * scale2(relativeWeight, 18) * SECONDS_PER_YEAR19;
65037
65954
  const stakedUsd = scale2(workingSupply, 18) * scale2(pricePerShare, 18) * assetPriceUsd;
65038
65955
  if (!(stakedUsd > 0)) return 0;
65039
65956
  return crvPerYear * crvPriceUsd / stakedUsd * 100 * UNBOOSTED_FACTOR;
@@ -65052,7 +65969,7 @@ function extraRewardApr(params) {
65052
65969
  if (nowSeconds2 >= Number(periodFinish)) return 0;
65053
65970
  if (rate <= 0n || totalSupply <= 0n) return 0;
65054
65971
  if (!(rewardPriceUsd > 0) || !(assetPriceUsd > 0)) return 0;
65055
- const rewardPerYearUsd = scale2(rate, rewardDecimals) * SECONDS_PER_YEAR18 * rewardPriceUsd;
65972
+ const rewardPerYearUsd = scale2(rate, rewardDecimals) * SECONDS_PER_YEAR19 * rewardPriceUsd;
65056
65973
  const stakedUsd = scale2(totalSupply, 18) * scale2(pricePerShare, 18) * assetPriceUsd;
65057
65974
  if (!(stakedUsd > 0)) return 0;
65058
65975
  return rewardPerYearUsd / stakedUsd * 100;
@@ -65085,7 +66002,7 @@ function decodeRewardData(data) {
65085
66002
  if (periodFinish > MAX_PLAUSIBLE_TIMESTAMP) return null;
65086
66003
  return { periodFinish, rate };
65087
66004
  }
65088
- var LLAMA_CHAIN_SLUG = {
66005
+ var LLAMA_CHAIN_SLUG2 = {
65089
66006
  [Chain.ETHEREUM_MAINNET]: "ethereum",
65090
66007
  [Chain.OP_MAINNET]: "optimism",
65091
66008
  [Chain.ARBITRUM_ONE]: "arbitrum"
@@ -65094,7 +66011,7 @@ async function fetchPrices(keys) {
65094
66011
  const ids = Array.from(
65095
66012
  new Set(
65096
66013
  keys.map(({ chainId, address }) => {
65097
- const slug = LLAMA_CHAIN_SLUG[chainId];
66014
+ const slug = LLAMA_CHAIN_SLUG2[chainId];
65098
66015
  return slug ? `${slug}:${address.toLowerCase()}` : null;
65099
66016
  }).filter((x) => !!x)
65100
66017
  )
@@ -65120,8 +66037,8 @@ async function fetchPrices(keys) {
65120
66037
  }
65121
66038
  return out;
65122
66039
  }
65123
- var priceOf = (prices, chainId, address) => prices[`${LLAMA_CHAIN_SLUG[chainId]}:${address.toLowerCase()}`] ?? 0;
65124
- function rosterFor(chainId) {
66040
+ var priceOf = (prices, chainId, address) => prices[`${LLAMA_CHAIN_SLUG2[chainId]}:${address.toLowerCase()}`] ?? 0;
66041
+ function rosterFor2(chainId) {
65125
66042
  const markets = llamaLendChainData(Lender.LLAMALEND, chainId)?.markets ?? [];
65126
66043
  return markets.filter((m) => m.gauge && m.gauge !== ZERO6).map((m) => ({
65127
66044
  controller: m.controller,
@@ -65132,8 +66049,8 @@ function rosterFor(chainId) {
65132
66049
  }));
65133
66050
  }
65134
66051
  var lenderKeyFor = (controller) => `${Lender.LLAMALEND}_${controller.replace(/^0x/i, "").toUpperCase()}`;
65135
- async function fetchForChain(chainId, nowSeconds2) {
65136
- const markets = rosterFor(chainId);
66052
+ async function fetchForChain2(chainId, nowSeconds2) {
66053
+ const markets = rosterFor2(chainId);
65137
66054
  if (markets.length === 0) return {};
65138
66055
  const isL1 = L1_CHAINS.has(chainId);
65139
66056
  const week = BigInt(Math.floor(nowSeconds2 / 604800));
@@ -65160,7 +66077,7 @@ async function fetchForChain(chainId, nowSeconds2) {
65160
66077
  abi: GAUGE_ABI,
65161
66078
  allowFailure: true
65162
66079
  });
65163
- const big31 = (v) => {
66080
+ const big32 = (v) => {
65164
66081
  try {
65165
66082
  if (typeof v === "bigint") return v;
65166
66083
  if (typeof v === "string" && v !== "0x") return BigInt(v);
@@ -65174,15 +66091,15 @@ async function fetchForChain(chainId, nowSeconds2) {
65174
66091
  const b = i * STRIDE;
65175
66092
  return {
65176
66093
  market: m,
65177
- inflationRate: big31(r1[b]),
65178
- workingSupply: big31(r1[b + 1]),
65179
- totalSupply: big31(r1[b + 2]),
66094
+ inflationRate: big32(r1[b]),
66095
+ workingSupply: big32(r1[b + 1]),
66096
+ totalSupply: big32(r1[b + 2]),
65180
66097
  isKilled: r1[b + 3] === true,
65181
- rewardCount: Number(big31(r1[b + 4])),
65182
- pricePerShare: big31(r1[b + 5]),
66098
+ rewardCount: Number(big32(r1[b + 4])),
66099
+ pricePerShare: big32(r1[b + 5]),
65183
66100
  // Off L1 the child gauge's own rate is already market-scoped, so the
65184
66101
  // weight is the identity.
65185
- relativeWeight: isL1 ? big31(r1[b + 6]) : WAD17
66102
+ relativeWeight: isL1 ? big32(r1[b + 6]) : WAD17
65186
66103
  };
65187
66104
  });
65188
66105
  const tokenCalls = state.flatMap(
@@ -65275,7 +66192,7 @@ async function fetchForChain(chainId, nowSeconds2) {
65275
66192
  const decoded = decodeRewardData(data);
65276
66193
  if (!decoded) continue;
65277
66194
  const { periodFinish, rate } = decoded;
65278
- const decimals = typeof decRaw === "number" ? decRaw : Number(big31(decRaw) || 18n);
66195
+ const decimals = typeof decRaw === "number" ? decRaw : Number(big32(decRaw) || 18n);
65279
66196
  const rewardPrice = priceOf(prices, chainId, token);
65280
66197
  const apr = extraRewardApr({
65281
66198
  rate,
@@ -65345,7 +66262,7 @@ var llamaLendGaugeRewardFetcher = {
65345
66262
  const results = await Promise.all(
65346
66263
  GAUGE_CHAINS.map(async (chainId) => {
65347
66264
  try {
65348
- return await fetchForChain(chainId, nowSeconds2);
66265
+ return await fetchForChain2(chainId, nowSeconds2);
65349
66266
  } catch (e) {
65350
66267
  console.error(`[llamalend-gauge] read failed on chain ${chainId}:`, e);
65351
66268
  return {};
@@ -65377,8 +66294,14 @@ var rewardFetchers = [
65377
66294
  aaveMerklRewardFetcher,
65378
66295
  eulerMerklRewardFetcher,
65379
66296
  morphoCollateralMerklRewardFetcher,
66297
+ neverlandMerklRewardFetcher,
66298
+ layerBankMerklRewardFetcher,
66299
+ dolomiteMerklRewardFetcher,
66300
+ fluidMerklRewardFetcher,
65380
66301
  dtrinityRebateRewardFetcher,
65381
- llamaLendGaugeRewardFetcher
66302
+ llamaLendGaugeRewardFetcher,
66303
+ flyingTulipFtRewardFetcher,
66304
+ listaEmissionRewardFetcher
65382
66305
  ];
65383
66306
  function mergeReserveTokenRewards(target, source) {
65384
66307
  for (const [chainId, byToken] of Object.entries(source)) {
@@ -65401,6 +66324,929 @@ async function fetchLenderRewards() {
65401
66324
  return { byLender, byReserveToken };
65402
66325
  }
65403
66326
 
66327
+ // src/yields/rewards/user/prices.ts
66328
+ var LLAMA_SLUG = {
66329
+ "1": "ethereum",
66330
+ "10": "optimism",
66331
+ "56": "bsc",
66332
+ "100": "xdai",
66333
+ "137": "polygon",
66334
+ "143": "monad",
66335
+ "146": "sonic",
66336
+ "252": "fraxtal",
66337
+ "1329": "sei",
66338
+ "5000": "mantle",
66339
+ "8453": "base",
66340
+ "9745": "plasma",
66341
+ "42161": "arbitrum",
66342
+ "43114": "avax",
66343
+ "59144": "linea",
66344
+ "534352": "scroll"
66345
+ };
66346
+ async function fetchRewardTokenPrices(keys, fetchImpl = fetch) {
66347
+ const byId = /* @__PURE__ */ new Map();
66348
+ for (const { chainId, address } of keys) {
66349
+ const slug = LLAMA_SLUG[chainId];
66350
+ if (slug)
66351
+ byId.set(
66352
+ `${slug}:${address.toLowerCase()}`,
66353
+ `${chainId}:${address.toLowerCase()}`
66354
+ );
66355
+ }
66356
+ const ids = [...byId.keys()];
66357
+ const out = {};
66358
+ for (let i = 0; i < ids.length; i += 60) {
66359
+ const slice2 = ids.slice(i, i + 60);
66360
+ try {
66361
+ const res = await fetchImpl(
66362
+ `https://coins.llama.fi/prices/current/${slice2.join(",")}`,
66363
+ { signal: AbortSignal.timeout(8e3) }
66364
+ );
66365
+ if (!res.ok) continue;
66366
+ const json = await res.json();
66367
+ for (const [id, v] of Object.entries(json?.coins ?? {})) {
66368
+ const key5 = byId.get(id.toLowerCase());
66369
+ if (key5 && typeof v?.price === "number") out[key5] = v.price;
66370
+ }
66371
+ } catch {
66372
+ }
66373
+ }
66374
+ return out;
66375
+ }
66376
+ var toUsd = (raw, decimals, price2) => price2 != null && decimals != null ? Number(raw) / 10 ** decimals * price2 : void 0;
66377
+
66378
+ // src/yields/rewards/user/aaveIncentives.ts
66379
+ var ZERO7 = "0x0000000000000000000000000000000000000000";
66380
+ var ABI4 = [
66381
+ {
66382
+ name: "getIncentivesController",
66383
+ type: "function",
66384
+ stateMutability: "view",
66385
+ inputs: [],
66386
+ outputs: [{ type: "address" }]
66387
+ },
66388
+ {
66389
+ name: "balanceOf",
66390
+ type: "function",
66391
+ stateMutability: "view",
66392
+ inputs: [{ type: "address" }],
66393
+ outputs: [{ type: "uint256" }]
66394
+ },
66395
+ {
66396
+ name: "getAllUserRewards",
66397
+ type: "function",
66398
+ stateMutability: "view",
66399
+ inputs: [{ type: "address[]" }, { type: "address" }],
66400
+ outputs: [{ type: "address[]" }, { type: "uint256[]" }]
66401
+ },
66402
+ {
66403
+ name: "getUserRewards",
66404
+ type: "function",
66405
+ stateMutability: "view",
66406
+ inputs: [{ type: "address[]" }, { type: "address" }, { type: "address" }],
66407
+ outputs: [{ type: "uint256" }]
66408
+ },
66409
+ {
66410
+ name: "decimals",
66411
+ type: "function",
66412
+ stateMutability: "view",
66413
+ inputs: [],
66414
+ outputs: [{ type: "uint8" }]
66415
+ },
66416
+ {
66417
+ name: "symbol",
66418
+ type: "function",
66419
+ stateMutability: "view",
66420
+ inputs: [],
66421
+ outputs: [{ type: "string" }]
66422
+ }
66423
+ ];
66424
+ function balanceTokensFor(chainId) {
66425
+ const out = [];
66426
+ for (const [lender, chains] of Object.entries(aaveTokens() ?? {})) {
66427
+ for (const [underlying, t] of Object.entries(chains?.[chainId] ?? {})) {
66428
+ const u = underlying.toLowerCase();
66429
+ if (t?.aToken && t.aToken !== ZERO7)
66430
+ out.push({
66431
+ token: t.aToken.toLowerCase(),
66432
+ lender,
66433
+ underlying: u,
66434
+ side: "deposit"
66435
+ });
66436
+ if (t?.vToken && t.vToken !== ZERO7)
66437
+ out.push({
66438
+ token: t.vToken.toLowerCase(),
66439
+ lender,
66440
+ underlying: u,
66441
+ side: "borrow"
66442
+ });
66443
+ }
66444
+ }
66445
+ return out;
66446
+ }
66447
+ async function fetchAaveIncentivesUserRewards(account, chainId, opts = {}) {
66448
+ const tokens = balanceTokensFor(chainId);
66449
+ if (!tokens.length) return { rewards: [], errors: [] };
66450
+ const mc = (calls) => multicallRetryUniversal({
66451
+ chain: chainId,
66452
+ abi: ABI4,
66453
+ calls,
66454
+ allowFailure: true,
66455
+ overrides: opts.overrides
66456
+ });
66457
+ const r1 = await mc(
66458
+ tokens.flatMap((t) => [
66459
+ { address: t.token, name: "getIncentivesController", params: [] },
66460
+ { address: t.token, name: "balanceOf", params: [account] }
66461
+ ])
66462
+ );
66463
+ const byController = /* @__PURE__ */ new Map();
66464
+ tokens.forEach((t, i) => {
66465
+ const ctrl = String(r1[2 * i] ?? "").toLowerCase();
66466
+ if (!/^0x[0-9a-f]{40}$/.test(ctrl) || ctrl === ZERO7) return;
66467
+ const balance = typeof r1[2 * i + 1] === "bigint" ? r1[2 * i + 1] : 0n;
66468
+ const list = byController.get(ctrl) ?? [];
66469
+ list.push({ ...t, balance });
66470
+ byController.set(ctrl, list);
66471
+ });
66472
+ if (!byController.size) return { rewards: [], errors: [] };
66473
+ const controllers = [...byController.keys()];
66474
+ const r2 = await mc(
66475
+ controllers.map((c) => ({
66476
+ address: c,
66477
+ name: "getAllUserRewards",
66478
+ params: [byController.get(c).map((t) => t.token), account]
66479
+ }))
66480
+ );
66481
+ const owed = [];
66482
+ controllers.forEach((c, i) => {
66483
+ const res = r2[i];
66484
+ if (!Array.isArray(res) || !Array.isArray(res[0])) return;
66485
+ const [rewardsList, amounts] = res;
66486
+ rewardsList.forEach((reward, k) => {
66487
+ const amount5 = amounts?.[k] ?? 0n;
66488
+ if (amount5 > 0n)
66489
+ owed.push({ controller: c, reward: reward.toLowerCase(), amount: amount5 });
66490
+ });
66491
+ });
66492
+ if (!owed.length) return { rewards: [], errors: [] };
66493
+ const held = owed.flatMap(
66494
+ (o) => byController.get(o.controller).filter((t) => t.balance > 0n).map((t) => ({ o, t }))
66495
+ );
66496
+ const rewardTokens = [...new Set(owed.map((o) => o.reward))];
66497
+ const r3 = await mc([
66498
+ ...held.map(({ o, t }) => ({
66499
+ address: o.controller,
66500
+ name: "getUserRewards",
66501
+ params: [[t.token], account, o.reward]
66502
+ })),
66503
+ ...rewardTokens.flatMap((r) => [
66504
+ { address: r, name: "decimals", params: [] },
66505
+ { address: r, name: "symbol", params: [] }
66506
+ ])
66507
+ ]);
66508
+ const meta = /* @__PURE__ */ new Map();
66509
+ rewardTokens.forEach((r, i) => {
66510
+ const d = r3[held.length + 2 * i];
66511
+ const s = r3[held.length + 2 * i + 1];
66512
+ meta.set(r, {
66513
+ decimals: d == null ? void 0 : Number(d),
66514
+ symbol: typeof s === "string" ? s : void 0
66515
+ });
66516
+ });
66517
+ const prices = await fetchRewardTokenPrices(
66518
+ rewardTokens.map((address) => ({ chainId, address })),
66519
+ opts.fetchImpl
66520
+ );
66521
+ const rewards = owed.map((o) => {
66522
+ const breakdowns = [];
66523
+ let attributed = 0n;
66524
+ held.forEach(({ o: ho, t }, i) => {
66525
+ if (ho !== o) return;
66526
+ const amount5 = typeof r3[i] === "bigint" ? r3[i] : 0n;
66527
+ if (amount5 <= 0n) return;
66528
+ attributed += amount5;
66529
+ breakdowns.push({
66530
+ amount: amount5.toString(),
66531
+ claimable: amount5.toString(),
66532
+ market: {
66533
+ chainId,
66534
+ lender: t.lender,
66535
+ underlying: t.underlying,
66536
+ reserveToken: t.token,
66537
+ side: t.side,
66538
+ marketUid: createMarketUid(chainId, t.lender, t.underlying)
66539
+ }
66540
+ });
66541
+ });
66542
+ const residue = attributed < o.amount;
66543
+ const claimAssets2 = residue ? byController.get(o.controller).map((t) => t.token) : breakdowns.map((b) => b.market.reserveToken);
66544
+ const m = meta.get(o.reward) ?? {};
66545
+ const price2 = prices[`${chainId}:${o.reward}`];
66546
+ return {
66547
+ chainId,
66548
+ source: "aave-incentives",
66549
+ sourceId: "aave:rewards-controller",
66550
+ token: { address: o.reward, ...m, priceUsd: price2 },
66551
+ claimable: o.amount.toString(),
66552
+ pending: "0",
66553
+ claimableUsd: toUsd(o.amount, m.decimals, price2),
66554
+ breakdowns,
66555
+ claim: {
66556
+ kind: "aave-incentives",
66557
+ controller: o.controller,
66558
+ assets: claimAssets2
66559
+ }
66560
+ };
66561
+ });
66562
+ await markClaimSupport(account, chainId, rewards, opts);
66563
+ return { rewards, errors: [] };
66564
+ }
66565
+ var CLAIM_SELF_ABI = [
66566
+ {
66567
+ name: "claimAllRewardsToSelf",
66568
+ type: "function",
66569
+ stateMutability: "nonpayable",
66570
+ inputs: [{ type: "address[]" }],
66571
+ outputs: [{ type: "address[]" }, { type: "uint256[]" }]
66572
+ }
66573
+ ];
66574
+ async function markClaimSupport(account, chainId, rewards, opts) {
66575
+ const byController = /* @__PURE__ */ new Map();
66576
+ for (const r of rewards)
66577
+ if (r.claim.kind === "aave-incentives")
66578
+ byController.set(r.claim.controller, r.claim.assets);
66579
+ if (!byController.size) return;
66580
+ const client = getEvmClientWithCustomRpcsUniversal({
66581
+ chain: chainId,
66582
+ rpcId: 0,
66583
+ customRpcs: opts.overrides ?? {}
66584
+ });
66585
+ const verdict = /* @__PURE__ */ new Map();
66586
+ await Promise.all(
66587
+ [...byController].map(async ([controller, assets]) => {
66588
+ try {
66589
+ await client.call({
66590
+ account,
66591
+ to: controller,
66592
+ data: encodeFunctionData({
66593
+ abi: CLAIM_SELF_ABI,
66594
+ functionName: "claimAllRewardsToSelf",
66595
+ args: [assets]
66596
+ })
66597
+ });
66598
+ verdict.set(controller, true);
66599
+ } catch (e) {
66600
+ const reverted = /revert/i.test(
66601
+ `${e?.shortMessage ?? ""} ${e?.details ?? ""} ${e?.message ?? ""}`
66602
+ );
66603
+ verdict.set(controller, reverted ? false : void 0);
66604
+ }
66605
+ })
66606
+ );
66607
+ for (const r of rewards) {
66608
+ if (r.claim.kind !== "aave-incentives") continue;
66609
+ const ok4 = verdict.get(r.claim.controller);
66610
+ r.claimSupported = ok4;
66611
+ if (ok4 === false)
66612
+ r.warning = "This controller does not accept the standard claim (`claimAllRewardsToSelf` reverts) \u2014 the protocol claims through its own flow, which may lock or vest the reward. Claim it in the protocol's app.";
66613
+ }
66614
+ }
66615
+ var LENDER4 = "FLYING_TULIP";
66616
+ var FT_DECIMALS2 = 18;
66617
+ var ABI5 = [
66618
+ {
66619
+ name: "previewFTClaimFor",
66620
+ type: "function",
66621
+ stateMutability: "view",
66622
+ inputs: [{ type: "address" }, { type: "address" }],
66623
+ outputs: [{ type: "uint256" }]
66624
+ }
66625
+ ];
66626
+ async function fetchFlyingTulipUserRewards(account, chainId, opts = {}) {
66627
+ const cfg = flyingTulipConfigFor(LENDER4, chainId);
66628
+ const assets = (flyingTulipAssetsFor(LENDER4, chainId)?.assets ?? []).filter(
66629
+ (a) => a.address.toLowerCase() !== cfg?.ft?.toLowerCase()
66630
+ );
66631
+ if (!cfg?.lendingLens || !cfg.positionsManager || !cfg.ft || !assets.length)
66632
+ return { rewards: [], errors: [] };
66633
+ const res = await multicallRetryUniversal({
66634
+ chain: chainId,
66635
+ abi: ABI5,
66636
+ calls: assets.map((a) => ({
66637
+ address: cfg.lendingLens,
66638
+ name: "previewFTClaimFor",
66639
+ params: [account, a.address]
66640
+ })),
66641
+ allowFailure: true,
66642
+ overrides: opts.overrides
66643
+ });
66644
+ const earning = assets.map((a, i) => ({
66645
+ asset: a.address.toLowerCase(),
66646
+ amount: typeof res[i] === "bigint" ? res[i] : 0n
66647
+ })).filter((x) => x.amount > 0n);
66648
+ const failed = res.filter((r) => r == null).length;
66649
+ const errors = failed === assets.length ? [
66650
+ {
66651
+ source: "flying-tulip",
66652
+ chainId,
66653
+ error: "previewFTClaimFor failed for every asset"
66654
+ }
66655
+ ] : [];
66656
+ if (!earning.length) return { rewards: [], errors };
66657
+ const ft = cfg.ft.toLowerCase();
66658
+ const total = earning.reduce((s, x) => s + x.amount, 0n);
66659
+ const prices = await fetchRewardTokenPrices(
66660
+ [{ chainId, address: ft }],
66661
+ opts.fetchImpl
66662
+ );
66663
+ const price2 = prices[`${chainId}:${ft}`];
66664
+ return {
66665
+ rewards: [
66666
+ {
66667
+ chainId,
66668
+ source: "flying-tulip",
66669
+ sourceId: "flying-tulip:ft-emission",
66670
+ token: {
66671
+ address: ft,
66672
+ symbol: "FT",
66673
+ decimals: FT_DECIMALS2,
66674
+ priceUsd: price2
66675
+ },
66676
+ claimable: total.toString(),
66677
+ pending: "0",
66678
+ claimableUsd: toUsd(total, FT_DECIMALS2, price2),
66679
+ breakdowns: earning.map((x) => ({
66680
+ amount: x.amount.toString(),
66681
+ claimable: x.amount.toString(),
66682
+ market: {
66683
+ chainId,
66684
+ lender: LENDER4,
66685
+ underlying: x.asset,
66686
+ side: "deposit",
66687
+ marketUid: createMarketUid(chainId, LENDER4, x.asset)
66688
+ }
66689
+ })),
66690
+ claim: {
66691
+ kind: "flying-tulip",
66692
+ positionsManager: cfg.positionsManager.toLowerCase(),
66693
+ assets: earning.map((x) => x.asset),
66694
+ ft
66695
+ }
66696
+ }
66697
+ ],
66698
+ errors
66699
+ };
66700
+ }
66701
+ var LISTA_TOKEN = "0xfceb31a79f71ac9cbdcf853519c1b12d379edc46";
66702
+ var LISUSD_TOKEN = "0x0782b6d8c4551b9760e74c0545a9bcd90bdc41e5";
66703
+ var LISTA_PROGRAMS = {
66704
+ "lending-v1": {
66705
+ distributor: "0x665410ee5ea96aa729589491badc11e0fe163d29",
66706
+ path: "/api/moolah/emission/userProof",
66707
+ shape: "single",
66708
+ token: { address: LISTA_TOKEN, symbol: "LISTA" },
66709
+ auth: true,
66710
+ sourceId: "lista:emission"
66711
+ },
66712
+ lending: {
66713
+ distributor: "0x2993e9ea76f5839a20673e1b3cf6666ab5b3ae76",
66714
+ path: "/api/moolah/emission/userMultiProof",
66715
+ shape: "multi",
66716
+ auth: true,
66717
+ sourceId: "lista:emission"
66718
+ },
66719
+ holder: {
66720
+ distributor: "0xf17bd72e8bc4abbe7e8dd91b23734bfcf2832a68",
66721
+ path: "/api/moolah/listaHolder/emission/userProof",
66722
+ shape: "multi",
66723
+ auth: true,
66724
+ sourceId: "lista:holder-emission"
66725
+ },
66726
+ "velista-rebate": {
66727
+ distributor: "0xda1e93d58cccc9683f9cb051caec5cf2f01b3253",
66728
+ path: "/api/veboost/userRebateProof",
66729
+ shape: "single",
66730
+ token: { address: LISUSD_TOKEN, symbol: "lisUSD" },
66731
+ auth: true,
66732
+ sourceId: "lista:velista-rebate"
66733
+ },
66734
+ credit: {
66735
+ distributor: "0xc003fb7485ec58a24f26abcaf7646707abc4886c",
66736
+ path: "/api/credit/emission/user-reward",
66737
+ shape: "multi",
66738
+ auth: false,
66739
+ sourceId: "lista:credit-emission"
66740
+ }
66741
+ };
66742
+ Object.fromEntries(
66743
+ Object.entries(LISTA_PROGRAMS).map(([k, v]) => [k, v.distributor])
66744
+ );
66745
+ var LISTA_API2 = "https://api.lista.org";
66746
+ var LOGIN_TTL_SECONDS = 7 * 86400;
66747
+ var LOGIN_SUFFIX = "\nThank you for your support of listaDAO.";
66748
+ var ListaDistributorAbi = [
66749
+ {
66750
+ name: "claimed",
66751
+ type: "function",
66752
+ stateMutability: "view",
66753
+ inputs: [{ type: "address" }, { type: "address" }],
66754
+ outputs: [{ type: "uint256" }]
66755
+ },
66756
+ {
66757
+ name: "claim",
66758
+ type: "function",
66759
+ stateMutability: "nonpayable",
66760
+ inputs: [
66761
+ { name: "_account", type: "address" },
66762
+ { name: "_token", type: "address" },
66763
+ { name: "_totalAmount", type: "uint256" },
66764
+ { name: "_proof", type: "bytes32[]" }
66765
+ ],
66766
+ outputs: []
66767
+ }
66768
+ ];
66769
+ var ListaDistributorV1Abi = [
66770
+ {
66771
+ name: "claimed",
66772
+ type: "function",
66773
+ stateMutability: "view",
66774
+ inputs: [{ type: "address" }],
66775
+ outputs: [{ type: "uint256" }]
66776
+ },
66777
+ {
66778
+ name: "claim",
66779
+ type: "function",
66780
+ stateMutability: "nonpayable",
66781
+ inputs: [
66782
+ { name: "_account", type: "address" },
66783
+ { name: "_totalAmount", type: "uint256" },
66784
+ { name: "_proof", type: "bytes32[]" }
66785
+ ],
66786
+ outputs: []
66787
+ }
66788
+ ];
66789
+ function listaLoginMessage(date = /* @__PURE__ */ new Date()) {
66790
+ return `${date.toISOString()}${LOGIN_SUFFIX}`;
66791
+ }
66792
+ function listaLoginExpiry(message2) {
66793
+ if (!message2.endsWith(LOGIN_SUFFIX)) return void 0;
66794
+ const t = Date.parse(message2.slice(0, -LOGIN_SUFFIX.length));
66795
+ return Number.isFinite(t) ? Math.floor(t / 1e3) + LOGIN_TTL_SECONDS : void 0;
66796
+ }
66797
+ function listaAuthRequired(now = /* @__PURE__ */ new Date()) {
66798
+ return {
66799
+ source: "lista",
66800
+ chainId: LISTA_CLAIM_CHAIN,
66801
+ format: "personal_sign",
66802
+ message: listaLoginMessage(now),
66803
+ expiresAt: Math.floor(now.getTime() / 1e3) + LOGIN_TTL_SECONDS,
66804
+ description: "Lista serves reward proofs only to the account itself: sign this message (personal_sign, the same login the Lista app asks for) and pass it back as listaSignature + listaMessage. It stays valid for 7 days."
66805
+ };
66806
+ }
66807
+ var asProof = (p) => Array.isArray(p) ? p.filter((x) => typeof x === "string") : [];
66808
+ var toWei = (v) => {
66809
+ const t = String(v ?? "0").split(".")[0];
66810
+ return /^\d+$/.test(t) ? BigInt(t) : 0n;
66811
+ };
66812
+ function parseListaProofs(program, data) {
66813
+ const spec = LISTA_PROGRAMS[program];
66814
+ const rows = program === "credit" || spec.shape === "single" ? [data] : data;
66815
+ if (!Array.isArray(rows)) return [];
66816
+ return rows.map((d) => ({
66817
+ program,
66818
+ token: String(
66819
+ spec.token?.address ?? (program === "credit" ? d?.tokenAddress : d?.token) ?? ""
66820
+ ).toLowerCase(),
66821
+ symbol: spec.token?.symbol ?? d?.tokenSymbol ?? (program === "credit" ? "LISTA" : void 0),
66822
+ totalAmount: toWei(program === "credit" ? d?.totalAmount : d?.amountWei),
66823
+ proof: program === "credit" && d?.hasReward === false ? [] : asProof(d?.proof)
66824
+ })).filter(
66825
+ (l) => /^0x[0-9a-f]{40}$/.test(l.token) && l.totalAmount > 0n && l.proof.length > 0
66826
+ );
66827
+ }
66828
+ async function fetchProofs(program, account, auth, fetchImpl) {
66829
+ const spec = LISTA_PROGRAMS[program];
66830
+ const u = new URL(`${LISTA_API2}${spec.path}`);
66831
+ if (!spec.auth) u.searchParams.set("userAddress", account);
66832
+ else {
66833
+ if (!auth) throw new Error(`Lista ${program} needs the login signature`);
66834
+ u.searchParams.set("address", account);
66835
+ u.searchParams.set("signature", auth.signature);
66836
+ u.searchParams.set("message", auth.message);
66837
+ if (auth.type) u.searchParams.set("type", auth.type);
66838
+ }
66839
+ const res = await fetchImpl(u.toString(), {
66840
+ headers: { accept: "application/json" },
66841
+ signal: AbortSignal.timeout(8e3)
66842
+ });
66843
+ const body = await res.json().catch(() => void 0);
66844
+ if (!res.ok || body?.code !== "000000000")
66845
+ throw new Error(
66846
+ `Lista ${program} proofs: ${body?.msg ?? `HTTP ${res.status}`}`
66847
+ );
66848
+ return parseListaProofs(program, body.data);
66849
+ }
66850
+ async function fetchListaUserRewards(account, chainIds, opts = {}) {
66851
+ if (!chainIds.some((c) => LISTA_API_CHAIN[c]))
66852
+ return { rewards: [], errors: [] };
66853
+ const given = opts.listaAuth;
66854
+ const expiry = given?.message ? listaLoginExpiry(given.message) : void 0;
66855
+ const auth = given?.signature && expiry != null && expiry > Date.now() / 1e3 ? given : void 0;
66856
+ let authRequired = auth ? void 0 : [listaAuthRequired()];
66857
+ const chainId = LISTA_CLAIM_CHAIN;
66858
+ const fetchImpl = opts.fetchImpl ?? fetch;
66859
+ const all = Object.keys(LISTA_PROGRAMS);
66860
+ const programs = all.filter((p) => auth || !LISTA_PROGRAMS[p].auth);
66861
+ const errors = [];
66862
+ const authErrors = [];
66863
+ const legs = (await Promise.all(
66864
+ programs.map(
66865
+ (p) => fetchProofs(p, account, auth, fetchImpl).catch((e) => {
66866
+ const error = String(e?.message ?? e);
66867
+ if (LISTA_PROGRAMS[p].auth && /signature|login/i.test(error)) {
66868
+ authErrors.push({ source: "lista", chainId, error });
66869
+ return [];
66870
+ }
66871
+ errors.push({ source: "lista", chainId, error });
66872
+ return [];
66873
+ })
66874
+ )
66875
+ )).flat();
66876
+ if (authErrors.length) {
66877
+ const ask = listaAuthRequired();
66878
+ authRequired = [
66879
+ {
66880
+ ...ask,
66881
+ description: `Lista refused the signature (${authErrors[0].error.replace(/^Lista [\w-]+ proofs: /, "")}). ${ask.description}`
66882
+ }
66883
+ ];
66884
+ }
66885
+ const done = (rewards2) => ({
66886
+ rewards: rewards2,
66887
+ errors,
66888
+ ...authRequired ? { authRequired } : {}
66889
+ });
66890
+ if (!legs.length) return done([]);
66891
+ const claimed = await multicallRetryUniversal({
66892
+ chain: chainId,
66893
+ abi: legs.map(
66894
+ (l) => LISTA_PROGRAMS[l.program].shape === "single" ? ListaDistributorV1Abi : ListaDistributorAbi
66895
+ ),
66896
+ calls: legs.map((l) => ({
66897
+ address: LISTA_PROGRAMS[l.program].distributor,
66898
+ name: "claimed",
66899
+ params: LISTA_PROGRAMS[l.program].shape === "single" ? [account] : [account, l.token]
66900
+ })),
66901
+ allowFailure: true,
66902
+ overrides: opts.overrides
66903
+ });
66904
+ const prices = await fetchRewardTokenPrices(
66905
+ legs.map((l) => ({ chainId, address: l.token })),
66906
+ fetchImpl
66907
+ );
66908
+ const rewards = [];
66909
+ legs.forEach((l, i) => {
66910
+ const done2 = claimed[i];
66911
+ if (typeof done2 !== "bigint") {
66912
+ errors.push({
66913
+ source: "lista",
66914
+ chainId,
66915
+ error: `claimed() unreadable on the ${l.program} distributor for ${l.token}`
66916
+ });
66917
+ return;
66918
+ }
66919
+ const owed = l.totalAmount > done2 ? l.totalAmount - done2 : 0n;
66920
+ if (owed <= 0n) return;
66921
+ const price2 = prices[`${chainId}:${l.token}`];
66922
+ rewards.push({
66923
+ chainId,
66924
+ source: "lista",
66925
+ sourceId: LISTA_PROGRAMS[l.program].sourceId,
66926
+ token: {
66927
+ address: l.token,
66928
+ symbol: l.symbol,
66929
+ decimals: 18,
66930
+ priceUsd: price2
66931
+ },
66932
+ claimable: owed.toString(),
66933
+ pending: "0",
66934
+ claimed: done2.toString(),
66935
+ claimableUsd: toUsd(owed, 18, price2),
66936
+ // The proof attributes nothing per market: the slice names the lender
66937
+ // only, so a `lender=LISTA_DAO` filter keeps it.
66938
+ breakdowns: [
66939
+ {
66940
+ market: { chainId, lender: "LISTA_DAO" },
66941
+ amount: l.totalAmount.toString(),
66942
+ claimable: owed.toString(),
66943
+ claimed: done2.toString(),
66944
+ reason: l.program
66945
+ }
66946
+ ],
66947
+ claim: {
66948
+ kind: "lista",
66949
+ program: l.program,
66950
+ shape: LISTA_PROGRAMS[l.program].shape,
66951
+ distributor: LISTA_PROGRAMS[l.program].distributor,
66952
+ totalAmount: l.totalAmount.toString(),
66953
+ proof: l.proof
66954
+ }
66955
+ });
66956
+ });
66957
+ await markClaimSupport2(account, rewards, opts);
66958
+ return done(rewards);
66959
+ }
66960
+ async function markClaimSupport2(account, rewards, opts) {
66961
+ if (!rewards.length) return;
66962
+ const client = getEvmClientWithCustomRpcsUniversal({
66963
+ chain: LISTA_CLAIM_CHAIN,
66964
+ rpcId: 0,
66965
+ customRpcs: opts.overrides ?? {}
66966
+ });
66967
+ await Promise.all(
66968
+ rewards.map(async (r) => {
66969
+ if (r.claim.kind !== "lista") return;
66970
+ const c = r.claim;
66971
+ const data = c.shape === "single" ? encodeFunctionData({
66972
+ abi: ListaDistributorV1Abi,
66973
+ functionName: "claim",
66974
+ args: [
66975
+ account,
66976
+ BigInt(c.totalAmount),
66977
+ c.proof
66978
+ ]
66979
+ }) : encodeFunctionData({
66980
+ abi: ListaDistributorAbi,
66981
+ functionName: "claim",
66982
+ args: [
66983
+ account,
66984
+ r.token.address,
66985
+ BigInt(c.totalAmount),
66986
+ c.proof
66987
+ ]
66988
+ });
66989
+ try {
66990
+ await client.call({
66991
+ account,
66992
+ to: c.distributor,
66993
+ data
66994
+ });
66995
+ r.claimSupported = true;
66996
+ } catch (e) {
66997
+ const reverted = /revert/i.test(
66998
+ `${e?.shortMessage ?? ""} ${e?.details ?? ""} ${e?.message ?? ""}`
66999
+ );
67000
+ if (reverted) {
67001
+ r.claimSupported = false;
67002
+ r.warning = "Lista's proof does not verify against the distributor's live root yet (a new root waits out a delay before it is accepted) \u2014 retry later.";
67003
+ }
67004
+ }
67005
+ })
67006
+ );
67007
+ }
67008
+ var MERKL_API = "https://api.merkl.xyz/v4";
67009
+ var MERKL_DISTRIBUTOR = "0x3ef3d8ba38ebe18db133cec108f4d14ce00dd9ae";
67010
+ var TIMEOUT_MS7 = 8e3;
67011
+ var OPP_CONCURRENCY = 8;
67012
+ var ROOT_ABI = [
67013
+ {
67014
+ name: "getMerkleRoot",
67015
+ type: "function",
67016
+ stateMutability: "view",
67017
+ inputs: [],
67018
+ outputs: [{ type: "bytes32" }]
67019
+ }
67020
+ ];
67021
+ var big27 = (v) => {
67022
+ try {
67023
+ return BigInt(String(v ?? "0"));
67024
+ } catch {
67025
+ return 0n;
67026
+ }
67027
+ };
67028
+ var oppCache2 = /* @__PURE__ */ new Map();
67029
+ function fetchOpportunity(id, f) {
67030
+ let p = oppCache2.get(id);
67031
+ if (!p) {
67032
+ p = f(`${MERKL_API}/opportunities/${id}`, {
67033
+ signal: AbortSignal.timeout(TIMEOUT_MS7)
67034
+ }).then((r) => r.ok ? r.json() : void 0).catch(() => void 0);
67035
+ p.then((o) => {
67036
+ if (!o) oppCache2.delete(id);
67037
+ });
67038
+ oppCache2.set(id, p);
67039
+ if (oppCache2.size > 5e3) oppCache2.delete(oppCache2.keys().next().value);
67040
+ }
67041
+ return p;
67042
+ }
67043
+ async function mapLimit2(items, limit, fn2) {
67044
+ const out = new Array(items.length);
67045
+ let next = 0;
67046
+ await Promise.all(
67047
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
67048
+ while (next < items.length) {
67049
+ const i = next++;
67050
+ out[i] = await fn2(items[i]);
67051
+ }
67052
+ })
67053
+ );
67054
+ return out;
67055
+ }
67056
+ async function fetchMerklUserRewards(account, chainIds, resolve, opts = {}) {
67057
+ const f = opts.fetchImpl ?? fetch;
67058
+ const errors = [];
67059
+ if (!chainIds.length) return { rewards: [], errors };
67060
+ let body;
67061
+ try {
67062
+ const q = chainIds.map((c) => `chainId=${encodeURIComponent(c)}`).join("&");
67063
+ const res = await f(`${MERKL_API}/users/${account}/rewards?${q}`, {
67064
+ signal: AbortSignal.timeout(TIMEOUT_MS7)
67065
+ });
67066
+ if (!res.ok) throw new Error(`Merkl API ${res.status}`);
67067
+ const json = await res.json();
67068
+ body = Array.isArray(json) ? json : [];
67069
+ } catch (e) {
67070
+ return {
67071
+ rewards: [],
67072
+ errors: [{ source: "merkl", error: String(e?.message ?? e) }]
67073
+ };
67074
+ }
67075
+ const rows = body.flatMap(
67076
+ (c) => (c.rewards ?? []).map((r) => ({
67077
+ chainId: String(r.distributionChainId ?? c.chain?.id ?? ""),
67078
+ r
67079
+ }))
67080
+ );
67081
+ const live = rows.filter(
67082
+ ({ r }) => big27(r.amount) > big27(r.claimed) || big27(r.pending) > 0n
67083
+ );
67084
+ if (!live.length) return { rewards: [], errors };
67085
+ const chains = [...new Set(live.map((x) => x.chainId))];
67086
+ const onchainRoot = /* @__PURE__ */ new Map();
67087
+ await Promise.all(
67088
+ chains.map(async (chainId) => {
67089
+ try {
67090
+ const [root] = await multicallRetryUniversal({
67091
+ chain: chainId,
67092
+ abi: ROOT_ABI,
67093
+ calls: [
67094
+ { address: MERKL_DISTRIBUTOR, name: "getMerkleRoot", params: [] }
67095
+ ],
67096
+ allowFailure: true,
67097
+ overrides: opts.overrides
67098
+ });
67099
+ onchainRoot.set(
67100
+ chainId,
67101
+ typeof root === "string" ? root.toLowerCase() : void 0
67102
+ );
67103
+ } catch {
67104
+ onchainRoot.set(chainId, void 0);
67105
+ }
67106
+ })
67107
+ );
67108
+ const oppIds = [
67109
+ ...new Set(
67110
+ live.flatMap(
67111
+ ({ r }) => (r.breakdowns ?? []).map((b) => b.opportunityId).filter(Boolean)
67112
+ )
67113
+ )
67114
+ ];
67115
+ const opps = await mapLimit2(
67116
+ oppIds,
67117
+ OPP_CONCURRENCY,
67118
+ (id) => fetchOpportunity(id, f)
67119
+ );
67120
+ const marketsByOpp = /* @__PURE__ */ new Map();
67121
+ oppIds.forEach((id, i) => {
67122
+ const o = opps[i];
67123
+ if (o) {
67124
+ try {
67125
+ marketsByOpp.set(id, resolve(o));
67126
+ } catch {
67127
+ marketsByOpp.set(id, []);
67128
+ }
67129
+ }
67130
+ });
67131
+ const rewards = live.map(({ chainId, r }) => {
67132
+ const claimable = big27(r.amount) - big27(r.claimed);
67133
+ const pending = big27(r.pending);
67134
+ const decimals = r.token.decimals;
67135
+ const price2 = r.token.price ?? void 0;
67136
+ const breakdowns = (r.breakdowns ?? []).filter((b) => big27(b.amount) > big27(b.claimed) || big27(b.pending) > 0n).flatMap((b) => {
67137
+ const markets = b.opportunityId ? marketsByOpp.get(b.opportunityId) ?? [] : [];
67138
+ const base = {
67139
+ amount: big27(b.amount).toString(),
67140
+ claimable: (big27(b.amount) - big27(b.claimed)).toString(),
67141
+ claimed: big27(b.claimed).toString(),
67142
+ pending: big27(b.pending).toString(),
67143
+ merklOpportunityId: b.opportunityId,
67144
+ campaignId: b.campaignId,
67145
+ reason: b.reason
67146
+ };
67147
+ if (!markets.length) return [base];
67148
+ return markets.map(
67149
+ (market, k) => k === 0 ? { ...base, market } : {
67150
+ ...base,
67151
+ market,
67152
+ amount: "0",
67153
+ claimable: "0",
67154
+ claimed: "0",
67155
+ pending: "0"
67156
+ }
67157
+ );
67158
+ });
67159
+ const root = onchainRoot.get(chainId);
67160
+ const warning = claimable > 0n && root && r.root && r.root.toLowerCase() !== root ? "Merkl's proof is for an older root than the Distributor's \u2014 the balance is right, but a claim must wait for the update to propagate" : claimable > 0n && !root ? "Could not read the Distributor's root on this chain" : void 0;
67161
+ return {
67162
+ chainId,
67163
+ source: "merkl",
67164
+ sourceId: "merkl",
67165
+ token: {
67166
+ address: r.token.address.toLowerCase(),
67167
+ symbol: r.token.symbol,
67168
+ decimals,
67169
+ priceUsd: price2
67170
+ },
67171
+ claimable: claimable.toString(),
67172
+ pending: pending.toString(),
67173
+ claimed: big27(r.claimed).toString(),
67174
+ claimableUsd: toUsd(claimable, decimals, price2),
67175
+ pendingUsd: toUsd(pending, decimals, price2),
67176
+ breakdowns,
67177
+ claim: { kind: "merkl", distributor: MERKL_DISTRIBUTOR },
67178
+ ...warning ? { warning } : {}
67179
+ };
67180
+ });
67181
+ return { rewards, errors };
67182
+ }
67183
+
67184
+ // src/yields/rewards/user/index.ts
67185
+ var USER_REWARD_SOURCES = [
67186
+ "merkl",
67187
+ "aave-incentives",
67188
+ "flying-tulip",
67189
+ "lista"
67190
+ ];
67191
+ async function fetchUserRewards(params) {
67192
+ const account = params.account.toLowerCase();
67193
+ const sources = new Set(params.sources ?? USER_REWARD_SOURCES);
67194
+ const opts = params.options ?? {};
67195
+ const jobs = [];
67196
+ if (sources.has("merkl"))
67197
+ jobs.push(
67198
+ fetchMerklUserRewards(
67199
+ account,
67200
+ params.chainIds,
67201
+ params.resolveMerkl ?? resolveMerklOpportunityMarkets,
67202
+ opts
67203
+ )
67204
+ );
67205
+ if (sources.has("lista"))
67206
+ jobs.push(
67207
+ fetchListaUserRewards(account, params.chainIds, opts).catch((e) => ({
67208
+ rewards: [],
67209
+ errors: [{ source: "lista", error: String(e?.message ?? e) }]
67210
+ }))
67211
+ );
67212
+ for (const chainId of params.chainIds) {
67213
+ if (sources.has("aave-incentives"))
67214
+ jobs.push(
67215
+ fetchAaveIncentivesUserRewards(account, chainId, opts).catch((e) => ({
67216
+ rewards: [],
67217
+ errors: [
67218
+ {
67219
+ source: "aave-incentives",
67220
+ chainId,
67221
+ error: String(e?.message ?? e)
67222
+ }
67223
+ ]
67224
+ }))
67225
+ );
67226
+ if (sources.has("flying-tulip"))
67227
+ jobs.push(
67228
+ fetchFlyingTulipUserRewards(account, chainId, opts).catch((e) => ({
67229
+ rewards: [],
67230
+ errors: [
67231
+ {
67232
+ source: "flying-tulip",
67233
+ chainId,
67234
+ error: String(e?.message ?? e)
67235
+ }
67236
+ ]
67237
+ }))
67238
+ );
67239
+ }
67240
+ const results = await Promise.all(jobs);
67241
+ const authRequired = results.flatMap((r) => r.authRequired ?? []);
67242
+ return {
67243
+ account,
67244
+ rewards: results.flatMap((r) => r.rewards),
67245
+ errors: results.flatMap((r) => r.errors),
67246
+ ...authRequired.length ? { authRequired } : {}
67247
+ };
67248
+ }
67249
+
65404
67250
  // src/yields/fetchGeneralYields.ts
65405
67251
  var fetchGeneralYields = async () => {
65406
67252
  const [intrinsicYields, rewards] = await Promise.all([
@@ -66569,7 +68415,7 @@ function getDssCalls(chainId) {
66569
68415
  return results;
66570
68416
  }
66571
68417
  var RAY10 = 1e27;
66572
- var big27 = (v) => {
68418
+ var big28 = (v) => {
66573
68419
  try {
66574
68420
  if (typeof v === "bigint") return v;
66575
68421
  if (v == null || v === "0x") return 0n;
@@ -66581,16 +68427,16 @@ var big27 = (v) => {
66581
68427
  var field15 = (res, name, idx) => {
66582
68428
  const v = res?.[name];
66583
68429
  if (typeof v === "bigint" || typeof v === "number" || typeof v === "string") {
66584
- return big27(v);
68430
+ return big28(v);
66585
68431
  }
66586
- return big27(res?.[idx]);
68432
+ return big28(res?.[idx]);
66587
68433
  };
66588
68434
  function parseDssResults(data, meta, context) {
66589
68435
  const { chainId } = context;
66590
68436
  const key5 = dssLenderKey(meta.lender, chainId, meta.ilk);
66591
68437
  const entries = [];
66592
68438
  const spot = field15(data?.[0], "spot", 2);
66593
- const mat = big27(meta.mat);
68439
+ const mat = big28(meta.mat);
66594
68440
  if (spot > 0n && mat > 0n) {
66595
68441
  const collUSD = Number(spot) / RAY10 * (Number(mat) / RAY10);
66596
68442
  if (collUSD > 0 && collUSD < 1e9) {
@@ -68343,7 +70189,7 @@ var gearboxV3Fetcher = {
68343
70189
  parse: parseGearboxV3Results,
68344
70190
  getAbi: getGearboxV3Abi
68345
70191
  };
68346
- var LENDER2 = "DOLOMITE";
70192
+ var LENDER5 = "DOLOMITE";
68347
70193
  function getDolomiteCalls(chainId) {
68348
70194
  const cfg = dolomiteConfigs()?.[chainId];
68349
70195
  const margin = cfg?.dolomiteMargin;
@@ -68359,7 +70205,7 @@ function getDolomiteCalls(chainId) {
68359
70205
  name: "getMarketPrice",
68360
70206
  params: [marketId]
68361
70207
  }));
68362
- return [{ calls, meta: { markets }, lender: LENDER2 }];
70208
+ return [{ calls, meta: { markets }, lender: LENDER5 }];
68363
70209
  }
68364
70210
  function parseDolomiteResults(data, meta, context) {
68365
70211
  const { chainId, tokenList } = context;
@@ -68377,8 +70223,8 @@ function parseDolomiteResults(data, meta, context) {
68377
70223
  asset,
68378
70224
  price: priceUSD,
68379
70225
  priceUSD,
68380
- marketUid: createMarketUid(chainId, LENDER2, String(mkt.marketId)),
68381
- targetLender: LENDER2
70226
+ marketUid: createMarketUid(chainId, LENDER5, String(mkt.marketId)),
70227
+ targetLender: LENDER5
68382
70228
  });
68383
70229
  } catch {
68384
70230
  }
@@ -68877,10 +70723,10 @@ var SHARE_RATE_PRICE_SPECS = [
68877
70723
  ...ERC4626_SHARE_RATE_PRICE_SPECS,
68878
70724
  ...YEARN_V3_SHARE_RATE_PRICE_SPECS
68879
70725
  ];
68880
- var ABI3 = parseAbi([
70726
+ var ABI6 = parseAbi([
68881
70727
  "function getReport(address asset) view returns (uint224 priceD18, uint32 timestamp, bool isSuspicious)"
68882
70728
  ]);
68883
- var abiItemFor = (read) => read.kind === "mellow-report" ? ABI3 : parseAbi([
70729
+ var abiItemFor = (read) => read.kind === "mellow-report" ? ABI6 : parseAbi([
68884
70730
  read.arg === null ? `function ${read.fn}() view returns (uint256)` : `function ${read.fn}(uint256) view returns (uint256)`
68885
70731
  ]);
68886
70732
  function shareRateCalls(chainId, specs = SHARE_RATE_PRICE_SPECS) {
@@ -71572,6 +73418,7 @@ var fetchFluidFTokens = async (chainId, multicallRetry, prices = {}, tokenList =
71572
73418
  });
71573
73419
  const [converter] = getFluidFTokensConverter(chainId, prices, tokenList);
71574
73420
  const fTokens = converter(raw) ?? {};
73421
+ const merklPromise = fetchFluidFTokenMerklStreams(chainId);
71575
73422
  try {
71576
73423
  const underlyings = Object.values(fTokens).map((f) => f.underlying).filter((a) => !!a && a !== zeroAddress);
71577
73424
  const assetDec = await fetchAssetDecimals(
@@ -71604,6 +73451,14 @@ var fetchFluidFTokens = async (chainId, multicallRetry, prices = {}, tokenList =
71604
73451
  }
71605
73452
  } catch {
71606
73453
  }
73454
+ const merkl = await merklPromise;
73455
+ for (const f of Object.values(fTokens)) {
73456
+ const m = merkl.get((f.address ?? "").toLowerCase());
73457
+ if (!m) continue;
73458
+ f.rewardsRate += m.apr;
73459
+ f.depositRate = f.supplyRate + f.rewardsRate;
73460
+ f.rewardStreams = m.streams;
73461
+ }
71607
73462
  return fTokens;
71608
73463
  };
71609
73464
  async function fetchFluidExposures(chainId, multicallRetry, prices, tokenList) {
@@ -71906,7 +73761,7 @@ function curatorNameFromVaultName(name, assetSymbol) {
71906
73761
  // src/vaults/morpho/fetchFromApi.ts
71907
73762
  var MORPHO_SHARE_DECIMALS = 18;
71908
73763
  var MORPHO_API_URL = "https://blue-api.morpho.org/graphql";
71909
- var PAGE_SIZE2 = 200;
73764
+ var PAGE_SIZE3 = 200;
71910
73765
  var MIN_TOTAL_ASSETS_USD = 100;
71911
73766
  var vaultsQuery = (first, skip, chainId, tier = "decorated") => `
71912
73767
  query GetVaults {
@@ -72207,14 +74062,14 @@ async function fetchMorphoVaultsFromApi(chainId, prices = {}, tokenList = {}, ma
72207
74062
  const out = {};
72208
74063
  let skip = 0;
72209
74064
  while (skip < maxItems) {
72210
- const page = await fetchPage(chainId, PAGE_SIZE2, skip);
74065
+ const page = await fetchPage(chainId, PAGE_SIZE3, skip);
72211
74066
  if (page.length === 0) break;
72212
74067
  for (const v of page) {
72213
74068
  const parsed = parseVault2(v, chainId, prices, tokenList);
72214
74069
  if (parsed) out[parsed.address] = parsed;
72215
74070
  }
72216
- if (page.length < PAGE_SIZE2) break;
72217
- skip += PAGE_SIZE2;
74071
+ if (page.length < PAGE_SIZE3) break;
74072
+ skip += PAGE_SIZE3;
72218
74073
  }
72219
74074
  try {
72220
74075
  let skipV2 = 0;
@@ -72992,6 +74847,12 @@ var collectEntries2 = (chainId) => {
72992
74847
  var fetchListaVaultsFromChain = async (chainId, multicallRetry, prices = {}, tokenList = {}, opts = {}) => {
72993
74848
  const entries = opts.vaultsOverride ?? collectEntries2(chainId);
72994
74849
  if (entries.length === 0) return {};
74850
+ const emissionsP = opts.emissions === false ? Promise.resolve({}) : fetchListaVaultEmissions(chainId).catch((e) => {
74851
+ console.warn(
74852
+ `[lista] vault emissions unavailable on chain ${chainId}: ${e?.message ?? e}`
74853
+ );
74854
+ return {};
74855
+ });
72995
74856
  const phase1Calls = entries.flatMap(
72996
74857
  (entry2) => PHASE1_CALLS2.map((name) => ({
72997
74858
  address: entry2.vault,
@@ -73084,8 +74945,29 @@ var fetchListaVaultsFromChain = async (chainId, multicallRetry, prices = {}, tok
73084
74945
  );
73085
74946
  if (parsed) out[parsed.address] = parsed;
73086
74947
  }
73087
- return dropUnrealizableRates(out);
74948
+ return withListaEmissions(dropUnrealizableRates(out), await emissionsP);
73088
74949
  };
74950
+ async function withListaEmissions(vaults, emissions) {
74951
+ const paying = Object.values(emissions).filter((e) => vaults[e.vault]);
74952
+ if (!paying.length) return vaults;
74953
+ const prices = await fetchLlamaBscPrices(
74954
+ paying.flatMap((e) => e.legs.map((l) => l.token))
74955
+ );
74956
+ for (const e of paying) {
74957
+ const v = vaults[e.vault];
74958
+ const streams = listaEmissionStreams("deposit", e.legs, prices, {
74959
+ vault: e.vault
74960
+ });
74961
+ const rewardsRate = streams.reduce((s, x) => s + x.apr, 0);
74962
+ vaults[e.vault] = {
74963
+ ...v,
74964
+ rewardsRate,
74965
+ depositRate: v.supplyRate + rewardsRate,
74966
+ rewardStreams: streams
74967
+ };
74968
+ }
74969
+ return vaults;
74970
+ }
73089
74971
  async function fetchListaMarketRates(chainId, moolah, marketIds, multicallRetry) {
73090
74972
  const map = /* @__PURE__ */ new Map();
73091
74973
  const lens = MORPHO_LENS[chainId];
@@ -73368,7 +75250,7 @@ function computeSiloUtilization(vaultId, totalAssetsFormatted, positionsByVault,
73368
75250
  }
73369
75251
  var clamp012 = (n) => !Number.isFinite(n) ? 0 : n < 0 ? 0 : n > 1 ? 1 : n;
73370
75252
  var PERFORMANCE_FEE_SCALE = 1e16;
73371
- var SECONDS_PER_YEAR19 = 31536e3;
75253
+ var SECONDS_PER_YEAR20 = 31536e3;
73372
75254
  function buildVaultRewards(vaultId, totalAssetsUsd, programsByShareToken, priceOf2, nowSeconds2) {
73373
75255
  const programs = programsByShareToken.get(vaultId) ?? [];
73374
75256
  const rewards = [];
@@ -73384,7 +75266,7 @@ function buildVaultRewards(vaultId, totalAssetsUsd, programsByShareToken, priceO
73384
75266
  const tokenPrice = tokenAddress ? priceOf2(tokenAddress) : 0;
73385
75267
  let apr;
73386
75268
  if (tokenPrice > 0 && totalAssetsUsd > 0) {
73387
- const annualTokens = emission / 10 ** tokenDecimals * SECONDS_PER_YEAR19;
75269
+ const annualTokens = emission / 10 ** tokenDecimals * SECONDS_PER_YEAR20;
73388
75270
  apr = annualTokens * tokenPrice / totalAssetsUsd * 100;
73389
75271
  rewardsRate += apr;
73390
75272
  } else {
@@ -73761,7 +75643,7 @@ query EvkByAssets($assets: [Bytes!]!) {
73761
75643
  }
73762
75644
  }
73763
75645
  `;
73764
- var ZERO7 = 0n;
75646
+ var ZERO8 = 0n;
73765
75647
  var RAY_TO_PERCENT3 = 1e25;
73766
75648
  function readAddress2(field16) {
73767
75649
  if (!field16) return void 0;
@@ -73776,28 +75658,28 @@ function parseVaultFee(v) {
73776
75658
  return n;
73777
75659
  }
73778
75660
  function safeBigInt(v) {
73779
- if (v == null || v === "") return ZERO7;
75661
+ if (v == null || v === "") return ZERO8;
73780
75662
  try {
73781
75663
  return BigInt(v);
73782
75664
  } catch {
73783
- return ZERO7;
75665
+ return ZERO8;
73784
75666
  }
73785
75667
  }
73786
75668
  function computeWeightedSupplyApy(strategies, totalAssetsRaw, feePercent2, evkIndex) {
73787
75669
  if (!strategies?.length) return 0;
73788
75670
  const totalAssets = safeBigInt(totalAssetsRaw);
73789
- if (totalAssets === ZERO7) return 0;
73790
- let weightedRay = ZERO7;
75671
+ if (totalAssets === ZERO8) return 0;
75672
+ let weightedRay = ZERO8;
73791
75673
  for (const s of strategies) {
73792
75674
  const evk = s.strategy?.toLowerCase();
73793
75675
  if (!evk) continue;
73794
75676
  const apyRay = evkIndex.bySupplyApyRay.get(evk);
73795
75677
  if (apyRay == null) continue;
73796
75678
  const allocated = safeBigInt(s.allocatedAssets);
73797
- if (allocated === ZERO7) continue;
75679
+ if (allocated === ZERO8) continue;
73798
75680
  weightedRay += allocated * apyRay;
73799
75681
  }
73800
- if (weightedRay === ZERO7) return 0;
75682
+ if (weightedRay === ZERO8) return 0;
73801
75683
  const apyRayPerAsset = weightedRay / totalAssets;
73802
75684
  const grossPercent = apyToAprPercent(Number(apyRayPerAsset) / RAY_TO_PERCENT3);
73803
75685
  const netPercent = grossPercent * (1 - feePercent2 / 100);
@@ -73805,24 +75687,24 @@ function computeWeightedSupplyApy(strategies, totalAssetsRaw, feePercent2, evkIn
73805
75687
  }
73806
75688
  function computeRealLiquidity(strategies, totalAssetsRaw, evkIndex) {
73807
75689
  const totalAssets = safeBigInt(totalAssetsRaw);
73808
- if (totalAssets === ZERO7) return ZERO7;
75690
+ if (totalAssets === ZERO8) return ZERO8;
73809
75691
  if (evkIndex.byCash.size === 0 && evkIndex.bySupplyApyRay.size === 0) {
73810
75692
  return totalAssets;
73811
75693
  }
73812
75694
  if (!strategies?.length) {
73813
75695
  return totalAssets;
73814
75696
  }
73815
- let allocSum = ZERO7;
73816
- let withdrawable = ZERO7;
75697
+ let allocSum = ZERO8;
75698
+ let withdrawable = ZERO8;
73817
75699
  for (const s of strategies) {
73818
75700
  const alloc = safeBigInt(s.allocatedAssets);
73819
- if (alloc === ZERO7) continue;
75701
+ if (alloc === ZERO8) continue;
73820
75702
  allocSum += alloc;
73821
75703
  const evk = s.strategy?.toLowerCase();
73822
75704
  const cash = evk ? evkIndex.byCash.get(evk) : void 0;
73823
75705
  withdrawable += cash == null ? alloc : alloc < cash ? alloc : cash;
73824
75706
  }
73825
- const idle = totalAssets > allocSum ? totalAssets - allocSum : ZERO7;
75707
+ const idle = totalAssets > allocSum ? totalAssets - allocSum : ZERO8;
73826
75708
  const result = idle + withdrawable;
73827
75709
  return result > totalAssets ? totalAssets : result;
73828
75710
  }
@@ -74001,7 +75883,7 @@ function rescaleExchangeRate(exchangeRate, shareDecimals) {
74001
75883
  }
74002
75884
  var EULER_API_CACHE_TTL_MS = 6e4;
74003
75885
  var jsonCache = /* @__PURE__ */ new Map();
74004
- function getJson6(url) {
75886
+ function getJson7(url) {
74005
75887
  const hit = jsonCache.get(url);
74006
75888
  if (hit && Date.now() - hit.at < EULER_API_CACHE_TTL_MS) return hit.promise;
74007
75889
  const entry2 = { at: Date.now(), promise: fetchJsonOnce(url) };
@@ -74108,7 +75990,7 @@ async function mapWithConcurrency(items, limit, fn2) {
74108
75990
  return out;
74109
75991
  }
74110
75992
  async function fetchEulerEarnVaultsFromApi(chainId, prices = {}, tokenList = {}, multicallRetry) {
74111
- const list = await getJson6(
75993
+ const list = await getJson7(
74112
75994
  `${EULER_DATA_API_BASE2}/earn/vaults?chainId=${chainId}&limit=200&visibility=${VISIBILITY_ALL}`
74113
75995
  );
74114
75996
  if (!list) return void 0;
@@ -74125,7 +76007,7 @@ async function fetchEulerEarnVaultsFromApi(chainId, prices = {}, tokenList = {},
74125
76007
  mapWithConcurrency(
74126
76008
  rows,
74127
76009
  DETAIL_CONCURRENCY,
74128
- (row) => getJson6(
76010
+ (row) => getJson7(
74129
76011
  `${EULER_DATA_API_BASE2}/earn/vaults/${chainId}/${row.address}?include=strategies`
74130
76012
  ).then((d) => d?.data)
74131
76013
  ),
@@ -74180,11 +76062,11 @@ var fetchEulerEarnVaults = async (chainId, prices = {}, tokenList = {}, multical
74180
76062
  };
74181
76063
  var warn6 = (...args) => {
74182
76064
  };
74183
- var num5 = (v) => {
76065
+ var num6 = (v) => {
74184
76066
  const n = Number(v);
74185
76067
  return Number.isFinite(n) ? n : 0;
74186
76068
  };
74187
- var big28 = (v) => {
76069
+ var big29 = (v) => {
74188
76070
  try {
74189
76071
  if (v === void 0 || v === null || v === "") return "0";
74190
76072
  const s = String(v);
@@ -74215,21 +76097,21 @@ async function fetchTermMaxVaultsFromApi(chainId, prices = {}, tokenList = {}, f
74215
76097
  const underlying = lower3(r?.asset?.contractAddress);
74216
76098
  if (!address || !underlying) continue;
74217
76099
  if (r.isEnabled === false) continue;
74218
- const assetDecimals = num5(r?.asset?.decimals) || 18;
76100
+ const assetDecimals = num6(r?.asset?.decimals) || 18;
74219
76101
  const scale3 = 10 ** assetDecimals;
74220
76102
  const assetEntry = tokenList[underlying];
74221
76103
  const priceKey = toOracleKey(assetEntry?.assetGroup) || toGenericPriceKey(underlying, chainId);
74222
76104
  const priceUsd = prices[priceKey];
74223
- const totalAssets = big28(r.totalAssets);
74224
- const totalSupply = big28(r.totalSupplyAmt);
76105
+ const totalAssets = big29(r.totalAssets);
76106
+ const totalSupply = big29(r.totalSupplyAmt);
74225
76107
  const totalAssetsFormatted = Number(totalAssets) / scale3;
74226
- const supplyRate = num5(r.apr) * 100;
74227
- const rewardsRate = num5(r?.incentiveData?.TMX_APR) * 100;
74228
- const rawLiquidity = BigInt(big28(r.redeemableAmt ?? r.idleFunds ?? "0"));
76108
+ const supplyRate = num6(r.apr) * 100;
76109
+ const rewardsRate = num6(r?.incentiveData?.TMX_APR) * 100;
76110
+ const rawLiquidity = BigInt(big29(r.redeemableAmt ?? r.idleFunds ?? "0"));
74229
76111
  const totalAssetsBig = BigInt(totalAssets);
74230
76112
  const liquidity = (rawLiquidity > totalAssetsBig ? totalAssetsBig : rawLiquidity).toString();
74231
76113
  const liquidityFormatted = Number(liquidity) / scale3;
74232
- const totalSupplyValue = num5(r.totalSupplyValue);
76114
+ const totalSupplyValue = num6(r.totalSupplyValue);
74233
76115
  out[address] = {
74234
76116
  address,
74235
76117
  underlying,
@@ -74246,8 +76128,8 @@ async function fetchTermMaxVaultsFromApi(chainId, prices = {}, tokenList = {}, f
74246
76128
  rewardsRate,
74247
76129
  depositRate: supplyRate + rewardsRate,
74248
76130
  // 1e8-scaled upstream (10000000 = 10%).
74249
- fee: num5(r.performanceFeeRate) / 1e6,
74250
- timelock: num5(r.timeLockSeconds) || void 0,
76131
+ fee: num6(r.performanceFeeRate) / 1e6,
76132
+ timelock: num6(r.timeLockSeconds) || void 0,
74251
76133
  curator: r?.curator?.curatorAddress ? lower3(r.curator.curatorAddress) : void 0,
74252
76134
  // The API is the ONLY source for this — do not derive it from `name`.
74253
76135
  curatorName: r?.curator?.name || void 0,
@@ -74261,7 +76143,7 @@ async function fetchTermMaxVaultsFromApi(chainId, prices = {}, tokenList = {}, f
74261
76143
  liquidityUsd: priceUsd ? liquidityFormatted * priceUsd : 0,
74262
76144
  version: r.version,
74263
76145
  isPaused: r.isPaused === true || void 0,
74264
- supplyCap: r.capacity ? big28(r.capacity) : void 0,
76146
+ supplyCap: r.capacity ? big29(r.capacity) : void 0,
74265
76147
  basePool: r.poolAddress ? lower3(r.poolAddress) : void 0
74266
76148
  };
74267
76149
  }
@@ -74317,7 +76199,7 @@ var Erc20DecimalsBalanceAbi = [
74317
76199
 
74318
76200
  // src/vaults/termmax/fetchFromChain.ts
74319
76201
  var DECIMAL_BASE2 = 100000000n;
74320
- var big29 = (v) => {
76202
+ var big30 = (v) => {
74321
76203
  if (v === void 0 || v === null || v === "0x") return 0n;
74322
76204
  try {
74323
76205
  return typeof v === "bigint" ? v : BigInt(v);
@@ -74325,7 +76207,7 @@ var big29 = (v) => {
74325
76207
  return 0n;
74326
76208
  }
74327
76209
  };
74328
- var num6 = (v) => {
76210
+ var num7 = (v) => {
74329
76211
  const n = Number(v);
74330
76212
  return Number.isFinite(n) ? n : void 0;
74331
76213
  };
@@ -74381,23 +76263,23 @@ var fetchTermMaxVaultsFromChain = async (chainId, multicallRetry, prices = {}, t
74381
76263
  vaults.forEach((address, i) => {
74382
76264
  const at2 = (k) => res[i * READS_PER_VAULT + VAULT_READS.indexOf(k)];
74383
76265
  const asset = addr(at2("asset"));
74384
- const totalAssets = big29(at2("totalAssets"));
76266
+ const totalAssets = big30(at2("totalAssets"));
74385
76267
  if (!asset || totalAssets === 0n) return;
74386
76268
  rows.push({
74387
76269
  address,
74388
76270
  name: str3(at2("name")),
74389
76271
  symbol: str3(at2("symbol")),
74390
- decimals: num6(at2("decimals")) ?? 18,
76272
+ decimals: num7(at2("decimals")) ?? 18,
74391
76273
  asset,
74392
76274
  totalAssets,
74393
- totalSupply: big29(at2("totalSupply")),
74394
- annualizedInterest: big29(at2("annualizedInterest")),
74395
- accretingPrincipal: big29(at2("accretingPrincipal")),
74396
- performanceFeeRate: big29(at2("performanceFeeRate")),
74397
- aprRaw: at2("apr") != null ? big29(at2("apr")) : void 0,
76275
+ totalSupply: big30(at2("totalSupply")),
76276
+ annualizedInterest: big30(at2("annualizedInterest")),
76277
+ accretingPrincipal: big30(at2("accretingPrincipal")),
76278
+ performanceFeeRate: big30(at2("performanceFeeRate")),
76279
+ aprRaw: at2("apr") != null ? big30(at2("apr")) : void 0,
74398
76280
  curator: addr(at2("curator")),
74399
76281
  guardian: addr(at2("guardian")),
74400
- timelock: num6(at2("timelock")),
76282
+ timelock: num7(at2("timelock")),
74401
76283
  version: str3(at2("getVersion"))
74402
76284
  });
74403
76285
  });
@@ -74414,8 +76296,8 @@ var fetchTermMaxVaultsFromChain = async (chainId, multicallRetry, prices = {}, t
74414
76296
  });
74415
76297
  const out = {};
74416
76298
  rows.forEach((r, i) => {
74417
- const assetDecimals = num6(res2[i * 2]) ?? r.decimals;
74418
- const idle = big29(res2[i * 2 + 1]);
76299
+ const assetDecimals = num7(res2[i * 2]) ?? r.decimals;
76300
+ const idle = big30(res2[i * 2 + 1]);
74419
76301
  const assetEntry = tokenList[r.asset];
74420
76302
  const priceKey = toOracleKey(assetEntry?.assetGroup) || toGenericPriceKey(r.asset, chainId);
74421
76303
  const priceUsd = prices[priceKey];
@@ -81616,6 +83498,30 @@ var SuperformStrategyConfigAbi = [
81616
83498
  }
81617
83499
  ];
81618
83500
 
83501
+ // src/vaults/savings/abis/ember.ts
83502
+ var EmberMaxDepositAbi = [
83503
+ {
83504
+ name: "maxDeposit",
83505
+ type: "function",
83506
+ stateMutability: "view",
83507
+ inputs: [{ type: "address", name: "receiver" }],
83508
+ outputs: [{ type: "uint256" }]
83509
+ }
83510
+ ];
83511
+ var EmberPauseStatusAbi = [
83512
+ {
83513
+ name: "pauseStatus",
83514
+ type: "function",
83515
+ stateMutability: "view",
83516
+ inputs: [],
83517
+ outputs: [
83518
+ { type: "bool", name: "deposits" },
83519
+ { type: "bool", name: "withdrawals" },
83520
+ { type: "bool", name: "privilegedOperations" }
83521
+ ]
83522
+ }
83523
+ ];
83524
+
81619
83525
  // src/vaults/savings/readers/erc4626Idle.ts
81620
83526
  var readerErc4626Idle = (entry2) => {
81621
83527
  const shareUnit = 10n ** BigInt(entry2.decimals);
@@ -81969,7 +83875,7 @@ var readerHyperbeatVault = (entry2) => {
81969
83875
 
81970
83876
  // src/vaults/savings/readers/listaRwaPool.ts
81971
83877
  var PERIOD_SECONDS = 7n * 86400n;
81972
- var SECONDS_PER_YEAR20 = 365n * 86400n;
83878
+ var SECONDS_PER_YEAR21 = 365n * 86400n;
81973
83879
  var readerListaRwaPool = (entry2) => {
81974
83880
  const shareUnit = 10n ** BigInt(entry2.decimals);
81975
83881
  const underlyingUnit = 10n ** BigInt(entry2.underlyingDecimals ?? entry2.decimals);
@@ -82002,7 +83908,7 @@ var readerListaRwaPool = (entry2) => {
82002
83908
  const rewards = toBigInt16(periodRewards);
82003
83909
  const supplyRate = rewards !== void 0 && rewards > 0n && totalAssets > 0n ? (
82004
83910
  // percent, nominal: rewards per period → per year ÷ TVL.
82005
- Number(rewards * SECONDS_PER_YEAR20 * 1000000n / PERIOD_SECONDS) / Number(totalAssets) / 1e4
83911
+ Number(rewards * SECONDS_PER_YEAR21 * 1000000n / PERIOD_SECONDS) / Number(totalAssets) / 1e4
82006
83912
  ) : void 0;
82007
83913
  return {
82008
83914
  totalAssets,
@@ -82747,6 +84653,51 @@ var readerSuperformVault = (entry2) => {
82747
84653
  };
82748
84654
  };
82749
84655
 
84656
+ // src/vaults/savings/readers/emberVault.ts
84657
+ var NEUTRAL_PROBE4 = "0x000000000000000000000000000000000000dead";
84658
+ var readerEmberVault = (entry2) => {
84659
+ const shareUnit = 10n ** BigInt(entry2.decimals);
84660
+ const underlyingUnit = 10n ** BigInt(entry2.underlyingDecimals ?? entry2.decimals);
84661
+ return {
84662
+ calls: [
84663
+ { address: entry2.address, name: "totalAssets", params: [] },
84664
+ { address: entry2.address, name: "totalSupply", params: [] },
84665
+ { address: entry2.address, name: "convertToAssets", params: [shareUnit] },
84666
+ { address: entry2.address, name: "maxDeposit", params: [NEUTRAL_PROBE4] },
84667
+ { address: entry2.address, name: "pauseStatus", params: [] }
84668
+ ],
84669
+ abis: [
84670
+ Erc4626ReadAbi2,
84671
+ TotalSupplyAbi2,
84672
+ Erc4626ReadAbi2,
84673
+ EmberMaxDepositAbi,
84674
+ EmberPauseStatusAbi
84675
+ ],
84676
+ parse: ([assets, supply, rate, maxDeposit, pause]) => {
84677
+ const totalAssets = toBigInt16(assets);
84678
+ const totalSupply = toBigInt16(supply);
84679
+ const convertToAssetsRaw = toBigInt16(rate);
84680
+ if (totalAssets === void 0 || totalSupply === void 0 || convertToAssetsRaw === void 0)
84681
+ return void 0;
84682
+ const cap = toBigInt16(maxDeposit);
84683
+ const flags = Array.isArray(pause) ? pause : pause && typeof pause === "object" ? [
84684
+ pause.deposits,
84685
+ pause.withdrawals
84686
+ ] : void 0;
84687
+ const depositsPaused = typeof flags?.[0] === "boolean" ? flags[0] : void 0;
84688
+ const withdrawalsPaused = typeof flags?.[1] === "boolean" ? flags[1] : void 0;
84689
+ return {
84690
+ totalAssets,
84691
+ totalSupply,
84692
+ exchangeRate: convertToAssetsRaw * ONE_E1823 / underlyingUnit,
84693
+ ...cap !== void 0 ? { depositCapacity: cap } : {},
84694
+ ...withdrawalsPaused !== void 0 ? { exitPaused: withdrawalsPaused } : {},
84695
+ ...depositsPaused !== void 0 && withdrawalsPaused !== void 0 ? { paused: depositsPaused && withdrawalsPaused } : {}
84696
+ };
84697
+ }
84698
+ };
84699
+ };
84700
+
82750
84701
  // src/vaults/savings/readers/l2sD.ts
82751
84702
  var NavOracleAbi = [
82752
84703
  {
@@ -83032,7 +84983,7 @@ var readerUnitasXgld = (entry2) => {
83032
84983
  };
83033
84984
 
83034
84985
  // src/vaults/savings/readers/roycoTranche.ts
83035
- var NEUTRAL_PROBE4 = "0x000000000000000000000000000000000000dead";
84986
+ var NEUTRAL_PROBE5 = "0x000000000000000000000000000000000000dead";
83036
84987
  var ASSET_CLAIMS = {
83037
84988
  name: "claims",
83038
84989
  type: "tuple",
@@ -83135,7 +85086,7 @@ var readerRoycoTranche = (entry2) => {
83135
85086
  { address: entry2.address, name: "totalAssets", params: [] },
83136
85087
  { address: entry2.address, name: "totalSupply", params: [] },
83137
85088
  { address: entry2.address, name: "convertToAssets", params: [shareUnit] },
83138
- { address: entry2.address, name: "maxDeposit", params: [NEUTRAL_PROBE4] },
85089
+ { address: entry2.address, name: "maxDeposit", params: [NEUTRAL_PROBE5] },
83139
85090
  { address: entry2.address, name: "paused", params: [] },
83140
85091
  ...entryPoint ? [
83141
85092
  {
@@ -83620,6 +85571,8 @@ var buildReader2 = (entry2) => {
83620
85571
  return readerErc4626CooldownInstantFee(entry2);
83621
85572
  case "superform-supervault":
83622
85573
  return readerSuperformVault(entry2);
85574
+ case "ember-vault":
85575
+ return readerEmberVault(entry2);
83623
85576
  case "liminal-pipe":
83624
85577
  return readerLiminalPipe(entry2);
83625
85578
  case "veda-boring":
@@ -83894,7 +85847,10 @@ var fetchSavingsVaults = async (chainId, multicallRetry, prices = {}, tokenList
83894
85847
  // opposite and correctly falls through to `false`.
83895
85848
  entry2.reader === "bitfi-vault" || // SuperVaults ARE 4626 on the deposit side and 7540 on the exit, the
83896
85849
  // Lagoon / yoETH shape. NB `previewRedeem` reverts — see the reader.
83897
- entry2.reader === "superform-supervault" || // sBOLD and the Alchemix MYTs (Morpho Vault V2) are conforming 4626 on
85850
+ entry2.reader === "superform-supervault" || // Ember vaults are conforming 4626 VIEWS (`asset`, `totalAssets`,
85851
+ // `convertToAssets`) and deposit; `redeem`/`withdraw` revert
85852
+ // `UseRedeemShares()`, which the savings kind routes around.
85853
+ entry2.reader === "ember-vault" || // sBOLD and the Alchemix MYTs (Morpho Vault V2) are conforming 4626 on
83898
85854
  // both legs; their readers exist for the exit cap (SP BOLD / the
83899
85855
  // liquidity adapter) and sBOLD's collateral gate.
83900
85856
  entry2.reader === "sbold" || entry2.reader === "morpho-vault-v2",
@@ -83940,7 +85896,10 @@ var fetchSavingsVaults = async (chainId, multicallRetry, prices = {}, tokenList
83940
85896
  // savings row gets it without a per-provider change; the queued leg's
83941
85897
  // fee is left ABSENT rather than 0 because "not published" and "free"
83942
85898
  // are different claims and only some protocols make the second.
83943
- exitRoutes: withSelfOnly(
85899
+ // An exit the vault has switched off (Ember `pauseStatus().withdrawals`)
85900
+ // publishes no route at all — `fromVault` reads that as
85901
+ // `canWithdraw: false`, the same statement bfBTC's shut legs make.
85902
+ exitRoutes: state.exitPaused ? [] : withSelfOnly(
83944
85903
  bitfiExitRoutes(
83945
85904
  state.bitfiExit,
83946
85905
  state.withdrawalCooldownSeconds ?? entry2.withdrawalCooldownSeconds
@@ -83994,7 +85953,7 @@ var fetchSavingsVaults = async (chainId, multicallRetry, prices = {}, tokenList
83994
85953
  // src/vaults/savings/usualRewards.ts
83995
85954
  var USUAL_DISTRIBUTION_MODULE = "0x75cc0c0ddd2ccafe6ec415be686267588011e36a";
83996
85955
  var USUAL_REWARDS_API = "https://app.usual.money/api/rewards";
83997
- var ZERO8 = "0x0000000000000000000000000000000000000000";
85956
+ var ZERO9 = "0x0000000000000000000000000000000000000000";
83998
85957
  var fn = (name, inputs, outputs) => ({ name, type: "function", stateMutability: "view", inputs, outputs });
83999
85958
  var acct = [{ name: "account", type: "address" }];
84000
85959
  var UsualDistributionModuleReadAbi = [
@@ -84109,7 +86068,7 @@ var fetchUsualRewardsClaimData = async (account, multicallRetry, opts = {}) => {
84109
86068
  const sel = selectUsualRewardEntry(entries, root);
84110
86069
  if (sel.status !== "ok") return { ...sel, account: who };
84111
86070
  const claimable = sel.cumulative > claimedRaw ? sel.cumulative - claimedRaw : 0n;
84112
- const redirectTo = typeof redirect === "string" && redirect.toLowerCase() !== ZERO8 ? redirect.toLowerCase() : who;
86071
+ const redirectTo = typeof redirect === "string" && redirect.toLowerCase() !== ZERO9 ? redirect.toLowerCase() : who;
84113
86072
  return {
84114
86073
  status: "ok",
84115
86074
  account: who,
@@ -84199,7 +86158,7 @@ query LagoonVaults($where: VaultFilterInput!, $first: Int!, $skip: Int!) {
84199
86158
  }
84200
86159
  }
84201
86160
  }`;
84202
- var PAGE_SIZE3 = 200;
86161
+ var PAGE_SIZE4 = 200;
84203
86162
  async function fetchLagoonApiVaults(chainId) {
84204
86163
  const out = [];
84205
86164
  let skip = 0;
@@ -84211,7 +86170,7 @@ async function fetchLagoonApiVaults(chainId) {
84211
86170
  query: VAULTS_QUERY,
84212
86171
  variables: {
84213
86172
  where: { chainId_eq: Number(chainId), isVisible_eq: true },
84214
- first: PAGE_SIZE3,
86173
+ first: PAGE_SIZE4,
84215
86174
  skip
84216
86175
  }
84217
86176
  })
@@ -84229,8 +86188,8 @@ async function fetchLagoonApiVaults(chainId) {
84229
86188
  }
84230
86189
  const items = json?.data?.vaults?.items ?? [];
84231
86190
  out.push(...items);
84232
- if (items.length < PAGE_SIZE3) break;
84233
- skip += PAGE_SIZE3;
86191
+ if (items.length < PAGE_SIZE4) break;
86192
+ skip += PAGE_SIZE4;
84234
86193
  }
84235
86194
  return out;
84236
86195
  }
@@ -84244,7 +86203,7 @@ var pickApr = (apr) => {
84244
86203
  if (apr.inception != null) return { rate: apr.inception, window: "inception" };
84245
86204
  return { rate: 0, window: "none" };
84246
86205
  };
84247
- var num7 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
86206
+ var num8 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
84248
86207
  function parseVault7(v, chainId, prices, tokenList) {
84249
86208
  const address = (v?.address ?? "").toLowerCase();
84250
86209
  const assetAddr = (v?.asset?.address ?? "").toLowerCase();
@@ -84260,14 +86219,14 @@ function parseVault7(v, chainId, prices, tokenList) {
84260
86219
  parseRawAmount(totalAssetsRaw, assetDecimals)
84261
86220
  );
84262
86221
  const apr = {
84263
- weekly: num7(state.weeklyApr?.twrrNetApr),
84264
- monthly: num7(state.monthlyApr?.twrrNetApr),
84265
- yearly: num7(state.yearlyApr?.twrrNetApr),
84266
- inception: num7(state.inceptionApr?.twrrNetApr)
86222
+ weekly: num8(state.weeklyApr?.twrrNetApr),
86223
+ monthly: num8(state.monthlyApr?.twrrNetApr),
86224
+ yearly: num8(state.yearlyApr?.twrrNetApr),
86225
+ inception: num8(state.inceptionApr?.twrrNetApr)
84267
86226
  };
84268
86227
  const { rate: supplyRate, window: aprWindow } = pickApr(apr);
84269
86228
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
84270
- const apiTotalAssetsUsd = num7(state.totalAssetsUsd) ?? 0;
86229
+ const apiTotalAssetsUsd = num8(state.totalAssetsUsd) ?? 0;
84271
86230
  const impliedPriceUsd = totalAssetsFormatted > 0 ? apiTotalAssetsUsd / totalAssetsFormatted : 0;
84272
86231
  const priceUsd = prices[oracleKey] ?? prices[assetAddr] ?? impliedPriceUsd;
84273
86232
  const totalAssetsUsd = apiTotalAssetsUsd || totalAssetsFormatted * priceUsd;
@@ -84287,7 +86246,7 @@ function parseVault7(v, chainId, prices, tokenList) {
84287
86246
  totalAssets: totalAssetsRaw,
84288
86247
  totalSupply: totalSupplyRaw,
84289
86248
  pricePerShare: state.pricePerShare?.toString() ?? "0",
84290
- pricePerShareUsd: num7(state.pricePerShareUsd) ?? void 0,
86249
+ pricePerShareUsd: num8(state.pricePerShareUsd) ?? void 0,
84291
86250
  supplyRate,
84292
86251
  rewardsRate: 0,
84293
86252
  depositRate: supplyRate,
@@ -84350,7 +86309,7 @@ var Erc4626TotalAssetsAbi = [
84350
86309
 
84351
86310
  // src/vaults/aave-earn/api.ts
84352
86311
  var AAVE_EARN_API_URL = "https://api.v3.aave.com/graphql";
84353
- var PAGE_SIZE4 = "FIFTY";
86312
+ var PAGE_SIZE5 = "FIFTY";
84354
86313
  var VAULT_FIELDS = `
84355
86314
  address
84356
86315
  shareName
@@ -84408,7 +86367,7 @@ async function fetchAaveEarnApiVaults(chainId, targets) {
84408
86367
  for (let page = 0; page < 20; page++) {
84409
86368
  const request = {
84410
86369
  criteria: { ownedBy: [owner] },
84411
- pageSize: PAGE_SIZE4
86370
+ pageSize: PAGE_SIZE5
84412
86371
  };
84413
86372
  if (cursor) request.cursor = cursor;
84414
86373
  const data = await postGraphql(OWNED_VAULTS_QUERY, { request });
@@ -84484,7 +86443,7 @@ var toBigInt17 = (v) => {
84484
86443
  }
84485
86444
  return void 0;
84486
86445
  };
84487
- var num8 = (v) => {
86446
+ var num9 = (v) => {
84488
86447
  const n = Number(v);
84489
86448
  return Number.isFinite(n) ? n : 0;
84490
86449
  };
@@ -84541,12 +86500,12 @@ var fetchAaveEarnVaults = async (chainId, multicallRetry, prices = {}, tokenList
84541
86500
  const totalAssets = toBigInt17(slice2[0]) ?? totalSupply * convertToAssets / shareUnit;
84542
86501
  const totalAssetsFormatted = Number(totalAssets) / 10 ** assetDecimals;
84543
86502
  const asset = tokenList[underlyingLc];
84544
- const priceUsd = prices[underlyingLc] ?? (v.balance?.usdPerToken != null ? num8(v.balance.usdPerToken) : void 0);
86503
+ const priceUsd = prices[underlyingLc] ?? (v.balance?.usdPerToken != null ? num9(v.balance.usdPerToken) : void 0);
84545
86504
  const totalAssetsUsd = priceUsd !== void 0 ? totalAssetsFormatted * priceUsd : 0;
84546
- const supplyRate = num8(v.vaultApr?.formatted);
86505
+ const supplyRate = num9(v.vaultApr?.formatted);
84547
86506
  const rewardsRate = 0;
84548
86507
  const depositRate = supplyRate + rewardsRate;
84549
- const fee = num8(v.fee?.value);
86508
+ const fee = num9(v.fee?.value);
84550
86509
  const symbol = (v.shareSymbol ?? "").trim();
84551
86510
  const shareName = (v.shareName ?? "").trim();
84552
86511
  const name = shareName || symbol;
@@ -84652,7 +86611,7 @@ var V2_CALLS = [
84652
86611
  ];
84653
86612
  var FAILED = "0x";
84654
86613
  var ok3 = (v) => v !== void 0 && v !== null && v !== FAILED;
84655
- var big30 = (v) => {
86614
+ var big31 = (v) => {
84656
86615
  if (!ok3(v)) return void 0;
84657
86616
  try {
84658
86617
  return BigInt(v).toString();
@@ -84662,7 +86621,7 @@ var big30 = (v) => {
84662
86621
  };
84663
86622
  var addr2 = (v) => ok3(v) && /^0x[0-9a-fA-F]{40}$/.test(String(v)) ? String(v).toLowerCase() : void 0;
84664
86623
  var bool3 = (v) => typeof v === "boolean" ? v : void 0;
84665
- var ZERO9 = "0x0000000000000000000000000000000000000000";
86624
+ var ZERO10 = "0x0000000000000000000000000000000000000000";
84666
86625
  async function readUpshiftVaultsOnChain(chainId, vaults, multicallRetry) {
84667
86626
  const reads = /* @__PURE__ */ new Map();
84668
86627
  const failed = [];
@@ -84715,7 +86674,7 @@ async function readUpshiftVaultsOnChain(chainId, vaults, multicallRetry) {
84715
86674
  });
84716
86675
  }
84717
86676
  const wl = addr2(v.out.assetsWhitelistAddress);
84718
- if (wl && wl !== ZERO9)
86677
+ if (wl && wl !== ZERO10)
84719
86678
  r2Asks.push({
84720
86679
  address: wl,
84721
86680
  name: "getWhitelistedAssets",
@@ -84738,12 +86697,12 @@ async function readUpshiftVaultsOnChain(chainId, vaults, multicallRetry) {
84738
86697
  for (const v of named) {
84739
86698
  const o = v.out;
84740
86699
  const asset = addr2(o.asset);
84741
- const assetDecimals = Number(big30(r2By.get(`${v.address}:assetDecimals`)));
86700
+ const assetDecimals = Number(big31(r2By.get(`${v.address}:assetDecimals`)));
84742
86701
  const isV2 = v.version === "evm-2";
84743
86702
  const receipt = isV2 ? addr2(o.lpTokenAddress) : v.address.toLowerCase();
84744
- const receiptDecimals = isV2 ? Number(big30(r2By.get(`${v.address}:receiptDecimals`))) : Number(big30(o.decimals));
84745
- const totalAssets = big30(isV2 ? o.getTotalAssets : o.totalAssets);
84746
- const totalSupply = isV2 ? big30(r2By.get(`${v.address}:receiptSupply`)) : big30(o.totalSupply);
86703
+ const receiptDecimals = isV2 ? Number(big31(r2By.get(`${v.address}:receiptDecimals`))) : Number(big31(o.decimals));
86704
+ const totalAssets = big31(isV2 ? o.getTotalAssets : o.totalAssets);
86705
+ const totalSupply = isV2 ? big31(r2By.get(`${v.address}:receiptSupply`)) : big31(o.totalSupply);
84747
86706
  if (!asset || !receipt || !Number.isFinite(assetDecimals) || !Number.isFinite(receiptDecimals) || totalAssets === void 0 || totalSupply === void 0) {
84748
86707
  failed.push(v.address);
84749
86708
  continue;
@@ -84763,12 +86722,12 @@ async function readUpshiftVaultsOnChain(chainId, vaults, multicallRetry) {
84763
86722
  depositAssets: [...new Set(depositAssets)],
84764
86723
  totalAssets,
84765
86724
  totalSupply,
84766
- lagDuration: Number(big30(o.lagDuration) ?? 0),
86725
+ lagDuration: Number(big31(o.lagDuration) ?? 0),
84767
86726
  depositsPaused: bool3(o.depositsPaused),
84768
86727
  withdrawalsPaused: bool3(o.withdrawalsPaused),
84769
- depositCap: isV2 ? big30(o.depositCap) : void 0,
84770
- maxSupply: isV2 ? void 0 : big30(o.maxSupply),
84771
- maxDepositAmount: big30(o.maxDepositAmount)
86728
+ depositCap: isV2 ? big31(o.depositCap) : void 0,
86729
+ maxSupply: isV2 ? void 0 : big31(o.maxSupply),
86730
+ maxDepositAmount: big31(o.maxDepositAmount)
84772
86731
  });
84773
86732
  }
84774
86733
  return { reads, failed };
@@ -84976,7 +86935,7 @@ async function fetchUpshiftApiVaults(chainId, multicallRetry = multicallRetryUni
84976
86935
  }
84977
86936
 
84978
86937
  // src/vaults/upshift/fetchPublic.ts
84979
- var num9 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
86938
+ var num10 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
84980
86939
  var isEvmAddress = (a) => /^0x[0-9a-fA-F]{40}$/.test(a);
84981
86940
  var str4 = (v) => {
84982
86941
  const s = typeof v === "string" ? v.trim() : "";
@@ -85023,13 +86982,13 @@ function parseVault8(v, chainId, prices, tokenList) {
85023
86982
  );
85024
86983
  const realized = augustRealizedRate(v);
85025
86984
  const supplyRate = realized.rate ?? 0;
85026
- const campaign = num9(v.apy?.campaignApy);
86985
+ const campaign = num10(v.apy?.campaignApy);
85027
86986
  const rewardsRate = campaign != null ? apyToAprPercent(campaign) : 0;
85028
- const targetApy = num9(v.apy?.apy) ?? void 0;
86987
+ const targetApy = num10(v.apy?.apy) ?? void 0;
85029
86988
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
85030
- const apiTvlUsd = num9(v.latest_reported_tvl) ?? 0;
86989
+ const apiTvlUsd = num10(v.latest_reported_tvl) ?? 0;
85031
86990
  const impliedPriceUsd = totalAssetsFormatted > 0 ? apiTvlUsd / totalAssetsFormatted : 0;
85032
- const ownPrice = num9(prices[oracleKey]) ?? num9(prices[assetAddr]);
86991
+ const ownPrice = num10(prices[oracleKey]) ?? num10(prices[assetAddr]);
85033
86992
  const priceUsd = ownPrice ?? impliedPriceUsd;
85034
86993
  const totalAssetsUsd = ownPrice !== null ? totalAssetsFormatted * ownPrice : apiTvlUsd || totalAssetsFormatted * priceUsd;
85035
86994
  const totalSupplyFormatted = Number(parseRawAmount(totalSupplyRaw, decimals));
@@ -85038,15 +86997,15 @@ function parseVault8(v, chainId, prices, tokenList) {
85038
86997
  const symbol = (v.receipt?.symbol ?? "").trim();
85039
86998
  const strategist = (v.strategists ?? []).find((s) => str4(s?.name));
85040
86999
  const curatorName = str4(strategist?.name);
85041
- const performanceStanding = num9(v.fees?.performance) ?? 0;
85042
- const managementStanding = num9(v.fees?.management) ?? 0;
87000
+ const performanceStanding = num10(v.fees?.performance) ?? 0;
87001
+ const managementStanding = num10(v.fees?.management) ?? 0;
85043
87002
  const performanceWaived = v.fees?.isPerformanceWaived === true;
85044
87003
  const managementWaived = v.fees?.isManagementWaived === true;
85045
87004
  const instant = v.instant_redeem_config;
85046
87005
  const instantRedeemEnabled = !!instant && instant.isPaused !== true;
85047
87006
  const spreadBps = instantRedeemEnabled ? Math.max(
85048
87007
  0,
85049
- ...(instant?.redeemableAssets ?? []).map((a) => num9(a?.spreadBps) ?? 0)
87008
+ ...(instant?.redeemableAssets ?? []).map((a) => num10(a?.spreadBps) ?? 0)
85050
87009
  ) : void 0;
85051
87010
  return {
85052
87011
  address: receiptAddr,
@@ -85072,10 +87031,10 @@ function parseVault8(v, chainId, prices, tokenList) {
85072
87031
  depositRate: supplyRate + rewardsRate,
85073
87032
  sharePrice,
85074
87033
  apy: {
85075
- base: num9(v.apy?.apy),
87034
+ base: num10(v.apy?.apy),
85076
87035
  campaign,
85077
- points: num9(v.apy?.pointsApy),
85078
- underlying: num9(v.apy?.underlyingApy)
87036
+ points: num10(v.apy?.pointsApy),
87037
+ underlying: num10(v.apy?.underlyingApy)
85079
87038
  },
85080
87039
  curatorName,
85081
87040
  curatorLogoURI: str4(strategist?.logo),
@@ -85095,7 +87054,7 @@ function parseVault8(v, chainId, prices, tokenList) {
85095
87054
  performanceWaivedUntilDate: str4(v.fees?.performanceFeeWaivedUntilDate),
85096
87055
  managementWaivedUntilDate: str4(v.fees?.managementFeeWaivedUntilDate)
85097
87056
  },
85098
- withdrawalCooldownSeconds: num9(v.lagDuration) ?? 0,
87057
+ withdrawalCooldownSeconds: num10(v.lagDuration) ?? 0,
85099
87058
  ...instantRedeemEnabled ? {
85100
87059
  withdrawalMode: "fee-or-queued",
85101
87060
  withdrawFeeBps: spreadBps,
@@ -85212,9 +87171,9 @@ var asBig = (v) => {
85212
87171
  return null;
85213
87172
  }
85214
87173
  };
85215
- var num10 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
87174
+ var num11 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
85216
87175
  var toPct2 = (v) => {
85217
- const n = num10(v);
87176
+ const n = num11(v);
85218
87177
  return n == null ? 0 : n * 100;
85219
87178
  };
85220
87179
  var deriveTotalSupply = (totalAssetsRaw, pricePerShareRaw, decimals) => {
@@ -85246,19 +87205,19 @@ function parseVault9(v, chainId, prices, tokenList) {
85246
87205
  const totalAssetsFormatted = Number(
85247
87206
  parseRawAmount(totalAssetsRaw, assetDecimals)
85248
87207
  );
85249
- const month = num10(v.apr?.points?.monthAgo);
85250
- const week = num10(v.apr?.points?.weekAgo);
85251
- const netApr = num10(v.apr?.netAPR);
87208
+ const month = num11(v.apr?.points?.monthAgo);
87209
+ const week = num11(v.apr?.points?.weekAgo);
87210
+ const netApr = num11(v.apr?.netAPR);
85252
87211
  const realized = netApr === 0 && month === 0 && week != null && week > 0 ? week : netApr;
85253
- const forward = num10(v.apr?.forwardAPR?.netAPR);
87212
+ const forward = num11(v.apr?.forwardAPR?.netAPR);
85254
87213
  const isForwardApr = realized == null && forward != null;
85255
87214
  const supplyRate = toPct2(realized ?? forward);
85256
87215
  const rewardsRate = toPct2(v.apr?.extra?.stakingRewardsAPR);
85257
87216
  const fee = toPct2(v.apr?.fees?.performance);
85258
87217
  const oracleKey = toOracleKey(assetMeta?.assetGroup) ?? toGenericPriceKey(assetAddr, chainId);
85259
- const apiPrice = num10(v.tvl?.price) ?? 0;
87218
+ const apiPrice = num11(v.tvl?.price) ?? 0;
85260
87219
  const priceUsd = prices[oracleKey] ?? prices[assetAddr] ?? apiPrice;
85261
- const apiTvlUsd = num10(v.tvl?.tvl) ?? 0;
87220
+ const apiTvlUsd = num11(v.tvl?.tvl) ?? 0;
85262
87221
  const totalAssetsUsd = apiTvlUsd || totalAssetsFormatted * priceUsd;
85263
87222
  const name = (v.name ?? "").trim();
85264
87223
  const symbol = (v.symbol ?? "").trim();
@@ -86342,7 +88301,7 @@ var reserveFactorKey = (market, isLong) => keccak256(
86342
88301
  var USD_1E30 = 1e30;
86343
88302
  var USD_1E30N = 10n ** 30n;
86344
88303
  var GLV_NOMINAL_MARKET_COUNT = 20n;
86345
- var toUsd = (v) => typeof v === "bigint" ? Number(v) / USD_1E30 : 0;
88304
+ var toUsd2 = (v) => typeof v === "bigint" ? Number(v) / USD_1E30 : 0;
86346
88305
  var fetchGmxTickerPrices = async (chainId, apiUrlOverride) => {
86347
88306
  const host = apiUrlOverride ?? getGmxApiHost(chainId);
86348
88307
  const out = /* @__PURE__ */ new Map();
@@ -86438,31 +88397,31 @@ var priceGmMarkets = async (chainId, multicallRetry, markets, prices) => {
86438
88397
  const poolValue = info?.poolValue;
86439
88398
  if (typeof tokenPrice !== "bigint") return;
86440
88399
  const value = {
86441
- priceUsd: toUsd(tokenPrice),
86442
- tvlUsd: toUsd(poolValue)
88400
+ priceUsd: toUsd2(tokenPrice),
88401
+ tvlUsd: toUsd2(poolValue)
86443
88402
  };
86444
88403
  const longMax = price(prices, m.longToken)?.max;
86445
88404
  const shortMax = price(prices, m.shortToken)?.max;
86446
88405
  const indexMax = price(prices, m.indexToken)?.max;
86447
88406
  if (Array.isArray(dsRes) && longMax != null && shortMax != null) {
86448
88407
  const base = i * SLOTS;
86449
- const big31 = (j) => typeof dsRes[base + j] === "bigint" ? dsRes[base + j] : 0n;
88408
+ const big32 = (j) => typeof dsRes[base + j] === "bigint" ? dsRes[base + j] : 0n;
86450
88409
  const cap = computeDepositCapacityUsd(
86451
- [info?.longTokenAmount, longMax, big31(0), big31(2)],
86452
- [info?.shortTokenAmount, shortMax, big31(1), big31(3)]
88410
+ [info?.longTokenAmount, longMax, big32(0), big32(2)],
88411
+ [info?.shortTokenAmount, shortMax, big32(1), big32(3)]
86453
88412
  );
86454
88413
  if (cap != null) value.depositCapacityUsd = cap;
86455
88414
  if (indexMax != null) {
86456
88415
  const divisor = m.longToken.toLowerCase() === m.shortToken.toLowerCase() ? 2n : 1n;
86457
- const reservedUsdLong = (big31(4) + big31(5)) / divisor * indexMax;
86458
- const reservedUsdShort = (big31(6) + big31(7)) / divisor;
88416
+ const reservedUsdLong = (big32(4) + big32(5)) / divisor * indexMax;
88417
+ const reservedUsdShort = (big32(6) + big32(7)) / divisor;
86459
88418
  const liq = computeLiquidityUsd(
86460
88419
  info?.longTokenUsd,
86461
88420
  info?.shortTokenUsd,
86462
88421
  reservedUsdLong,
86463
88422
  reservedUsdShort,
86464
- big31(8),
86465
- big31(9)
88423
+ big32(8),
88424
+ big32(9)
86466
88425
  );
86467
88426
  if (liq != null)
86468
88427
  value.liquidityUsd = Math.max(0, Math.min(liq, value.tvlUsd));
@@ -86481,7 +88440,7 @@ var computeLiquidityUsd = (poolUsdLong, poolUsdShort, reservedUsdLong, reservedU
86481
88440
  return avail > 0n ? avail : 0n;
86482
88441
  };
86483
88442
  const total = side2(poolUsdLong, reservedUsdLong, reserveFactorLong) + side2(poolUsdShort, reservedUsdShort, reserveFactorShort);
86484
- return toUsd(total);
88443
+ return toUsd2(total);
86485
88444
  };
86486
88445
  var computeDepositCapacityUsd = (long, short) => {
86487
88446
  const INF = -1n;
@@ -86498,7 +88457,7 @@ var computeDepositCapacityUsd = (long, short) => {
86498
88457
  const l = side2(long);
86499
88458
  const s = side2(short);
86500
88459
  if (l == null && s == null) return void 0;
86501
- return toUsd((l ?? 0n) + (s ?? 0n));
88460
+ return toUsd2((l ?? 0n) + (s ?? 0n));
86502
88461
  };
86503
88462
  var priceGlvVaults = async (chainId, multicallRetry, glvTokens, prices, marketIndexToken) => {
86504
88463
  const values = /* @__PURE__ */ new Map();
@@ -86619,8 +88578,8 @@ var priceGlvVaults = async (chainId, multicallRetry, glvTokens, prices, marketIn
86619
88578
  const r = res[i];
86620
88579
  if (!Array.isArray(r) || typeof r[0] !== "bigint") return;
86621
88580
  values.set(glv.toLowerCase(), {
86622
- priceUsd: toUsd(r[0]),
86623
- tvlUsd: toUsd(r[1])
88581
+ priceUsd: toUsd2(r[0]),
88582
+ tvlUsd: toUsd2(r[1])
86624
88583
  });
86625
88584
  });
86626
88585
  pairs.forEach(({ glv, market }, i) => {
@@ -86661,27 +88620,27 @@ var fetchGmxExecutionFees = async (chainId, multicallRetry, gasPriceWei) => {
86661
88620
  } catch {
86662
88621
  return void 0;
86663
88622
  }
86664
- const big31 = (i) => typeof res[i] === "bigint" ? res[i] : 0n;
86665
- const base = big31(0);
86666
- const mult = big31(1);
88623
+ const big32 = (i) => typeof res[i] === "bigint" ? res[i] : 0n;
88624
+ const base = big32(0);
88625
+ const mult = big32(1);
86667
88626
  if (base === 0n && mult === 0n) return void 0;
86668
88627
  const PRECISION = 10n ** 30n;
86669
88628
  const adjusted = (opGas) => base + opGas * mult / PRECISION;
86670
88629
  const fee = (opGas) => (adjusted(opGas) * gasPriceWei).toString();
86671
- const glvExtra = big31(6) * GLV_NOMINAL_MARKET_COUNT;
88630
+ const glvExtra = big32(6) * GLV_NOMINAL_MARKET_COUNT;
86672
88631
  return {
86673
88632
  chainId,
86674
88633
  gasPriceWei: gasPriceWei.toString(),
86675
- deposit: fee(big31(2)),
86676
- withdrawal: fee(big31(3)),
86677
- glvDeposit: fee(big31(4) + glvExtra),
86678
- glvWithdrawal: fee(big31(5) + glvExtra)
88634
+ deposit: fee(big32(2)),
88635
+ withdrawal: fee(big32(3)),
88636
+ glvDeposit: fee(big32(4) + glvExtra),
88637
+ glvWithdrawal: fee(big32(5) + glvExtra)
86679
88638
  };
86680
88639
  };
86681
88640
 
86682
88641
  // src/vaults/gmx/fetchPublic.ts
86683
88642
  var GMX_TOKEN_DECIMALS = 18;
86684
- var num11 = (n) => typeof n === "number" && Number.isFinite(n) ? n : 0;
88643
+ var num12 = (n) => typeof n === "number" && Number.isFinite(n) ? n : 0;
86685
88644
  var minDefined = (a, b) => a == null ? b : b == null ? a : Math.min(a, b);
86686
88645
  var glvMarketRoomUsd = (cap, priceUsd) => {
86687
88646
  const currentUsd = Number(cap.balanceAmount) / 1e18 * priceUsd;
@@ -86715,9 +88674,9 @@ var fetchGmxVaults = async (chainId, multicallRetry, options) => {
86715
88674
  indexToken: indexToken ? indexToken.toLowerCase() : void 0,
86716
88675
  longSymbol,
86717
88676
  shortSymbol,
86718
- apy: num11(entry2?.apy),
86719
- baseApy: num11(entry2?.baseApy),
86720
- bonusApr: num11(entry2?.bonusApr),
88677
+ apy: num12(entry2?.apy),
88678
+ baseApy: num12(entry2?.baseApy),
88679
+ bonusApr: num12(entry2?.bonusApr),
86721
88680
  yieldProfile: "volatile",
86722
88681
  denomination: denominationFor(longSymbol, shortSymbol)
86723
88682
  };
@@ -87081,14 +89040,14 @@ function isLiveMarket(market, nowSecs = Math.floor(Date.now() / 1e3)) {
87081
89040
  if (expiry === void 0) return false;
87082
89041
  return expiry > nowSecs;
87083
89042
  }
87084
- var CACHE_TTL_MS10 = 6e4;
89043
+ var CACHE_TTL_MS11 = 6e4;
87085
89044
  var marketsCache;
87086
89045
  var assetsCache;
87087
89046
  function clearPendleMarketsCache() {
87088
89047
  marketsCache = void 0;
87089
89048
  assetsCache = void 0;
87090
89049
  }
87091
- async function getJson7(url, label) {
89050
+ async function getJson8(url, label) {
87092
89051
  const response = await fetch(url, { headers: { Accept: "application/json" } });
87093
89052
  if (!response.ok) {
87094
89053
  throw new Error(
@@ -87099,7 +89058,7 @@ async function getJson7(url, label) {
87099
89058
  }
87100
89059
  function cache5(slot, build9, store) {
87101
89060
  const now = Date.now();
87102
- if (slot && now - slot.at < CACHE_TTL_MS10) return slot.promise;
89061
+ if (slot && now - slot.at < CACHE_TTL_MS11) return slot.promise;
87103
89062
  const promise = build9();
87104
89063
  const entry2 = { at: now, promise };
87105
89064
  store(entry2);
@@ -87109,7 +89068,7 @@ function cache5(slot, build9, store) {
87109
89068
  function fetchPendleApiMarkets() {
87110
89069
  return cache5(
87111
89070
  marketsCache,
87112
- async () => (await getJson7(PENDLE_MARKETS_URL2, "markets"))?.markets ?? [],
89071
+ async () => (await getJson8(PENDLE_MARKETS_URL2, "markets"))?.markets ?? [],
87113
89072
  (c) => {
87114
89073
  marketsCache = c;
87115
89074
  }
@@ -87120,7 +89079,7 @@ function fetchPendleApiAssets() {
87120
89079
  return cache5(
87121
89080
  assetsCache,
87122
89081
  async () => {
87123
- const json = await getJson7(PENDLE_ASSETS_URL, "assets");
89082
+ const json = await getJson8(PENDLE_ASSETS_URL, "assets");
87124
89083
  const map = /* @__PURE__ */ new Map();
87125
89084
  for (const a of json?.assets ?? []) {
87126
89085
  if (a?.chainId == null || !a?.address) continue;
@@ -87136,9 +89095,9 @@ function fetchPendleApiAssets() {
87136
89095
 
87137
89096
  // src/vaults/pendle/fetchPublic.ts
87138
89097
  var SECONDS_PER_DAY2 = 86400;
87139
- var num12 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
89098
+ var num13 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
87140
89099
  var fractionToPercent = (v) => {
87141
- const n = num12(v);
89100
+ const n = num13(v);
87142
89101
  return n === null ? null : n * 100;
87143
89102
  };
87144
89103
  function resolveToken(address, chainId, tokenList, apiAssets, decimalsOnChain) {
@@ -87185,8 +89144,8 @@ function parseMarket2(m, chainId, prices, tokenList, apiAssets, decimalsOnChain,
87185
89144
  const impliedApyPercent = fractionToPercent(details.impliedApy) ?? 0;
87186
89145
  const supplyRate = apyToAprPercent(impliedApyPercent);
87187
89146
  const underlyingApyPercent = fractionToPercent(details.underlyingApy);
87188
- const totalAssetsUsd = num12(details.totalTvl) ?? 0;
87189
- const liquidityUsd = num12(details.liquidity) ?? 0;
89147
+ const totalAssetsUsd = num13(details.totalTvl) ?? 0;
89148
+ const liquidityUsd = num13(details.liquidity) ?? 0;
87190
89149
  const priceKey = toOracleKey(assetMeta.assetGroup ?? null) || toGenericPriceKey(underlying.address, chainId);
87191
89150
  const priceUsd = prices[priceKey] ?? prices[underlying.address];
87192
89151
  const ptPriceKey = toOracleKey(ptMeta.assetGroup ?? null) || toGenericPriceKey(pt.address, chainId);
@@ -87213,7 +89172,7 @@ function parseMarket2(m, chainId, prices, tokenList, apiAssets, decimalsOnChain,
87213
89172
  depositRate: supplyRate,
87214
89173
  impliedApyPercent,
87215
89174
  underlyingApyPercent: underlyingApyPercent ?? void 0,
87216
- feeRate: num12(details.feeRate) ?? void 0,
89175
+ feeRate: num13(details.feeRate) ?? void 0,
87217
89176
  totalAssetsUsd,
87218
89177
  totalAssetsFormatted: totalAssetsUsd,
87219
89178
  liquidityUsd,
@@ -87368,7 +89327,7 @@ function parsePtRate(raw) {
87368
89327
  if (!Number.isFinite(n) || n < 0 || n > 1.000001) return void 0;
87369
89328
  return n;
87370
89329
  }
87371
- var CACHE_TTL_MS11 = 6e4;
89330
+ var CACHE_TTL_MS12 = 6e4;
87372
89331
  var cache6 = /* @__PURE__ */ new Map();
87373
89332
  function clearSpectraMarketsCache() {
87374
89333
  cache6.clear();
@@ -87378,7 +89337,7 @@ function fetchSpectraApiMarkets(chainId) {
87378
89337
  if (!network) return Promise.resolve([]);
87379
89338
  const now = Date.now();
87380
89339
  const hit = cache6.get(network);
87381
- if (hit && now - hit.at < CACHE_TTL_MS11) return hit.promise;
89340
+ if (hit && now - hit.at < CACHE_TTL_MS12) return hit.promise;
87382
89341
  const promise = (async () => {
87383
89342
  const response = await fetch(spectraPoolsUrl(network), {
87384
89343
  headers: { Accept: "application/json" }
@@ -87400,7 +89359,7 @@ function fetchSpectraApiMarkets(chainId) {
87400
89359
 
87401
89360
  // src/vaults/spectra/fetchPublic.ts
87402
89361
  var SECONDS_PER_DAY3 = 86400;
87403
- var num13 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
89362
+ var num14 = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
87404
89363
  function resolveToken2(address, apiToken, tokenList, decimalsOnChain) {
87405
89364
  const listed = address ? tokenList[address] : void 0;
87406
89365
  const apiDecimals = typeof apiToken?.decimals === "number" && Number.isFinite(apiToken.decimals) ? apiToken.decimals : void 0;
@@ -87416,7 +89375,7 @@ function parseMarket3(m, chainId, prices, tokenList, decimalsOnChain, nowSecs) {
87416
89375
  const ptAddress = spectraAddress(m.address);
87417
89376
  const underlyingAddress = spectraAddress(m.underlying?.address);
87418
89377
  if (!ptAddress || !underlyingAddress) return null;
87419
- const maturity = num13(m.maturity);
89378
+ const maturity = num14(m.maturity);
87420
89379
  if (maturity === null) return null;
87421
89380
  const pool = pickPool(m.pools);
87422
89381
  if (!pool) return null;
@@ -87449,12 +89408,12 @@ function parseMarket3(m, chainId, prices, tokenList, decimalsOnChain, nowSecs) {
87449
89408
  const supplyRate = apyToAprPercent(impliedApyPercent);
87450
89409
  const priceKey = toOracleKey(assetMeta.assetGroup ?? null) || toGenericPriceKey(underlyingAddress, chainId);
87451
89410
  const priceUsd = prices[priceKey] ?? prices[underlyingAddress];
87452
- const totalAssetsUnderlying = num13(m.tvl?.underlying) ?? void 0;
87453
- const totalAssetsUsd = num13(m.tvl?.usd) ?? (totalAssetsUnderlying !== void 0 && priceUsd !== void 0 ? totalAssetsUnderlying * priceUsd : 0);
87454
- const liquidityUnderlying = num13(pool.liquidity?.underlying);
87455
- const liquidityUsd = num13(pool.liquidity?.usd) ?? (liquidityUnderlying !== null && priceUsd !== void 0 ? liquidityUnderlying * priceUsd : 0);
89411
+ const totalAssetsUnderlying = num14(m.tvl?.underlying) ?? void 0;
89412
+ const totalAssetsUsd = num14(m.tvl?.usd) ?? (totalAssetsUnderlying !== void 0 && priceUsd !== void 0 ? totalAssetsUnderlying * priceUsd : 0);
89413
+ const liquidityUnderlying = num14(pool.liquidity?.underlying);
89414
+ const liquidityUsd = num14(pool.liquidity?.usd) ?? (liquidityUnderlying !== null && priceUsd !== void 0 ? liquidityUnderlying * priceUsd : 0);
87456
89415
  const ptPriceKey = toOracleKey(ptMeta.assetGroup ?? null) || toGenericPriceKey(ptAddress, chainId);
87457
- const ptPriceUsd = prices[ptPriceKey] ?? prices[ptAddress] ?? num13(pool.ptPrice?.usd) ?? void 0;
89416
+ const ptPriceUsd = prices[ptPriceKey] ?? prices[ptAddress] ?? num14(pool.ptPrice?.usd) ?? void 0;
87458
89417
  const secondsToExpiry = Math.max(maturity - nowSecs, 0);
87459
89418
  return {
87460
89419
  address: ptAddress,
@@ -87504,7 +89463,7 @@ function parseMarket3(m, chainId, prices, tokenList, decimalsOnChain, nowSecs) {
87504
89463
  } : void 0),
87505
89464
  priceUsd,
87506
89465
  ptPriceUsd,
87507
- ptPriceUnderlying: num13(pool.ptPrice?.underlying) ?? void 0,
89466
+ ptPriceUnderlying: num14(pool.ptPrice?.underlying) ?? void 0,
87508
89467
  categoryIds: Array.isArray(m.tags) ? m.tags : void 0,
87509
89468
  protocol: m.ibt?.protocol ?? void 0
87510
89469
  };
@@ -91101,7 +93060,7 @@ function resolveEarnIdentity(venue, brand, publishedProtocol) {
91101
93060
  }
91102
93061
  return { protocol: { key: key5, name: protocolName }, curator: { name } };
91103
93062
  }
91104
- function num14(v) {
93063
+ function num15(v) {
91105
93064
  if (v == null || v === "") return void 0;
91106
93065
  const n = typeof v === "number" ? v : Number(v);
91107
93066
  return Number.isFinite(n) ? n : void 0;
@@ -91201,8 +93160,8 @@ function resolveExitMode2(provider, meta, tvl, liq) {
91201
93160
  if (declared) return declared;
91202
93161
  const fallback = vaultTraits(provider)?.defaultExitMode ?? "instant";
91203
93162
  if (fallback !== "instant-capped") return fallback;
91204
- const total = num14(tvl?.totalAssetsFormatted) ?? num14(tvl?.totalAssetsUsd);
91205
- const available = num14(liq?.liquidityFormatted) ?? num14(liq?.liquidityUsd);
93163
+ const total = num15(tvl?.totalAssetsFormatted) ?? num15(tvl?.totalAssetsUsd);
93164
+ const available = num15(liq?.liquidityFormatted) ?? num15(liq?.liquidityUsd);
91206
93165
  if (total === void 0 || available === void 0) return "instant-capped";
91207
93166
  if (total <= 0) return "instant";
91208
93167
  return available >= total ? "instant" : "instant-capped";
@@ -91240,8 +93199,8 @@ function earnMarketFromVault(row, chainId, opts = {}) {
91240
93199
  const rates = row.rates ?? {};
91241
93200
  const tvl = row.tvl ?? {};
91242
93201
  const liq = row.liquidity ?? {};
91243
- const shareDecimals = num14(row.decimals) ?? 18;
91244
- const assetDecimals = num14(row.assetDecimals) ?? num14(row.underlyingInfo?.asset?.decimals) ?? shareDecimals;
93202
+ const shareDecimals = num15(row.decimals) ?? 18;
93203
+ const assetDecimals = num15(row.assetDecimals) ?? num15(row.underlyingInfo?.asset?.decimals) ?? shareDecimals;
91245
93204
  const rateUnavailable = isRateSourceUnavailable(str6(meta.rateSource));
91246
93205
  const toPercent2 = (v) => rateUnavailable ? void 0 : ratePercent(v, provider, opts.fractionRateProviders);
91247
93206
  const rewards = toPercent2(rates.rewardsRate);
@@ -91331,7 +93290,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
91331
93290
  symbol: str6(row.underlyingInfo?.asset?.symbol) ?? "",
91332
93291
  decimals: assetDecimals,
91333
93292
  assetGroup: str6(info.assetGroup),
91334
- priceUsd: num14(row.underlyingInfo?.prices?.priceUsd)
93293
+ priceUsd: num15(row.underlyingInfo?.prices?.priceUsd)
91335
93294
  },
91336
93295
  // The vault IS a share token by construction; carry it so a withdraw in
91337
93296
  // share units can be built without a second lookup.
@@ -91361,8 +93320,8 @@ function earnMarketFromVault(row, chainId, opts = {}) {
91361
93320
  exit: {
91362
93321
  mode: exitMode,
91363
93322
  settlement: str6(meta.redemptionType),
91364
- cooldownSecs: num14(meta.withdrawalCooldownSeconds),
91365
- feeBps: num14(meta.withdrawFeeBps),
93323
+ cooldownSecs: num15(meta.withdrawalCooldownSeconds),
93324
+ feeBps: num15(meta.withdrawFeeBps),
91366
93325
  // Passed through, never re-derived: the earn row and the vault row must
91367
93326
  // not disagree about what the legs out are.
91368
93327
  routes: Array.isArray(meta.exitRoutes) ? meta.exitRoutes : void 0
@@ -91375,12 +93334,12 @@ function earnMarketFromVault(row, chainId, opts = {}) {
91375
93334
  // since the surface was written and never populated — a tranche's
91376
93335
  // first-loss position is the term most worth surfacing on a rate list.
91377
93336
  counterparty: str6(meta.solvency),
91378
- score: num14(row.rating?.score),
93337
+ score: num15(row.rating?.score),
91379
93338
  label: str6(row.rating?.level),
91380
93339
  illiquid: isIlliquid({
91381
93340
  exitMode,
91382
- tvlUsd: num14(tvl.totalAssetsUsd),
91383
- liquidityUsd: num14(liq.liquidityUsd)
93341
+ tvlUsd: num15(tvl.totalAssetsUsd),
93342
+ liquidityUsd: num15(liq.liquidityUsd)
91384
93343
  })
91385
93344
  },
91386
93345
  // Filled by `capabilities.ts` — kept required on the type so a normalizer
@@ -91392,7 +93351,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
91392
93351
  return market;
91393
93352
  }
91394
93353
  function ratePercent(value, provider, fractionProviders = FRACTION_RATE_PROVIDERS) {
91395
- const n = num14(value);
93354
+ const n = num15(value);
91396
93355
  if (n === void 0) return void 0;
91397
93356
  return fractionProviders.has(provider) ? n * 100 : n;
91398
93357
  }
@@ -91452,7 +93411,7 @@ function vaultDisplayName(row, info) {
91452
93411
  return str6(row.name) ?? str6(info.name) ?? str6(row.displayName) ?? str6(share?.name) ?? str6(share?.symbol) ?? str6(info.symbol) ?? str6(row.symbol);
91453
93412
  }
91454
93413
  function resolveMaturity(meta) {
91455
- const expiry = num14(meta.expiry) ?? num14(meta.maturity);
93414
+ const expiry = num15(meta.expiry) ?? num15(meta.maturity);
91456
93415
  if (expiry === void 0 || expiry <= 0) return void 0;
91457
93416
  const nowSecs = Math.floor(Date.now() / 1e3);
91458
93417
  return {
@@ -91492,8 +93451,8 @@ function amount3(raw, formatted, usd, decimals) {
91492
93451
  const rawStr = raw != null ? String(raw) : void 0;
91493
93452
  return {
91494
93453
  raw: rawStr,
91495
- formatted: num14(formatted) ?? formatRaw(rawStr, decimals),
91496
- usd: num14(usd)
93454
+ formatted: num15(formatted) ?? formatRaw(rawStr, decimals),
93455
+ usd: num15(usd)
91497
93456
  };
91498
93457
  }
91499
93458
  function withCuratorEntity(id, entity) {
@@ -91506,7 +93465,7 @@ function sum(a, b) {
91506
93465
  }
91507
93466
 
91508
93467
  // src/terms/vault/input.ts
91509
- var num15 = (v) => {
93468
+ var num16 = (v) => {
91510
93469
  if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
91511
93470
  if (typeof v === "string" && v.trim() !== "") {
91512
93471
  const n = Number(v);
@@ -91537,13 +93496,13 @@ var fromRaw = (raw, decimals) => {
91537
93496
  function sdkRates(row, provider) {
91538
93497
  if (!SDK_FRACTION_RATE_PROVIDERS.has(provider)) {
91539
93498
  return {
91540
- supplyRate: num15(row.supplyRate),
91541
- rewardsRate: num15(row.rewardsRate),
91542
- totalRate: num15(row.depositRate)
93499
+ supplyRate: num16(row.supplyRate),
93500
+ rewardsRate: num16(row.rewardsRate),
93501
+ totalRate: num16(row.depositRate)
91543
93502
  };
91544
93503
  }
91545
93504
  const pct5 = (v) => {
91546
- const n = num15(v);
93505
+ const n = num16(v);
91547
93506
  return n === void 0 ? void 0 : n * 100;
91548
93507
  };
91549
93508
  return {
@@ -91557,7 +93516,7 @@ function toVaultTermInput(vault, provider, chainId) {
91557
93516
  const row = vault;
91558
93517
  const address = str7(row.address)?.toLowerCase();
91559
93518
  if (!address) return void 0;
91560
- const assetDecimals = num15(row.assetDecimals) ?? num15(row.decimals);
93519
+ const assetDecimals = num16(row.assetDecimals) ?? num16(row.decimals);
91561
93520
  const asset = row.asset;
91562
93521
  return {
91563
93522
  provider,
@@ -91583,23 +93542,23 @@ function toVaultTermInput(vault, provider, chainId) {
91583
93542
  // GMX / HyperCore / Pendle report USD only and set the token-denominated
91584
93543
  // fields to their USD figure — `totalAssetsFormatted` is the cross-provider
91585
93544
  // magnitude either way, so prefer it over re-deriving from raw.
91586
- totalAssets: num15(row.totalAssetsFormatted) ?? fromRaw(row.totalAssets, assetDecimals),
91587
- totalAssetsUsd: num15(row.totalAssetsUsd) ?? num15(row.tvlUsd),
91588
- liquidity: num15(row.liquidityFormatted) ?? fromRaw(row.liquidity, assetDecimals),
91589
- liquidityUsd: num15(row.liquidityUsd),
91590
- instantLiquidityRatio: num15(row.instantLiquidityRatio),
93545
+ totalAssets: num16(row.totalAssetsFormatted) ?? fromRaw(row.totalAssets, assetDecimals),
93546
+ totalAssetsUsd: num16(row.totalAssetsUsd) ?? num16(row.tvlUsd),
93547
+ liquidity: num16(row.liquidityFormatted) ?? fromRaw(row.liquidity, assetDecimals),
93548
+ liquidityUsd: num16(row.liquidityUsd),
93549
+ instantLiquidityRatio: num16(row.instantLiquidityRatio),
91591
93550
  totalBorrowed: fromRaw(row.totalBorrowed, assetDecimals),
91592
93551
  expectedLiquidity: fromRaw(row.expectedLiquidity, assetDecimals),
91593
93552
  withdrawalMode: str7(row.withdrawalMode),
91594
- withdrawalCooldownSeconds: num15(row.withdrawalCooldownSeconds),
91595
- withdrawFeeBps: num15(row.withdrawFeeBps),
93553
+ withdrawalCooldownSeconds: num16(row.withdrawalCooldownSeconds),
93554
+ withdrawFeeBps: num16(row.withdrawFeeBps),
91596
93555
  exitRoutes: routes(row.exitRoutes),
91597
- fee: num15(row.fee),
91598
- managementFee: num15(row.managementFee),
91599
- swapFeeRate: num15(row.feeRate),
91600
- redemptionDiscountBps: num15(row.redemptionDiscountBps),
93556
+ fee: num16(row.fee),
93557
+ managementFee: num16(row.managementFee),
93558
+ swapFeeRate: num16(row.feeRate),
93559
+ redemptionDiscountBps: num16(row.redemptionDiscountBps),
91601
93560
  instantRedeemEnabled: bool4(row.instantRedeemEnabled),
91602
- yieldWarmupSeconds: num15(row.yieldWarmupSeconds),
93561
+ yieldWarmupSeconds: num16(row.yieldWarmupSeconds),
91603
93562
  accrual: str7(row.accrual),
91604
93563
  needsDepositApproval: bool4(row.needsDepositApproval),
91605
93564
  isMintable: bool4(row.isMintable),
@@ -91610,8 +93569,8 @@ function toVaultTermInput(vault, provider, chainId) {
91610
93569
  withdrawalsPaused: bool4(row.isWithdrawalPaused),
91611
93570
  isClosed: bool4(row.isClosed),
91612
93571
  whitelisted: bool4(row.whitelisted),
91613
- expiry: num15(row.expiry),
91614
- timelock: num15(row.timelock),
93572
+ expiry: num16(row.expiry),
93573
+ timelock: num16(row.timelock),
91615
93574
  allocators: strArray(row.allocators),
91616
93575
  owner: str7(row.owner),
91617
93576
  curator: str7(row.curator),
@@ -91673,19 +93632,19 @@ function vaultTermInputFromEarnMarket(m) {
91673
93632
  totalAssetsUsd: m.tvl.usd,
91674
93633
  liquidity: m.liquidity?.formatted,
91675
93634
  liquidityUsd: m.liquidity?.usd,
91676
- instantLiquidityRatio: num15(meta.instantLiquidityRatio),
91677
- totalBorrowed: num15(meta.totalBorrowed),
91678
- expectedLiquidity: num15(meta.expectedLiquidity),
93635
+ instantLiquidityRatio: num16(meta.instantLiquidityRatio),
93636
+ totalBorrowed: num16(meta.totalBorrowed),
93637
+ expectedLiquidity: num16(meta.expectedLiquidity),
91679
93638
  withdrawalMode: m.exit.mode,
91680
93639
  withdrawalCooldownSeconds: m.exit.cooldownSecs,
91681
93640
  withdrawFeeBps: m.exit.feeBps,
91682
93641
  exitRoutes: routes(m.exit.routes),
91683
93642
  fee: m.rate.fee,
91684
- managementFee: num15(meta.managementFee),
91685
- swapFeeRate: num15(meta.feeRate),
91686
- redemptionDiscountBps: num15(meta.redemptionDiscountBps),
93643
+ managementFee: num16(meta.managementFee),
93644
+ swapFeeRate: num16(meta.feeRate),
93645
+ redemptionDiscountBps: num16(meta.redemptionDiscountBps),
91687
93646
  instantRedeemEnabled: bool4(meta.instantRedeemEnabled),
91688
- yieldWarmupSeconds: num15(meta.yieldWarmupSeconds) ?? curated.yieldWarmupSeconds,
93647
+ yieldWarmupSeconds: num16(meta.yieldWarmupSeconds) ?? curated.yieldWarmupSeconds,
91689
93648
  accrual: str7(meta.accrual) ?? curated.accrual,
91690
93649
  needsDepositApproval: bool4(meta.needsDepositApproval) ?? curated.needsDepositApproval,
91691
93650
  // `canDeposit` already folds in the cap, the pause and the gate, so it is
@@ -91699,7 +93658,7 @@ function vaultTermInputFromEarnMarket(m) {
91699
93658
  isClosed: bool4(meta.isClosed),
91700
93659
  whitelisted: bool4(meta.whitelisted),
91701
93660
  expiry: m.maturity?.maturity ?? curated.expiry,
91702
- timelock: num15(meta.timelock),
93661
+ timelock: num16(meta.timelock),
91703
93662
  allocators: strArray(meta.allocators),
91704
93663
  owner: str7(meta.owner),
91705
93664
  curator: str7(meta.curator),
@@ -91712,13 +93671,13 @@ function vaultTermInputFromEarnMarket(m) {
91712
93671
  };
91713
93672
  }
91714
93673
  function originRates(rates) {
91715
- const supply = num15(rates.supplyRate);
91716
- const rewards = num15(rates.rewardsRate);
91717
- const deposit = num15(rates.depositRate);
93674
+ const supply = num16(rates.supplyRate);
93675
+ const rewards = num16(rates.rewardsRate);
93676
+ const deposit = num16(rates.depositRate);
91718
93677
  return {
91719
93678
  supplyRate: supply ?? (deposit !== void 0 && rewards !== void 0 ? deposit - rewards : deposit),
91720
93679
  rewardsRate: rewards,
91721
- totalRate: num15(rates.totalRate) ?? deposit
93680
+ totalRate: num16(rates.totalRate) ?? deposit
91722
93681
  };
91723
93682
  }
91724
93683
  function vaultTermInputFromSourceRow(row, chainId) {
@@ -91731,7 +93690,7 @@ function vaultTermInputFromSourceRow(row, chainId) {
91731
93690
  const liq = row.liquidity ?? {};
91732
93691
  const info = row.vaultInfo ?? {};
91733
93692
  const assetInfo = row.underlyingInfo?.asset;
91734
- const assetDecimals = num15(row.assetDecimals) ?? num15(assetInfo?.decimals) ?? num15(row.decimals);
93693
+ const assetDecimals = num16(row.assetDecimals) ?? num16(assetInfo?.decimals) ?? num16(row.decimals);
91735
93694
  const curated = savingsCuration(provider, chainId, address);
91736
93695
  return {
91737
93696
  provider,
@@ -91753,23 +93712,23 @@ function vaultTermInputFromSourceRow(row, chainId) {
91753
93712
  ...originRates(rates),
91754
93713
  isForwardApr: bool4(meta.isForwardApr),
91755
93714
  aprWindow: str7(meta.aprWindow),
91756
- totalAssets: num15(tvl.totalAssetsFormatted) ?? fromRaw(tvl.totalAssets, assetDecimals),
91757
- totalAssetsUsd: num15(tvl.totalAssetsUsd),
91758
- liquidity: num15(liq.liquidityFormatted) ?? fromRaw(liq.liquidity, assetDecimals),
91759
- liquidityUsd: num15(liq.liquidityUsd),
91760
- instantLiquidityRatio: num15(meta.instantLiquidityRatio),
93715
+ totalAssets: num16(tvl.totalAssetsFormatted) ?? fromRaw(tvl.totalAssets, assetDecimals),
93716
+ totalAssetsUsd: num16(tvl.totalAssetsUsd),
93717
+ liquidity: num16(liq.liquidityFormatted) ?? fromRaw(liq.liquidity, assetDecimals),
93718
+ liquidityUsd: num16(liq.liquidityUsd),
93719
+ instantLiquidityRatio: num16(meta.instantLiquidityRatio),
91761
93720
  totalBorrowed: fromRaw(meta.totalBorrowed, assetDecimals),
91762
93721
  expectedLiquidity: fromRaw(meta.expectedLiquidity, assetDecimals),
91763
93722
  withdrawalMode: str7(meta.withdrawalMode),
91764
- withdrawalCooldownSeconds: num15(meta.withdrawalCooldownSeconds),
91765
- withdrawFeeBps: num15(meta.withdrawFeeBps),
93723
+ withdrawalCooldownSeconds: num16(meta.withdrawalCooldownSeconds),
93724
+ withdrawFeeBps: num16(meta.withdrawFeeBps),
91766
93725
  exitRoutes: routes(meta.exitRoutes),
91767
- fee: num15(rates.fee),
91768
- managementFee: num15(meta.managementFee),
91769
- swapFeeRate: num15(meta.feeRate),
91770
- redemptionDiscountBps: num15(meta.redemptionDiscountBps),
93726
+ fee: num16(rates.fee),
93727
+ managementFee: num16(meta.managementFee),
93728
+ swapFeeRate: num16(meta.feeRate),
93729
+ redemptionDiscountBps: num16(meta.redemptionDiscountBps),
91771
93730
  instantRedeemEnabled: bool4(meta.instantRedeemEnabled),
91772
- yieldWarmupSeconds: num15(meta.yieldWarmupSeconds) ?? curated.yieldWarmupSeconds,
93731
+ yieldWarmupSeconds: num16(meta.yieldWarmupSeconds) ?? curated.yieldWarmupSeconds,
91773
93732
  accrual: str7(meta.accrual) ?? curated.accrual,
91774
93733
  needsDepositApproval: bool4(meta.needsDepositApproval) ?? curated.needsDepositApproval,
91775
93734
  isMintable: bool4(meta.isMintable),
@@ -91780,8 +93739,8 @@ function vaultTermInputFromSourceRow(row, chainId) {
91780
93739
  withdrawalsPaused: bool4(meta.isWithdrawalPaused),
91781
93740
  isClosed: bool4(meta.isClosed),
91782
93741
  whitelisted: bool4(meta.whitelisted),
91783
- expiry: num15(meta.expiry) ?? num15(meta.maturity) ?? curated.expiry,
91784
- timelock: num15(meta.timelock),
93742
+ expiry: num16(meta.expiry) ?? num16(meta.maturity) ?? curated.expiry,
93743
+ timelock: num16(meta.timelock),
91785
93744
  allocators: strArray(meta.allocators),
91786
93745
  owner: str7(meta.owner),
91787
93746
  curator: str7(meta.curator),
@@ -92566,7 +94525,7 @@ async function fetchTokenBalances(chainId, account, tokens, options = {}) {
92566
94525
  }
92567
94526
 
92568
94527
  // src/terms/input.ts
92569
- var num16 = (v) => {
94528
+ var num17 = (v) => {
92570
94529
  if (v == null) return void 0;
92571
94530
  const n = typeof v === "string" ? Number(v) : v;
92572
94531
  return Number.isFinite(n) ? n : void 0;
@@ -92597,20 +94556,20 @@ function toTermSheetInput(row, ctx = {}) {
92597
94556
  {
92598
94557
  category: v?.category ?? k,
92599
94558
  label: v?.label,
92600
- borrowCollateralFactor: num16(v?.borrowCollateralFactor),
92601
- collateralFactor: num16(v?.collateralFactor),
92602
- borrowFactor: num16(v?.borrowFactor),
92603
- liquidationPenalty: num16(v?.liquidationPenalty),
92604
- closeFactor: num16(v?.closeFactor),
92605
- targetHealthFactor: num16(v?.targetHealthFactor),
94559
+ borrowCollateralFactor: num17(v?.borrowCollateralFactor),
94560
+ collateralFactor: num17(v?.collateralFactor),
94561
+ borrowFactor: num17(v?.borrowFactor),
94562
+ liquidationPenalty: num17(v?.liquidationPenalty),
94563
+ closeFactor: num17(v?.closeFactor),
94564
+ targetHealthFactor: num17(v?.targetHealthFactor),
92606
94565
  collateralDisabled: v?.collateralDisabled === true,
92607
94566
  debtDisabled: v?.debtDisabled === true,
92608
94567
  // the mode-level position fields (UNIFIED_API_AUDIT §11) — set
92609
94568
  // only where the row carries them, so EVM inputs are unchanged
92610
- ...v?.liquidationBorrowFactor != null ? { liquidationBorrowFactor: num16(v.liquidationBorrowFactor) } : {},
92611
- ...v?.debtCapacity != null ? { debtCapacity: num16(v.debtCapacity) } : {},
92612
- ...v?.collateralDebtCapacity != null ? { collateralDebtCapacity: num16(v.collateralDebtCapacity) } : {},
92613
- ...v?.maxCollateralAssets != null ? { maxCollateralAssets: num16(v.maxCollateralAssets) } : {},
94569
+ ...v?.liquidationBorrowFactor != null ? { liquidationBorrowFactor: num17(v.liquidationBorrowFactor) } : {},
94570
+ ...v?.debtCapacity != null ? { debtCapacity: num17(v.debtCapacity) } : {},
94571
+ ...v?.collateralDebtCapacity != null ? { collateralDebtCapacity: num17(v.collateralDebtCapacity) } : {},
94572
+ ...v?.maxCollateralAssets != null ? { maxCollateralAssets: num17(v.maxCollateralAssets) } : {},
92614
94573
  ...v?.exclusiveCollateral != null ? { exclusiveCollateral: v.exclusiveCollateral === true } : {},
92615
94574
  ...v?.openParameter ? { openParameter: v.openParameter } : {}
92616
94575
  }
@@ -92618,11 +94577,11 @@ function toTermSheetInput(row, ctx = {}) {
92618
94577
  ) : void 0;
92619
94578
  const rewards = pick2(row, "rewards")?.map((r) => ({
92620
94579
  asset: r?.asset,
92621
- depositRate: num16(r?.depositRate),
92622
- variableBorrowRate: num16(r?.variableBorrowRate),
92623
- stableBorrowRate: num16(r?.stableBorrowRate),
94580
+ depositRate: num17(r?.depositRate),
94581
+ variableBorrowRate: num17(r?.variableBorrowRate),
94582
+ stableBorrowRate: num17(r?.stableBorrowRate),
92624
94583
  kind: r?.kind,
92625
- endsAt: num16(r?.endsAt),
94584
+ endsAt: num17(r?.endsAt),
92626
94585
  claim: r?.claim
92627
94586
  }));
92628
94587
  return {
@@ -92636,29 +94595,29 @@ function toTermSheetInput(row, ctx = {}) {
92636
94595
  (v) => !!v && typeof v === "object"
92637
94596
  ),
92638
94597
  underlying: pick2(row, "underlying"),
92639
- decimals: num16(pick2(row, "decimals")),
92640
- depositRate: num16(pick2(row, "depositRate")),
92641
- variableBorrowRate: num16(pick2(row, "variableBorrowRate")),
92642
- stableBorrowRate: num16(pick2(row, "stableBorrowRate")),
92643
- intrinsicYield: num16(pick2(row, "intrinsicYield")),
94598
+ decimals: num17(pick2(row, "decimals")),
94599
+ depositRate: num17(pick2(row, "depositRate")),
94600
+ variableBorrowRate: num17(pick2(row, "variableBorrowRate")),
94601
+ stableBorrowRate: num17(pick2(row, "stableBorrowRate")),
94602
+ intrinsicYield: num17(pick2(row, "intrinsicYield")),
92644
94603
  rewards,
92645
94604
  rateModel: pick2(row, "rateModel"),
92646
- originationFee: num16(pick2(row, "originationFee")),
92647
- totalDeposits: num16(pick2(row, "totalDeposits")),
92648
- totalDebt: num16(pick2(row, "totalDebt")),
92649
- totalDebtStable: num16(pick2(row, "totalDebtStable")),
92650
- totalLiquidity: num16(pick2(row, "totalLiquidity")),
92651
- borrowLiquidity: num16(pick2(row, "borrowLiquidity")),
92652
- totalDepositsUsd: num16(pick2(row, "totalDepositsUSD", "totalDepositsUsd")),
92653
- totalDebtUsd: num16(pick2(row, "totalDebtUSD", "totalDebtUsd")),
92654
- totalLiquidityUsd: num16(pick2(row, "totalLiquidityUSD", "totalLiquidityUsd")),
92655
- utilization: num16(pick2(row, "utilization")),
92656
- irmTotalDeposits: num16(pick2(row, "irmTotalDeposits")),
92657
- irmTotalDebt: num16(pick2(row, "irmTotalDebt")),
92658
- lockupRatio: num16(pick2(row, "lockupRatio")),
94605
+ originationFee: num17(pick2(row, "originationFee")),
94606
+ totalDeposits: num17(pick2(row, "totalDeposits")),
94607
+ totalDebt: num17(pick2(row, "totalDebt")),
94608
+ totalDebtStable: num17(pick2(row, "totalDebtStable")),
94609
+ totalLiquidity: num17(pick2(row, "totalLiquidity")),
94610
+ borrowLiquidity: num17(pick2(row, "borrowLiquidity")),
94611
+ totalDepositsUsd: num17(pick2(row, "totalDepositsUSD", "totalDepositsUsd")),
94612
+ totalDebtUsd: num17(pick2(row, "totalDebtUSD", "totalDebtUsd")),
94613
+ totalLiquidityUsd: num17(pick2(row, "totalLiquidityUSD", "totalLiquidityUsd")),
94614
+ utilization: num17(pick2(row, "utilization")),
94615
+ irmTotalDeposits: num17(pick2(row, "irmTotalDeposits")),
94616
+ irmTotalDebt: num17(pick2(row, "irmTotalDebt")),
94617
+ lockupRatio: num17(pick2(row, "lockupRatio")),
92659
94618
  minBorrow: pick2(row, "minBorrow", "caps.minBorrow") ?? void 0,
92660
- supplyCap: num16(pick2(row, "supplyCap", "caps.supplyCap")),
92661
- borrowCap: num16(pick2(row, "borrowCap", "caps.borrowCap")),
94619
+ supplyCap: num17(pick2(row, "supplyCap", "caps.supplyCap")),
94620
+ borrowCap: num17(pick2(row, "borrowCap", "caps.borrowCap")),
92662
94621
  debtCeiling: pick2(row, "debtCeiling", "caps.debtCeiling"),
92663
94622
  isActive: pick2(row, "isActive", "flags.isActive"),
92664
94623
  isFrozen: pick2(row, "isFrozen", "flags.isFrozen"),
@@ -92695,8 +94654,8 @@ function toTermSheetInput(row, ctx = {}) {
92695
94654
  // builder's `?? 1`, so Aave and Compound V2 published "the whole debt can
92696
94655
  // be repaid in one liquidation" against a real close factor of 0.5, and
92697
94656
  // Aave V4's `targetHealthFactor` vanished entirely.
92698
- closeFactor: num16(pick2(row, "closeFactor", "caps.closeFactor")),
92699
- targetHealthFactor: num16(
94657
+ closeFactor: num17(pick2(row, "closeFactor", "caps.closeFactor")),
94658
+ targetHealthFactor: num17(
92700
94659
  pick2(row, "targetHealthFactor", "caps.targetHealthFactor")
92701
94660
  ),
92702
94661
  fixedTerm: pick2(row, "fixedTerm") ?? ctx.fixedTerm,
@@ -93847,7 +95806,7 @@ var ripeAdapter = {
93847
95806
  };
93848
95807
  }
93849
95808
  };
93850
- var num17 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
95809
+ var num18 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
93851
95810
  var alchemixAdapter = {
93852
95811
  id: "alchemix",
93853
95812
  matches: isAlchemix,
@@ -93855,8 +95814,8 @@ var alchemixAdapter = {
93855
95814
  build: (input) => {
93856
95815
  const a = input.market?.alchemix ?? {};
93857
95816
  const isCollateralRow = input.collateralActive !== false;
93858
- const protocolFeeBps = num17(a.protocolFeeBps);
93859
- const liquidatorFeeBps = num17(a.liquidatorFeeBps);
95817
+ const protocolFeeBps = num18(a.protocolFeeBps);
95818
+ const liquidatorFeeBps = num18(a.liquidatorFeeBps);
93860
95819
  const fees2 = [];
93861
95820
  if (protocolFeeBps != null)
93862
95821
  fees2.push({
@@ -93896,7 +95855,7 @@ var alchemixAdapter = {
93896
95855
  if (cap > 0) capUtilization = Math.min(1, Number(a.totalDeposited) / cap);
93897
95856
  }
93898
95857
  const capFull = capUtilization != null && capUtilization >= 1;
93899
- const termSecs = num17(a.transmuterQueue?.termSeconds);
95858
+ const termSecs = num18(a.transmuterQueue?.termSeconds);
93900
95859
  return {
93901
95860
  oracle: {
93902
95861
  // Not a market price feed: collateral is valued at the MYT's OWN share
@@ -93989,9 +95948,9 @@ var alchemixAdapter = {
93989
95948
  alchemix: {
93990
95949
  debtValuation: "face",
93991
95950
  redemptionFeeBps: protocolFeeBps,
93992
- redemptionRatePerYear: num17(a.redemptionRatePerYear),
95951
+ redemptionRatePerYear: num18(a.redemptionRatePerYear),
93993
95952
  transmuterTermSecs: termSecs,
93994
- transmuterTermBlocks: num17(a.transmuterQueue?.termBlocks)
95953
+ transmuterTermBlocks: num18(a.transmuterQueue?.termBlocks)
93995
95954
  }
93996
95955
  }
93997
95956
  },
@@ -94008,7 +95967,7 @@ var alchemixAdapter = {
94008
95967
  };
94009
95968
  }
94010
95969
  };
94011
- var num18 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
95970
+ var num19 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
94012
95971
  var flexAdapter = {
94013
95972
  id: "flex",
94014
95973
  matches: isFlex,
@@ -94016,18 +95975,18 @@ var flexAdapter = {
94016
95975
  build: (input) => {
94017
95976
  const f = input.market?.flex ?? {};
94018
95977
  const isCollateralRow = input.collateralActive !== false;
94019
- const minApr = num18(f.minAnnualInterestRate) != null ? f.minAnnualInterestRate * 100 : void 0;
94020
- const maxApr = num18(f.maxAnnualInterestRate) != null ? f.maxAnnualInterestRate * 100 : void 0;
94021
- const minFee = num18(f.minLiquidationFee);
94022
- const maxFee = num18(f.maxLiquidationFee);
94023
- const repayCooldown = num18(f.repayCooldown);
95978
+ const minApr = num19(f.minAnnualInterestRate) != null ? f.minAnnualInterestRate * 100 : void 0;
95979
+ const maxApr = num19(f.maxAnnualInterestRate) != null ? f.maxAnnualInterestRate * 100 : void 0;
95980
+ const minFee = num19(f.minLiquidationFee);
95981
+ const maxFee = num19(f.maxLiquidationFee);
95982
+ const repayCooldown = num19(f.repayCooldown);
94024
95983
  const decimals = input.asset?.decimals ?? input.decimals;
94025
- const minDebt = num18(f.minDebt) != null && decimals != null ? parseUnits(String(f.minDebt), decimals).toString() : void 0;
94026
- const perfFeeBps = num18(f.performanceFeeBps);
94027
- const idle = num18(f.idleLiquidity);
95984
+ const minDebt = num19(f.minDebt) != null && decimals != null ? parseUnits(String(f.minDebt), decimals).toString() : void 0;
95985
+ const perfFeeBps = num19(f.performanceFeeBps);
95986
+ const idle = num19(f.idleLiquidity);
94028
95987
  const borrowFees = [];
94029
- const upfrontPct = num18(input.originationFee) ?? (num18(f.averageInterestRate) != null && num18(f.upfrontInterestPeriod) ? f.averageInterestRate * (f.upfrontInterestPeriod / 31536e3) * 100 : void 0);
94030
- if (upfrontPct != null && num18(f.upfrontInterestPeriod))
95988
+ const upfrontPct = num19(input.originationFee) ?? (num19(f.averageInterestRate) != null && num19(f.upfrontInterestPeriod) ? f.averageInterestRate * (f.upfrontInterestPeriod / 31536e3) * 100 : void 0);
95989
+ if (upfrontPct != null && num19(f.upfrontInterestPeriod))
94031
95990
  borrowFees.push({
94032
95991
  id: "origination",
94033
95992
  label: "Upfront fee",
@@ -94090,7 +96049,7 @@ var flexAdapter = {
94090
96049
  default: input.variableBorrowRate,
94091
96050
  adjustable: true,
94092
96051
  adjustmentCostNote: "Changing the rate again within the adjustment cooldown re-charges the upfront fee.",
94093
- adjustmentCooldownSecs: num18(f.interestRateAdjCooldown),
96052
+ adjustmentCooldownSecs: num19(f.interestRateAdjCooldown),
94094
96053
  ...queueUserSetFields(f.queue)
94095
96054
  }
94096
96055
  },
@@ -94664,7 +96623,7 @@ var flyingTulipAdapter = {
94664
96623
  };
94665
96624
  }
94666
96625
  };
94667
- var num19 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
96626
+ var num20 = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
94668
96627
  var pct2 = (v) => `${(v * 100).toFixed(2)} %`;
94669
96628
  var twyneAdapter = {
94670
96629
  id: "twyne",
@@ -94672,13 +96631,13 @@ var twyneAdapter = {
94672
96631
  profileId: () => "twyne.credit-delegation@v1",
94673
96632
  build: (input) => {
94674
96633
  const tw = input.market?.twyne ?? {};
94675
- const floorLtv = num19(tw.floorLtv);
94676
- const maxLtv = num19(tw.maxLtv);
94677
- const externalLiqLtv = num19(tw.externalLiqLtv);
94678
- const creditApr = num19(tw.creditApr);
94679
- const maturity = num19(tw.collateralMaturity);
96634
+ const floorLtv = num20(tw.floorLtv);
96635
+ const maxLtv = num20(tw.maxLtv);
96636
+ const externalLiqLtv = num20(tw.externalLiqLtv);
96637
+ const creditApr = num20(tw.creditApr);
96638
+ const maturity = num20(tw.collateralMaturity);
94680
96639
  const matured = tw.collateralMatured === true;
94681
- const creditAvailable = num19(tw.creditAvailable);
96640
+ const creditAvailable = num20(tw.creditAvailable);
94682
96641
  const vaultType = typeof tw.vaultType === "string" ? tw.vaultType : void 0;
94683
96642
  const externalName = vaultType === "AAVE_V3" ? "Aave V3" : vaultType === "EULER_V2" ? "Euler V2" : "the external market";
94684
96643
  const creditExhausted = creditAvailable != null && creditAvailable <= 0;
@@ -94839,7 +96798,7 @@ var aaveV4Adapter = {
94839
96798
  build: (input) => {
94840
96799
  const target = input.targetHealthFactor;
94841
96800
  const desc = input.market?.aaveV4 ?? {};
94842
- const maxBonusHf = num20(desc.healthFactorForMaxBonus);
96801
+ const maxBonusHf = num21(desc.healthFactorForMaxBonus);
94843
96802
  return {
94844
96803
  borrow: {
94845
96804
  liquidation: {
@@ -94853,7 +96812,7 @@ var aaveV4Adapter = {
94853
96812
  };
94854
96813
  }
94855
96814
  };
94856
- function num20(v) {
96815
+ function num21(v) {
94857
96816
  if (v == null) return void 0;
94858
96817
  const n = typeof v === "string" ? Number(v) : v;
94859
96818
  return Number.isFinite(n) && n > 0 ? n : void 0;
@@ -95260,13 +97219,13 @@ var LOOPSCALE_REFINANCE_TERM_DAYS = 1;
95260
97219
  var LOOPSCALE_MAX_COLLATERALS = 5;
95261
97220
  var LOOPSCALE_MAX_LEDGERS = 5;
95262
97221
  var LS_NO_ACCOUNT = "11111111111111111111111111111111";
95263
- var DAY5 = 86400;
97222
+ var DAY6 = 86400;
95264
97223
  var isNum6 = (v) => typeof v === "number" && Number.isFinite(v);
95265
97224
  function menuOf(input) {
95266
97225
  if (!input.terms?.length) return void 0;
95267
97226
  return input.terms.map((t) => ({
95268
97227
  ...t,
95269
- durationSecs: isNum6(t.durationSecs) ? t.durationSecs : Math.round(t.durationDays * DAY5)
97228
+ durationSecs: isNum6(t.durationSecs) ? t.durationSecs : Math.round(t.durationDays * DAY6)
95270
97229
  }));
95271
97230
  }
95272
97231
  function build4(input) {
@@ -95776,13 +97735,13 @@ var OFFERBOOK_PROGRAM_ID = "offerbkFMvVfpQhL8ZQ5iromnjct5rz3r52B9ewu3ie";
95776
97735
  var ORIGINATION_SHARE_OF_INTEREST = 0.25;
95777
97736
  var REPAY_SHARE_OF_INTEREST = 0.1;
95778
97737
  var CLAIM_FEE_PERCENT_OF_COLLATERAL = 0.1;
95779
- var DAY6 = 86400;
97738
+ var DAY7 = 86400;
95780
97739
  var isNum8 = (v) => typeof v === "number" && Number.isFinite(v);
95781
97740
  function menuOf2(input) {
95782
97741
  if (!input.terms?.length) return void 0;
95783
97742
  return input.terms.map((t) => ({
95784
97743
  ...t,
95785
- durationSecs: isNum8(t.durationSecs) ? t.durationSecs : Math.round(t.durationDays * DAY6)
97744
+ durationSecs: isNum8(t.durationSecs) ? t.durationSecs : Math.round(t.durationDays * DAY7)
95786
97745
  }));
95787
97746
  }
95788
97747
  function build8(input) {
@@ -95794,7 +97753,7 @@ function build8(input) {
95794
97753
  const tenor = durations.length ? {
95795
97754
  minDurationSecs: Math.min(...durations),
95796
97755
  maxDurationSecs: Math.max(...durations)
95797
- } : { minDurationSecs: DAY6, maxDurationSecs: 30 * DAY6 };
97756
+ } : { minDurationSecs: DAY7, maxDurationSecs: 30 * DAY7 };
95798
97757
  const isLoanLeg = cfg?.debtDisabled === false || input.rateModel === "fixedTerm" || !!input.terms?.length;
95799
97758
  const fixedRate = {
95800
97759
  kind: "fixed-term",
@@ -96675,17 +98634,17 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
96675
98634
  const assetInfo = row.underlyingInfo?.asset ?? row.asset ?? {};
96676
98635
  const underlying = addr4(assetInfo.address, chainId) ?? addr4(row.underlying, chainId) ?? addr4(row.poolId, chainId);
96677
98636
  if (!underlying) return void 0;
96678
- const decimals = num14(assetInfo.decimals) ?? num14(row.decimals) ?? 18;
96679
- const priceUsd = num14(row.underlyingInfo?.prices?.priceUsd) ?? num14(row.price);
96680
- const base = num14(row.depositRate);
96681
- const intrinsic = num14(row.intrinsicYield);
98637
+ const decimals = num15(assetInfo.decimals) ?? num15(row.decimals) ?? 18;
98638
+ const priceUsd = num15(row.underlyingInfo?.prices?.priceUsd) ?? num15(row.price);
98639
+ const base = num15(row.depositRate);
98640
+ const intrinsic = num15(row.intrinsicYield);
96682
98641
  const rewards = sumRewardAprs(row.rewards);
96683
98642
  const marketOwn = sum2(base, rewards);
96684
98643
  const rate = {
96685
98644
  // Prefer our own sum over the origin's `apr`, because `apr` is documented
96686
98645
  // as `depositRate + intrinsicYield` and therefore EXCLUDES incentives —
96687
98646
  // using it as the headline would under-report every incentivized market.
96688
- total: sum2(base, intrinsic, rewards) ?? num14(row.apr) ?? 0,
98647
+ total: sum2(base, intrinsic, rewards) ?? num15(row.apr) ?? 0,
96689
98648
  base,
96690
98649
  rewards,
96691
98650
  intrinsic,
@@ -96753,7 +98712,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
96753
98712
  row.totalLiquidityUSD ?? row.totalLiquidityUsd
96754
98713
  ),
96755
98714
  depositCapacity: void 0,
96756
- utilization: num14(row.utilization),
98715
+ utilization: num15(row.utilization),
96757
98716
  // Lending withdrawals are same-block, bounded by available liquidity —
96758
98717
  // which is exactly `instant-capped`, not `instant`. A pool at 100 %
96759
98718
  // utilization cannot be exited, and calling that `instant` is the kind of
@@ -96761,12 +98720,12 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
96761
98720
  exit: { mode: "instant-capped", settlement: "sync" },
96762
98721
  availability: availability2,
96763
98722
  risk: {
96764
- score: num14(row.risk?.score),
98723
+ score: num15(row.risk?.score),
96765
98724
  label: str6(row.risk?.label),
96766
98725
  illiquid: isIlliquid({
96767
98726
  exitMode: "instant-capped",
96768
- tvlUsd: num14(row.totalDepositsUSD ?? row.totalDepositsUsd),
96769
- liquidityUsd: num14(row.totalLiquidityUSD ?? row.totalLiquidityUsd)
98727
+ tvlUsd: num15(row.totalDepositsUSD ?? row.totalDepositsUsd),
98728
+ liquidityUsd: num15(row.totalLiquidityUSD ?? row.totalLiquidityUsd)
96770
98729
  })
96771
98730
  },
96772
98731
  ...basket ? { basket } : {},
@@ -96832,9 +98791,9 @@ function resolveAvailability2(row, flags, totalRate) {
96832
98791
  };
96833
98792
  }
96834
98793
  function isSupplyCapFull(row) {
96835
- const cap = num14(row.caps?.supplyCap) ?? num14(row.supplyCap);
98794
+ const cap = num15(row.caps?.supplyCap) ?? num15(row.supplyCap);
96836
98795
  if (cap === void 0 || cap <= 0) return false;
96837
- const deposits = num14(row.totalDeposits);
98796
+ const deposits = num15(row.totalDeposits);
96838
98797
  if (deposits === void 0) return false;
96839
98798
  return deposits >= cap;
96840
98799
  }
@@ -96843,7 +98802,7 @@ function sumRewardAprs(rewards) {
96843
98802
  let total = 0;
96844
98803
  let seen = false;
96845
98804
  for (const r of rewards) {
96846
- const apr = num14(r?.depositRate);
98805
+ const apr = num15(r?.depositRate);
96847
98806
  if (apr === void 0) continue;
96848
98807
  total += apr;
96849
98808
  seen = true;
@@ -96851,7 +98810,7 @@ function sumRewardAprs(rewards) {
96851
98810
  return seen ? total : void 0;
96852
98811
  }
96853
98812
  function amount4(formatted, usd) {
96854
- return { formatted: num14(formatted), usd: num14(usd) };
98813
+ return { formatted: num15(formatted), usd: num15(usd) };
96855
98814
  }
96856
98815
  function sum2(...parts) {
96857
98816
  const present = parts.filter((p) => p !== void 0);
@@ -97380,7 +99339,7 @@ function vaultCapabilities(row) {
97380
99339
  caps.push({
97381
99340
  action: "withdraw",
97382
99341
  requires: withdrawRequires(provider),
97383
- feeBps: num14(meta.withdrawFeeBps) ?? row.exit.feeBps,
99342
+ feeBps: num15(meta.withdrawFeeBps) ?? row.exit.feeBps,
97384
99343
  // a fee-paying single-token exit: pays the vault's token only
97385
99344
  acceptsNative: false
97386
99345
  });
@@ -97524,7 +99483,7 @@ function legEarnUid(marketUid) {
97524
99483
  if (isVaultVenue(parts[0])) return void 0;
97525
99484
  return marketUid;
97526
99485
  }
97527
- function num21(v) {
99486
+ function num22(v) {
97528
99487
  const n = typeof v === "number" ? v : Number(v);
97529
99488
  return Number.isFinite(n) ? n : 0;
97530
99489
  }
@@ -97551,10 +99510,10 @@ function legAsset(pos) {
97551
99510
  };
97552
99511
  }
97553
99512
  function toLeg(pos) {
97554
- const depositsUsd = num21(pos.depositsUSD);
97555
- const debtUsd = num21(pos.debtUSD) + num21(pos.debtStableUSD);
97556
- const hasSupply = depositsUsd !== 0 || num21(pos.deposits) !== 0;
97557
- const hasDebt = debtUsd !== 0 || num21(pos.debt) !== 0 || num21(pos.debtStable) !== 0;
99513
+ const depositsUsd = num22(pos.depositsUSD);
99514
+ const debtUsd = num22(pos.debtUSD) + num22(pos.debtStableUSD);
99515
+ const hasSupply = depositsUsd !== 0 || num22(pos.deposits) !== 0;
99516
+ const hasDebt = debtUsd !== 0 || num22(pos.debt) !== 0 || num22(pos.debtStable) !== 0;
97558
99517
  return {
97559
99518
  earnUid: legEarnUid(pos.marketUid),
97560
99519
  marketUid: pos.marketUid,
@@ -97597,12 +99556,12 @@ function earnPositionFromLenderEntry(entry2) {
97597
99556
  (s) => s.legs.some((l) => l.side !== "none") || s.netUsd !== 0
97598
99557
  );
97599
99558
  const crossMargin = active.length <= 1;
97600
- const suppliedUsd = num21(entry2.balanceData?.deposits);
97601
- const borrowedUsd = num21(entry2.balanceData?.debt);
99559
+ const suppliedUsd = num22(entry2.balanceData?.deposits);
99560
+ const borrowedUsd = num22(entry2.balanceData?.debt);
97602
99561
  const aprBreakdown = {
97603
- market: num21(entry2.aprData?.apr),
97604
- rewards: num21(entry2.aprData?.rewardApr),
97605
- intrinsic: num21(entry2.aprData?.intrinsicApr)
99562
+ market: num22(entry2.aprData?.apr),
99563
+ rewards: num22(entry2.aprData?.rewardApr),
99564
+ intrinsic: num22(entry2.aprData?.intrinsicApr)
97606
99565
  };
97607
99566
  return {
97608
99567
  positionUid: buildLendingPositionUid(entry2.lender, entry2.chainId),
@@ -97616,15 +99575,15 @@ function earnPositionFromLenderEntry(entry2) {
97616
99575
  ...entry2.lenderInfo?.logoUri ? { logoURI: entry2.lenderInfo.logoUri } : {},
97617
99576
  suppliedUsd,
97618
99577
  borrowedUsd,
97619
- netUsd: num21(entry2.balanceData?.nav),
99578
+ netUsd: num22(entry2.balanceData?.nav),
97620
99579
  apr: aprBreakdown.market + aprBreakdown.rewards + aprBreakdown.intrinsic,
97621
99580
  aprBreakdown,
97622
- depositApr: num21(entry2.aprData?.depositApr),
97623
- borrowApr: num21(entry2.aprData?.borrowApr),
99581
+ depositApr: num22(entry2.aprData?.depositApr),
99582
+ borrowApr: num22(entry2.aprData?.borrowApr),
97624
99583
  // Only a cross-margin account HAS one health factor. Publishing the first
97625
99584
  // sub-account's as the row's would be a number about a different position.
97626
99585
  health: crossMargin ? active[0]?.health ?? null : null,
97627
- leverage: num21(entry2.leverage),
99586
+ leverage: num22(entry2.leverage),
97628
99587
  crossMargin,
97629
99588
  legs: subAccounts.flatMap((s) => s.legs),
97630
99589
  subAccounts: active,
@@ -97708,7 +99667,7 @@ function earnPositionTotals(items) {
97708
99667
 
97709
99668
  // src/boros/api.ts
97710
99669
  var BOROS_API_BASE = "https://api.boros.finance/open-api";
97711
- var TIMEOUT_MS7 = 8e3;
99670
+ var TIMEOUT_MS8 = 8e3;
97712
99671
  var BorosApiError = class extends Error {
97713
99672
  constructor(message2, status, errorCode) {
97714
99673
  super(message2);
@@ -97726,7 +99685,7 @@ async function borosApi(path, init, fetchImpl = fetch) {
97726
99685
  ...init?.body !== void 0 ? { "content-type": "application/json" } : {}
97727
99686
  },
97728
99687
  body: init?.body !== void 0 ? JSON.stringify(init.body) : void 0,
97729
- signal: AbortSignal.timeout(TIMEOUT_MS7)
99688
+ signal: AbortSignal.timeout(TIMEOUT_MS8)
97730
99689
  });
97731
99690
  const text = await res.text();
97732
99691
  let json;
@@ -98127,7 +100086,7 @@ async function fetchBorosOrderBook(marketId, fetchImpl) {
98127
100086
 
98128
100087
  // src/boros/history.ts
98129
100088
  var PAGE = 200;
98130
- var MAX_PAGES2 = 60;
100089
+ var MAX_PAGES3 = 60;
98131
100090
  var STEP = {
98132
100091
  "5m": 300,
98133
100092
  "1h": 3600,
@@ -98163,7 +100122,7 @@ async function fetchBorosRateHistory(marketId, opts = {}) {
98163
100122
  const from = Math.max(0, Math.floor(opts.from ?? 0));
98164
100123
  let end = Math.floor(opts.to ?? Date.now() / 1e3);
98165
100124
  const byTs = /* @__PURE__ */ new Map();
98166
- for (let page = 0; page < MAX_PAGES2 && end >= from; page++) {
100125
+ for (let page = 0; page < MAX_PAGES3 && end >= from; page++) {
98167
100126
  const r = await borosApi(
98168
100127
  `/v1/markets/chart?marketId=${marketId}&timeFrame=${interval}&startTimestamp=${from}&endTimestamp=${end}`,
98169
100128
  void 0,
@@ -98250,8 +100209,8 @@ async function fetchBorosAccount(account, fetchImpl) {
98250
100209
  }
98251
100210
 
98252
100211
  // src/boros/margin.ts
98253
- var SECONDS_PER_YEAR21 = 365 * 24 * 3600;
98254
- var ttmYears = (m, ttmSec) => Math.max(ttmSec ?? m.timeToMaturitySec, m.margin.tThreshSec) / SECONDS_PER_YEAR21;
100212
+ var SECONDS_PER_YEAR22 = 365 * 24 * 3600;
100213
+ var ttmYears = (m, ttmSec) => Math.max(ttmSec ?? m.timeToMaturitySec, m.margin.tThreshSec) / SECONDS_PER_YEAR22;
98255
100214
  function borosInitialMargin(m, size, ratePct, ttmSec) {
98256
100215
  const r = Math.max(Math.abs(ratePct) / 100, m.margin.rateFloor);
98257
100216
  return Math.abs(size) * r * m.margin.kIM * ttmYears(m, ttmSec);
@@ -98261,7 +100220,7 @@ function borosMaintenanceMargin(m, size, markPct, ttmSec) {
98261
100220
  return Math.abs(size) * r * m.margin.kMM * ttmYears(m, ttmSec);
98262
100221
  }
98263
100222
  function borosTakerFee(m, size) {
98264
- return Math.abs(size) * m.fees.takerFee * m.timeToMaturitySec / SECONDS_PER_YEAR21;
100223
+ return Math.abs(size) * m.fees.takerFee * m.timeToMaturitySec / SECONDS_PER_YEAR22;
98265
100224
  }
98266
100225
  function walkBorosBook(levels, size) {
98267
100226
  let left = size;
@@ -98283,7 +100242,7 @@ function walkBorosBook(levels, size) {
98283
100242
  };
98284
100243
  }
98285
100244
  function borosRateMoveToLiquidation(m, size, equity, markPct) {
98286
- const ttm = m.timeToMaturitySec / SECONDS_PER_YEAR21;
100245
+ const ttm = m.timeToMaturitySec / SECONDS_PER_YEAR22;
98287
100246
  if (!(Math.abs(size) > 0) || !(ttm > 0)) return null;
98288
100247
  const mm = borosMaintenanceMargin(m, size, markPct);
98289
100248
  const slack = equity - mm;
@@ -98373,7 +100332,7 @@ function quoteBorosHedgeLeg(p) {
98373
100332
  const fixed = fill.avgAprPct;
98374
100333
  const floating = m.rates.floatingApr;
98375
100334
  const takerFee = borosTakerFee(m, size);
98376
- const ttmYears2 = m.timeToMaturitySec / SECONDS_PER_YEAR21;
100335
+ const ttmYears2 = m.timeToMaturitySec / SECONDS_PER_YEAR22;
98377
100336
  const settleAprPct = m.fees.settleFee != null ? m.fees.settleFee * 100 : null;
98378
100337
  const allIn = ttmYears2 > 0 ? takerFee / size / ttmYears2 * 100 + (settleAprPct ?? 0) : null;
98379
100338
  const rateForMargin = fixed ?? m.rates.markApr ?? 0;
@@ -98428,6 +100387,6 @@ function quoteBorosHedgeLeg(p) {
98428
100387
  };
98429
100388
  }
98430
100389
 
98431
- export { ALCHEMIX_BLOCK_SECONDS, ApiBookSource, BOROS_API_BASE, BOROS_GOVERNANCE, BOROS_MIN_CASH_USD, BOROS_PROFILE_ID, BorosApiError, DEFAULT_CONSENSUS_DEMOTION, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_PROFILE_ID, DEFAULT_STALE_REJECT_SECONDS, DEFAULT_TERMMAX_API, DEFAULT_TERM_ORDER_STORE, DOLOMITE_ISO_ID_PREFIX, EARN_DESCRIPTIONS, EARN_LABELS, EARN_RATE_SOURCE_BY_PROVIDER, EMPTY_BALANCE, EXACTLY_LENDER_KEY, EXPONENT_MATURED_REASON, FIXED_YIELD_EARN_VENUE_PREFIXES, FLYING_TULIP_LENDER_KEY, FRACTION_RATE_PROVIDERS, FUNDING_EXPOSURE_PROFILES, 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, NON_EVM_VAULT_PROVIDERS, PASSTHROUGH_RATE_EPSILON, PENDLE_ASSETS_URL, PENDLE_CHAIN_IDS, PENDLE_MARKETS_URL2 as PENDLE_MARKETS_URL, PREFIX_LENDERS, RATE_QUEUE_MAX_LEVELS, RATE_QUEUE_STEP, RIPE_LENDER_KEY, SDK_FRACTION_RATE_PROVIDERS, SPECTRA_NETWORKS, SPECTRA_RATE_MAX_PERCENT, SPECTRA_RATE_MIN_PERCENT, STABLECOIN_SYMBOLS, STCELO_MANAGER_ADDRESS, SVM_EARN_MINT_BUILDERS, SVM_EARN_VAULT_BUILDERS, SVM_VAULT_PROVIDERS, TELLER_CALLS_PER_BID, DECIMAL_BASE as TERMMAX_DECIMAL_BASE, TERMMAX_LIQUIDATION_PENALTY, TERMMAX_LIQUIDATION_WINDOW_SECS, TERMMAX_LIQUIDATOR_BONUS, TERMMAX_MARKETS_PER_CALL, 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, USER_SET_RATE_PICKS, VAULT_PROVIDERS, VAULT_PROVIDER_PROFILE, VAULT_PROVIDER_TRAITS, VAULT_SHARE_PRICE_PROBE, VAULT_VENUE_PREFIX, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, __resetResupplyUserCaches, accountDepositListKey, accountWithdrawalListKey, alchemixLenderKey, alchemixMytRate, alchemixRedemptionPace, appendSnapshot, applyEarnSanity, applyPositionDelta, attachImplications, attachPricesToFlashLiquidity, blockNumberFromTag, borosApi, borosInitialMargin, borosMaintenanceMargin, borosRateMoveToLiquidation, borosSideTerms, borosTakerFee, borrowDescription, borrowFindings, borrowHeadline, buildBorosTermSheet, buildExposures2 as buildExposures, buildFluidFTokensCall, buildLendingPositionUid, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildQueriesFromMeta, buildRateQueue, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildTermMaxUserCall, buildTermSheet, buildTermSheetsForGroup, buildVaultEarnUid, buildVaultLookup, buildVaultTermSheet, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, classifyFreshness, classifyReliability, classifyVault, clearPendleMarketsCache, clearSpectraMarketsCache, collateralSymbolsByVenue, 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, convertAlchemixMarketsToResponse, convertBorosCandle, convertBorosMarket, convertCoolerMarketsToResponse, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFlexMarketsToResponse, convertFlyingTulipMarketsToResponse, convertFrankencoinMarketsToResponse, convertFraxlendPairsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRipeMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMultiAccountTypeUserState, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, debtAheadOf, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, deriveSwapTags, detectInterfaceKinds, dexResolverFor, disambiguateEarnNames, disambiguateOrderBookNames, discoverFlexTroves, dolomiteVaultAddress, dssIlkBytes32, dssKeyParts, dssLenderKey, duration, earnDescription, earnLabel, earnMarketFromPool, earnMarketFromVault, earnMarketLabel, earnPositionFromLenderEntry, earnPositionFromVaultBalance, earnPositionTotals, earnRateAtMaturity, earnRowSubtitle, earnUidFromMarketUid, earnVaultTerms, earnVenueKind, emitterCoverage, encodeBalanceFetcherCalldata, enrichTermSheet, enrichmentIndexFromRows, enumerateEmitters, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feePhrase, feedKeyOf, feedStatKey, fetchAlchemixMarkets, fetchBorosAccount, fetchBorosCollaterals, fetchBorosMarket, fetchBorosMarketById, fetchBorosMarkets, fetchBorosOrderBook, fetchBorosRateHistory, fetchCoolerMarkets, fetchDolomiteAccountNumbers, fetchDolomiteSubAccounts, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFlexMarkets, fetchFluidDexState, fetchFluidFTokens, fetchFlyingTulipMarkets, fetchFrankencoinMarkets, fetchFraxlendPairs, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchInverseMarkets, fetchLagoonApiVaults, fetchLagoonVaults, fetchLenderRewards, fetchLenderRewardsByMarketUid, fetchLiquityMarkets, fetchListaVaultsFromChain, fetchLlamaLendMarkets, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendleApiAssets, fetchPendleApiMarkets, fetchPendlePrices, fetchPendlePtMarkets, fetchResupplyMarkets, fetchRipeMarkets, fetchRiverMarkets, fetchSiloVaults, fetchSpectraApiMarkets, fetchSpectraPtMarkets, fetchTellerMarkets, fetchTermMarkets, fetchTermMaxMarkets, fetchTermStoreOrders, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchUsddMarkets, fetchUsualRewardsClaimData, fetchYearnApiVaults, fetchYearnVaults, fillableRemaining, filterActiveLenders, filterLenderMeta, filterLendersByProtocol, finalizeInfo, findingsFor, flexAverageRate, flexLenderApr, flexLenderKey, flexMarketIndex, formatRaw, frankencoinKeyParts, frankencoinLenderKey, fraxlendAssetPerCollateral, fraxlendKeyParts, fraxlendLenderKey, fundingExposureOf, fuseLenderData, generateLendingPools, getAavesForChain, getAssetConfig, getBalanceForMarketUid, getBorrowCapacity, getCachedFluidDexState, 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, getMidnightChainBooks, getMorphoTypeMarketConverter, getReadFailurePolicy, getResolvedDolomiteAccountNumbers, getResolvedDolomiteSubAccounts, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getTermProfile, getVaultPublicDataAll, getVaultWithdrawalRequests, hasCritical, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasPendleMarkets, hasSpectraMarkets, hasUpshiftVaults, hasYearnVaults, ilkToKeySegment, implausibleRatePercent, injectLenderInfoIntoEntries, inverseKeyParts, inverseLenderKey, isBoundNeed, isFailedCall, isFixedYieldEarnRow, isIlliquid, isLenderVenueKey, isLendingPosition, isLiveMarket as isLivePendleMarket, isLiveSpectraMarket, isMaturedTerm, isOrderBookCollateralLeg, isOrderBookLendRow, isPrincipalTokenSymbol, isRollingBookLendRow, isSecondaryMarketOnly, isStablecoinSymbol, isSyntheticQuoteUnit, isUnearnableEarnRate, isUnrealizableEarnRate, isVaultPosition, isVaultVenue, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, lenderLiquidityPressure, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, llamaLendKeyParts, llamaLendLenderKey, marketKeysOf, meetsLiquidityFloor, mergeDeep, multicall3Abi2 as multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, organizeUserQueries, parseBalanceFetcherResult, parseDolomiteSubAccountId, parseEarnUid, parseLenderKey, parseMergedResult, parseMulticallRpcResponses, parseExpirySeconds as parsePendleExpirySeconds, parseRawRpcBatchResponses, parseRawRpcResponses, parseCurveFee as parseSpectraCurveFee, parsePtRate as parseSpectraPtRate, parseTermMaxLtv, parseTokenBalanceResult, pct, pegPressure, assetKey as pendleAssetKey, pickPool as pickSpectraPool, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, protocolConsensus, protocolOf, pruneFeedStats, quoteBorosHedgeLeg, rankBorosHedgeMarkets, rankFindings, ratePercent, readUserPositions, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, repairImpossibleTvl, resolveAdapter, resolveDerivation, resolveDolomiteRowIdentity, resolveEarnIdentity, resolveModeConfig, resolveStCeloDepositGroup, resolveVaultProfileId, resupplyKeyParts, resupplyLenderKey, resupplyMarketLabel, riverKeyParts, riverLenderKey, sanePercent as saneSpectraPercent, savingsAddresses, savingsBalanceKind, secondaryMarketVault, selectAssetGroupPrices, selectUsualRewardEntry, setMysticApiKey, shortDate, spectraAddress, spectraNetwork, spectraPoolsUrl, splitChainScopedAddress as splitPendleChainScopedAddress, stampCapabilities, stampEarnSubtitles, stampOrderBookLendRow, stampRollingBookLendRow, stampVaultClassification, stampVaultTermSheets, stripLeadingBrand, subAccountsOf, supplyDescription, supplyFindings, supplyHeadline, svmEarnBuildability, svmEarnBuilderKey, swapRoutedProvidersArePriceConsistent, swapSideDescription, swapSideHeadline, swapSideImplications, tellerBpsToPercent, tellerImpliedLtv, tellerLenderKey, tellerPoolFromLenderKey, termApiBaseUrl, 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, termOfferRateToAprPct, termOrderStoreBaseUrl, tickToAprNumber, tickToPrice, toDigest, toDolomiteSubAccountId, toTermFillNow, toTermSheetInput, toVaultTermInput, trancheFromCounterparty, tryParseEarnUid, unflattenLenderData, updateFeedStats, usdValue, usddIlkBytes32, usddKeyParts, usddLenderKey, validateTermSheet, validateTermSheets, validateUserData, vaultSharesToAssets, vaultTermInputFromEarnMarket, vaultTermInputFromSourceRow, vaultTraits, vaultVenue, venueBrand, venueBrandKey, walkBorosBook, withMaturityLabel, withTrancheLabel };
100390
+ export { ALCHEMIX_BLOCK_SECONDS, ApiBookSource, BOROS_API_BASE, BOROS_GOVERNANCE, BOROS_MIN_CASH_USD, BOROS_PROFILE_ID, BorosApiError, DEFAULT_CONSENSUS_DEMOTION, DEFAULT_MIDNIGHT_API, DEFAULT_OUTLIER_GUARD, DEFAULT_PROFILE_ID, DEFAULT_STALE_REJECT_SECONDS, DEFAULT_TERMMAX_API, DEFAULT_TERM_ORDER_STORE, DOLOMITE_ISO_ID_PREFIX, EARN_DESCRIPTIONS, EARN_LABELS, EARN_RATE_SOURCE_BY_PROVIDER, EMPTY_BALANCE, EXACTLY_LENDER_KEY, EXPONENT_MATURED_REASON, FIXED_YIELD_EARN_VENUE_PREFIXES, FLYING_TULIP_LENDER_KEY, FRACTION_RATE_PROVIDERS, FUNDING_EXPOSURE_PROFILES, 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, NON_EVM_VAULT_PROVIDERS, PASSTHROUGH_RATE_EPSILON, PENDLE_ASSETS_URL, PENDLE_CHAIN_IDS, PENDLE_MARKETS_URL2 as PENDLE_MARKETS_URL, PREFIX_LENDERS, RATE_QUEUE_MAX_LEVELS, RATE_QUEUE_STEP, RIPE_LENDER_KEY, SDK_FRACTION_RATE_PROVIDERS, SPECTRA_NETWORKS, SPECTRA_RATE_MAX_PERCENT, SPECTRA_RATE_MIN_PERCENT, STABLECOIN_SYMBOLS, STCELO_MANAGER_ADDRESS, SVM_EARN_MINT_BUILDERS, SVM_EARN_VAULT_BUILDERS, SVM_VAULT_PROVIDERS, TELLER_CALLS_PER_BID, DECIMAL_BASE as TERMMAX_DECIMAL_BASE, TERMMAX_LIQUIDATION_PENALTY, TERMMAX_LIQUIDATION_WINDOW_SECS, TERMMAX_LIQUIDATOR_BONUS, TERMMAX_MARKETS_PER_CALL, 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, USER_REWARD_SOURCES, USER_SET_RATE_PICKS, VAULT_PROVIDERS, VAULT_PROVIDER_PROFILE, VAULT_PROVIDER_TRAITS, VAULT_SHARE_PRICE_PROBE, VAULT_VENUE_PREFIX, VOLATILE_VAULT_OVERRIDES, YEARN_CHAIN_IDS, YEARN_YDAEMON_BASE, __resetResupplyUserCaches, accountDepositListKey, accountWithdrawalListKey, alchemixLenderKey, alchemixMytRate, alchemixRedemptionPace, appendSnapshot, applyEarnSanity, applyPositionDelta, attachImplications, attachPricesToFlashLiquidity, blockNumberFromTag, borosApi, borosInitialMargin, borosMaintenanceMargin, borosRateMoveToLiquidation, borosSideTerms, borosTakerFee, borrowDescription, borrowFindings, borrowHeadline, buildBorosTermSheet, buildExposures2 as buildExposures, buildFluidFTokensCall, buildLendingPositionUid, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildQueriesFromMeta, buildRateQueue, buildSumerAccumulators, buildSummaries, buildTellerUserCall, buildTermMaxUserCall, buildTermSheet, buildTermSheetsForGroup, buildVaultEarnUid, buildVaultLookup, buildVaultTermSheet, calculateLeverage, calculateNetApr, calculateOverallNetApr, calculateWeightedAverage, classifyFreshness, classifyReliability, classifyVault, clearPendleMarketsCache, clearSpectraMarketsCache, collateralSymbolsByVenue, 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, convertAlchemixMarketsToResponse, convertBorosCandle, convertBorosMarket, convertCoolerMarketsToResponse, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFlexMarketsToResponse, convertFlyingTulipMarketsToResponse, convertFrankencoinMarketsToResponse, convertFraxlendPairsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRipeMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMultiAccountTypeUserState, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, debtAheadOf, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, deriveSwapTags, detectInterfaceKinds, dexResolverFor, disambiguateEarnNames, disambiguateOrderBookNames, discoverFlexTroves, dolomiteVaultAddress, dssIlkBytes32, dssKeyParts, dssLenderKey, duration, earnDescription, earnLabel, earnMarketFromPool, earnMarketFromVault, earnMarketLabel, earnPositionFromLenderEntry, earnPositionFromVaultBalance, earnPositionTotals, earnRateAtMaturity, earnRowSubtitle, earnUidFromMarketUid, earnVaultTerms, earnVenueKind, emitterCoverage, encodeBalanceFetcherCalldata, enrichTermSheet, enrichmentIndexFromRows, enumerateEmitters, exactlyPairLtv, exactlyPenaltyRateToAprPercent, exactlyWadRateToPercent, feePhrase, feedKeyOf, feedStatKey, fetchAaveIncentivesUserRewards, fetchAlchemixMarkets, fetchBorosAccount, fetchBorosCollaterals, fetchBorosMarket, fetchBorosMarketById, fetchBorosMarkets, fetchBorosOrderBook, fetchBorosRateHistory, fetchCoolerMarkets, fetchDolomiteAccountNumbers, fetchDolomiteSubAccounts, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, fetchFlexMarkets, fetchFluidDexState, fetchFluidFTokens, fetchFlyingTulipMarkets, fetchFlyingTulipUserRewards, fetchFrankencoinMarkets, fetchFraxlendPairs, fetchGeneralYields, fetchGeneralYieldsByMarketUid, fetchGmxExecutionFees, fetchGmxTickerPrices, fetchGmxVaults, fetchHypercoreVaults, fetchInverseMarkets, fetchLagoonApiVaults, fetchLagoonVaults, fetchLenderRewards, fetchLenderRewardsByMarketUid, fetchLiquityMarkets, fetchListaMarketEmissions, fetchListaUserRewards, fetchListaVaultEmissions, fetchListaVaultsFromChain, fetchLlamaLendMarkets, fetchMerklUserRewards, fetchMorphoUserBalances, fetchMorphoUserPositionMarkets, fetchMorphoVaults, fetchMorphoVaultsFromApi, fetchMorphoVaultsFromChain, fetchOraclePrices, fetchPendleApiAssets, fetchPendleApiMarkets, fetchPendlePrices, fetchPendlePtMarkets, fetchResupplyMarkets, fetchRipeMarkets, fetchRiverMarkets, fetchSiloVaults, fetchSpectraApiMarkets, fetchSpectraPtMarkets, fetchTellerMarkets, fetchTermMarkets, fetchTermMaxMarkets, fetchTermStoreOrders, fetchTokenBalances, fetchTokenMetadata, fetchUpshiftApiVaults, fetchUpshiftVaults, fetchUsddMarkets, fetchUserRewards, fetchUsualRewardsClaimData, fetchYearnApiVaults, fetchYearnVaults, fillableRemaining, filterActiveLenders, filterLenderMeta, filterLendersByProtocol, finalizeInfo, findingsFor, flexAverageRate, flexLenderApr, flexLenderKey, flexMarketIndex, formatRaw, frankencoinKeyParts, frankencoinLenderKey, fraxlendAssetPerCollateral, fraxlendKeyParts, fraxlendLenderKey, fundingExposureOf, fuseLenderData, generateLendingPools, getAavesForChain, getAssetConfig, getBalanceForMarketUid, getBorrowCapacity, getCachedFluidDexState, 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, getMidnightChainBooks, getMorphoTypeMarketConverter, getReadFailurePolicy, getResolvedDolomiteAccountNumbers, getResolvedDolomiteSubAccounts, getStCeloValidatorGroups, getSubAccountAddress, getSubAccountIndex, getTermProfile, getVaultPublicDataAll, getVaultWithdrawalRequests, hasCritical, hasEulerEarnVaultSubgraph, hasLagoonVaults, hasMorphoPositionIndex, hasMorphoUserApi, hasMorphoUserSubgraph, hasPendleMarkets, hasSpectraMarkets, hasUpshiftVaults, hasYearnVaults, ilkToKeySegment, implausibleRatePercent, injectLenderInfoIntoEntries, inverseKeyParts, inverseLenderKey, isBoundNeed, isFailedCall, isFixedYieldEarnRow, isIlliquid, isLenderVenueKey, isLendingPosition, isLiveMarket as isLivePendleMarket, isLiveSpectraMarket, isMaturedTerm, isOrderBookCollateralLeg, isOrderBookLendRow, isPrincipalTokenSymbol, isRollingBookLendRow, isSecondaryMarketOnly, isStablecoinSymbol, isSyntheticQuoteUnit, isUnearnableEarnRate, isUnrealizableEarnRate, isVaultPosition, isVaultVenue, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, lenderLiquidityPressure, liquityCandidateTroveIds, liquityKeyParts, liquityLenderKey, listaEmissionRewardFetcher, listaLoginMessage, llamaLendKeyParts, llamaLendLenderKey, marketKeysOf, meetsLiquidityFloor, mergeDeep, multicall3Abi2 as multicall3Abi, nanTo, needsLenderApproval, needsTokenApproval, noOpResult, normalizeToBytes, organizeUserQueries, parseBalanceFetcherResult, parseDolomiteSubAccountId, parseEarnUid, parseLenderKey, parseMergedResult, parseMulticallRpcResponses, parseExpirySeconds as parsePendleExpirySeconds, parseRawRpcBatchResponses, parseRawRpcResponses, parseCurveFee as parseSpectraCurveFee, parsePtRate as parseSpectraPtRate, parseTermMaxLtv, parseTokenBalanceResult, pct, pegPressure, assetKey as pendleAssetKey, pickPool as pickSpectraPool, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, protocolConsensus, protocolOf, pruneFeedStats, quoteBorosHedgeLeg, rankBorosHedgeMarkets, rankFindings, ratePercent, readUserPositions, readVaultSharePrices, rejectOutliers as rejectPriceOutliers, repairImpossibleTvl, resolveAdapter, resolveDerivation, resolveDolomiteRowIdentity, resolveEarnIdentity, resolveMerklOpportunityMarkets, resolveModeConfig, resolveStCeloDepositGroup, resolveVaultProfileId, resupplyKeyParts, resupplyLenderKey, resupplyMarketLabel, riverKeyParts, riverLenderKey, sanePercent as saneSpectraPercent, savingsAddresses, savingsBalanceKind, secondaryMarketVault, selectAssetGroupPrices, selectUsualRewardEntry, setMysticApiKey, shortDate, spectraAddress, spectraNetwork, spectraPoolsUrl, splitChainScopedAddress as splitPendleChainScopedAddress, stampCapabilities, stampEarnSubtitles, stampOrderBookLendRow, stampRollingBookLendRow, stampVaultClassification, stampVaultTermSheets, stripLeadingBrand, subAccountsOf, supplyDescription, supplyFindings, supplyHeadline, svmEarnBuildability, svmEarnBuilderKey, swapRoutedProvidersArePriceConsistent, swapSideDescription, swapSideHeadline, swapSideImplications, tellerBpsToPercent, tellerImpliedLtv, tellerLenderKey, tellerPoolFromLenderKey, termApiBaseUrl, 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, termOfferRateToAprPct, termOrderStoreBaseUrl, tickToAprNumber, tickToPrice, toDigest, toDolomiteSubAccountId, toTermFillNow, toTermSheetInput, toVaultTermInput, trancheFromCounterparty, tryParseEarnUid, unflattenLenderData, updateFeedStats, usdValue, usddIlkBytes32, usddKeyParts, usddLenderKey, validateTermSheet, validateTermSheets, validateUserData, vaultSharesToAssets, vaultTermInputFromEarnMarket, vaultTermInputFromSourceRow, vaultTraits, vaultVenue, venueBrand, venueBrandKey, walkBorosBook, withMaturityLabel, withTrancheLabel };
98432
100391
  //# sourceMappingURL=index.js.map
98433
100392
  //# sourceMappingURL=index.js.map