@1delta/margin-fetcher 5.0.130 → 5.0.132

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
@@ -12713,11 +12713,11 @@ function normalizeMorphoApiMarket(item) {
12713
12713
  out.oracleAddress = out.oracle?.address ?? void 0;
12714
12714
  delete out.oracle;
12715
12715
  }
12716
- for (const side of ["loanAsset", "collateralAsset"]) {
12717
- const a = out[side];
12716
+ for (const side2 of ["loanAsset", "collateralAsset"]) {
12717
+ const a = out[side2];
12718
12718
  if (a && typeof a === "object" && "price" in a) {
12719
12719
  const { price: price2, ...rest } = a;
12720
- out[side] = { ...rest, priceUsd: price2?.usd ?? null };
12720
+ out[side2] = { ...rest, priceUsd: price2?.usd ?? null };
12721
12721
  }
12722
12722
  }
12723
12723
  return out;
@@ -20690,8 +20690,8 @@ function parseVault(vault, chainId, prices, additionalYields, tokenList, liquidi
20690
20690
  }
20691
20691
  const isSmartCol = !!vault.isSmartCol;
20692
20692
  const isSmartDebt = !!vault.isSmartDebt;
20693
- const sideTokens = (side, isSmart) => {
20694
- const raw = side?.token0 !== void 0 ? side : { token0: side };
20693
+ const sideTokens = (side2, isSmart) => {
20694
+ const raw = side2?.token0 !== void 0 ? side2 : { token0: side2 };
20695
20695
  const t0 = normalizeUnderlying((raw?.token0 ?? "").toString().toLowerCase());
20696
20696
  if (!isSmart) return [t0];
20697
20697
  const t1 = normalizeUnderlying((raw?.token1 ?? "").toString().toLowerCase());
@@ -22078,9 +22078,9 @@ var ApiBookSource = class {
22078
22078
  * side is empty (or when the cursor runs out). Each side carries at most the
22079
22079
  * best 3 levels — exact best tick, partial depth.
22080
22080
  */
22081
- async walkBooksSide(chainId, side) {
22081
+ async walkBooksSide(chainId, side2) {
22082
22082
  const out = /* @__PURE__ */ new Map();
22083
- const sort = side === "bids" ? "-bid" : "-ask";
22083
+ const sort = side2 === "bids" ? "-bid" : "-ask";
22084
22084
  let cursor = null;
22085
22085
  for (let page = 0; page < MAX_WALK_PAGES; page++) {
22086
22086
  const json = await this.getJson(
@@ -22091,12 +22091,12 @@ var ApiBookSource = class {
22091
22091
  for (const b of rows) {
22092
22092
  const id = String(b?.market_id ?? b?.id ?? "").toLowerCase();
22093
22093
  if (!id || String(b?.chain_id) !== String(chainId)) continue;
22094
- const levels = (Array.isArray(b?.[side]) ? b[side].map(parseLevel) : []).filter((l) => l.units > 0n);
22094
+ const levels = (Array.isArray(b?.[side2]) ? b[side2].map(parseLevel) : []).filter((l) => l.units > 0n);
22095
22095
  if (levels.length === 0) {
22096
22096
  reachedEmpty = true;
22097
22097
  break;
22098
22098
  }
22099
- out.set(id, levels.sort(side === "bids" ? byTickDesc : byTickAsc));
22099
+ out.set(id, levels.sort(side2 === "bids" ? byTickDesc : byTickAsc));
22100
22100
  }
22101
22101
  cursor = json?.cursor ?? null;
22102
22102
  if (reachedEmpty || !cursor || rows.length === 0) break;
@@ -22252,9 +22252,9 @@ var ApiBookSource = class {
22252
22252
  * book's total depth so the quote returns EVERY offer (it returns none when the
22253
22253
  * target exceeds depth). Best-effort: `{}` on any failure.
22254
22254
  */
22255
- async getOfferMakers(marketId, side, assets) {
22255
+ async getOfferMakers(marketId, side2, assets) {
22256
22256
  const map = {};
22257
- const url = `${this.baseUrl}/books/${marketId}/${side}/quote?assets=${assets}`;
22257
+ const url = `${this.baseUrl}/books/${marketId}/${side2}/quote?assets=${assets}`;
22258
22258
  try {
22259
22259
  const res = await this.fetchImpl(url);
22260
22260
  if (!res.ok) return map;
@@ -22954,14 +22954,14 @@ var TermSubgraphSource = class {
22954
22954
  );
22955
22955
  if (!data) return null;
22956
22956
  const scale3 = Math.pow(10, config.loanDecimals);
22957
- const toOrder = (o, side, revealedRaw) => {
22957
+ const toOrder = (o, side2, revealedRaw) => {
22958
22958
  const a = o.auction ?? {};
22959
22959
  const complete = Boolean(a.auctionComplete);
22960
22960
  const cancelled = Boolean(a.auctionCancelled);
22961
22961
  const revealed = toBig3(revealedRaw) > 0n;
22962
22962
  return {
22963
22963
  id: String(o.id),
22964
- side,
22964
+ side: side2,
22965
22965
  auctionId: String(a.id ?? ""),
22966
22966
  account,
22967
22967
  amount: String(o.amount ?? "0"),
@@ -29279,6 +29279,10 @@ function convertResupplyMarketsToResponse(raw, chainId, prices = {}, _additional
29279
29279
  const maxLtv = p.maxLTV !== null ? Number(p.maxLTV) / LTV_PRECISION : 0;
29280
29280
  const liquidationPenalty = p.liquidationFee !== null ? Number(p.liquidationFee) / LTV_PRECISION : 0;
29281
29281
  const mintFeePct = p.mintFee !== null ? Number(p.mintFee) / LTV_PRECISION * 100 : 0;
29282
+ const debtWeight = Math.max(
29283
+ 1,
29284
+ collPrice / debtPrice * (1 + mintFeePct / 100)
29285
+ );
29282
29286
  const borrowApr = ratePerSecToApr(p.liveRatePerSec ?? p.ratePerSec);
29283
29287
  const collateralIntrinsicApr = ratePerSecToApr(p.underlyingSupplyRatePerSec);
29284
29288
  const entry2 = { data: {} };
@@ -29382,7 +29386,7 @@ function convertResupplyMarketsToResponse(raw, chainId, prices = {}, _additional
29382
29386
  label: marketLabel,
29383
29387
  borrowCollateralFactor: 0,
29384
29388
  collateralFactor: 0,
29385
- borrowFactor: 1,
29389
+ borrowFactor: debtWeight,
29386
29390
  liquidationPenalty,
29387
29391
  closeFactor: 1,
29388
29392
  collateralDisabled: true,
@@ -32020,10 +32024,17 @@ function organizeUserQueries(queries) {
32020
32024
  const siloV2 = queries.filter((q) => isSiloV2Type(q.lender));
32021
32025
  const siloV3 = queries.filter((q) => isSiloV3Type(q.lender));
32022
32026
  const frankencoin = queries.filter((q) => isFrankencoin(q.lender));
32023
- if (morphos.length === 0 && gearbox.length === 0 && midnight.length === 0 && term.length === 0 && exactly.length === 0 && liquity.length === 0 && river.length === 0 && teller.length === 0 && termMax.length === 0 && usdd.length === 0 && sky.length === 0 && frankencoin.length === 0 && llamaLend.length === 0 && siloV2.length === 0 && siloV3.length === 0)
32027
+ const byFamily = (pred, family) => [queries.filter((q) => pred(q.lender)), family];
32028
+ const familyGroups = [
32029
+ byFamily(isResupply, Lender.RESUPPLY),
32030
+ byFamily(isInverse, Lender.INVERSE),
32031
+ byFamily(isFraxlend, Lender.FRAXLEND),
32032
+ byFamily(isCurvance, Lender.CURVANCE)
32033
+ ];
32034
+ if (morphos.length === 0 && gearbox.length === 0 && midnight.length === 0 && term.length === 0 && exactly.length === 0 && liquity.length === 0 && river.length === 0 && teller.length === 0 && termMax.length === 0 && usdd.length === 0 && sky.length === 0 && frankencoin.length === 0 && llamaLend.length === 0 && siloV2.length === 0 && siloV3.length === 0 && familyGroups.every(([g]) => g.length === 0))
32024
32035
  return queries;
32025
32036
  const others = queries.filter(
32026
- (q) => !isMorphoType(q.lender) && !isGearboxV3(q.lender) && !isMidnight(q.lender) && !isTerm(q.lender) && !isExactly(q.lender) && !isLiquityFamily(q.lender) && !isRiver(q.lender) && !isTeller(q.lender) && !isTermMax(q.lender) && !isDssType(q.lender) && !isFrankencoin(q.lender) && !isLlamaLend(q.lender) && !isSiloV2Type(q.lender) && !isSiloV3Type(q.lender)
32037
+ (q) => !isMorphoType(q.lender) && !isGearboxV3(q.lender) && !isMidnight(q.lender) && !isTerm(q.lender) && !isExactly(q.lender) && !isLiquityFamily(q.lender) && !isRiver(q.lender) && !isTeller(q.lender) && !isTermMax(q.lender) && !isDssType(q.lender) && !isFrankencoin(q.lender) && !isLlamaLend(q.lender) && !isSiloV2Type(q.lender) && !isSiloV3Type(q.lender) && !isResupply(q.lender) && !isInverse(q.lender) && !isFraxlend(q.lender) && !isCurvance(q.lender)
32027
32038
  );
32028
32039
  const morphoBlue = morphos.filter((q) => q.lender.startsWith("MORPHO_BLUE"));
32029
32040
  const moolah = morphos.filter((q) => q.lender.startsWith("LISTA_DAO"));
@@ -32124,6 +32135,15 @@ function organizeUserQueries(queries) {
32124
32135
  assets: void 0
32125
32136
  });
32126
32137
  }
32138
+ for (const [group, family] of familyGroups) {
32139
+ if (group.length === 0) continue;
32140
+ result.push({
32141
+ lender: family,
32142
+ account: group[0].account,
32143
+ params: group.map((p) => p.lender),
32144
+ assets: void 0
32145
+ });
32146
+ }
32127
32147
  if (llamaLend.length > 0) {
32128
32148
  result.push({
32129
32149
  lender: Lender.LLAMALEND,
@@ -33089,7 +33109,7 @@ var usesSiloLens = (chainId) => getPositionLensFor(chainId, LENS_FAMILY.SILO) !=
33089
33109
  var buildSiloLensCall = (chainId, roster, account) => {
33090
33110
  const lens = getPositionLensFor(chainId, LENS_FAMILY.SILO);
33091
33111
  if (!lens || roster.length === 0) return [];
33092
- const side = (h) => [
33112
+ const side2 = (h) => [
33093
33113
  h.silo,
33094
33114
  h.protectedShareToken,
33095
33115
  h.debtShareToken,
@@ -33099,7 +33119,7 @@ var buildSiloLensCall = (chainId, roster, account) => {
33099
33119
  parseAbiParameters(
33100
33120
  "((address,address,address,uint8),(address,address,address,uint8))[]"
33101
33121
  ),
33102
- [roster.map((r) => [side(r.market.silo0), side(r.market.silo1)])]
33122
+ [roster.map((r) => [side2(r.market.silo0), side2(r.market.silo1)])]
33103
33123
  );
33104
33124
  return [
33105
33125
  {
@@ -33151,7 +33171,7 @@ var buildSiloV3UserCall = (chainId, lender, account, params) => {
33151
33171
  if (roster.length === 0) return [];
33152
33172
  const lens = getPositionLensFor(chainId, LENS_FAMILY.SILO);
33153
33173
  if (lens) {
33154
- const side = (h) => [
33174
+ const side2 = (h) => [
33155
33175
  h.silo,
33156
33176
  h.protectedShareToken,
33157
33177
  h.debtShareToken,
@@ -33161,7 +33181,7 @@ var buildSiloV3UserCall = (chainId, lender, account, params) => {
33161
33181
  parseAbiParameters(
33162
33182
  "((address,address,address,uint8),(address,address,address,uint8))[]"
33163
33183
  ),
33164
- [roster.map((r) => [side(r.market.silo0), side(r.market.silo1)])]
33184
+ [roster.map((r) => [side2(r.market.silo0), side2(r.market.silo1)])]
33165
33185
  );
33166
33186
  return [
33167
33187
  {
@@ -34309,6 +34329,11 @@ var DISCOVERY_TTL_MS2 = 6e4;
34309
34329
  var SNAPSHOT_CHUNK = 12;
34310
34330
  var rosterCache5 = /* @__PURE__ */ new Map();
34311
34331
  var discoveryCache4 = /* @__PURE__ */ new Map();
34332
+ var familyDiscoveryInflight = /* @__PURE__ */ new Map();
34333
+ var resupplyQueryScope = (lender) => {
34334
+ const parts = resupplyKeyParts(lender);
34335
+ return parts ? { family: parts.lender, pair: parts.pair } : { family: lender };
34336
+ };
34312
34337
  var rosterKey2 = (chainId, lender, block = "head") => `${chainId}:${lender}:${block}`;
34313
34338
  var discoveryKey2 = (chainId, lender, account, block = "head") => `${chainId}:${lender}:${account.toLowerCase()}:${block}`;
34314
34339
  var getCachedResupplyDiscovery = (chainId, lender, account, opts) => discoveryCache4.get(discoveryKey2(chainId, lender, account, blockKey(opts)));
@@ -34393,7 +34418,8 @@ var discoverPositions = async (chainId, pairs, account, opts) => {
34393
34418
  return active;
34394
34419
  };
34395
34420
  var buildResupplyUserCall = async (chainId, lender, account, opts) => {
34396
- const cfg = resupplyConfigFor(lender, chainId);
34421
+ const { family, pair: scopedPair } = resupplyQueryScope(lender);
34422
+ const cfg = resupplyConfigFor(family, chainId);
34397
34423
  const key4 = discoveryKey2(chainId, lender, account, blockKey(opts));
34398
34424
  const stash = (positions2) => discoveryCache4.set(key4, { positions: positions2, at: Date.now() });
34399
34425
  if (!cfg?.registry) {
@@ -34404,7 +34430,7 @@ var buildResupplyUserCall = async (chainId, lender, account, opts) => {
34404
34430
  try {
34405
34431
  roster = await fetchRoster2(
34406
34432
  chainId,
34407
- lender,
34433
+ family,
34408
34434
  cfg.registry,
34409
34435
  cfg.pairAllowlist,
34410
34436
  opts
@@ -34417,7 +34443,28 @@ var buildResupplyUserCall = async (chainId, lender, account, opts) => {
34417
34443
  return [];
34418
34444
  }
34419
34445
  const cachedDiscovery = discoveryCache4.get(key4);
34420
- const positions = cachedDiscovery && Date.now() - cachedDiscovery.at < DISCOVERY_TTL_MS2 ? cachedDiscovery.positions : await discoverPositions(chainId, roster.pairs, account, opts);
34446
+ let positions;
34447
+ if (cachedDiscovery && Date.now() - cachedDiscovery.at < DISCOVERY_TTL_MS2) {
34448
+ positions = cachedDiscovery.positions;
34449
+ } else {
34450
+ const famKey = discoveryKey2(chainId, family, account, blockKey(opts));
34451
+ const famCached = discoveryCache4.get(famKey);
34452
+ let all;
34453
+ if (famCached && Date.now() - famCached.at < DISCOVERY_TTL_MS2) {
34454
+ all = famCached.positions;
34455
+ } else {
34456
+ let inflight7 = familyDiscoveryInflight.get(famKey);
34457
+ if (!inflight7) {
34458
+ inflight7 = discoverPositions(chainId, roster.pairs, account, opts).then((found) => {
34459
+ discoveryCache4.set(famKey, { positions: found, at: Date.now() });
34460
+ return found;
34461
+ }).finally(() => familyDiscoveryInflight.delete(famKey));
34462
+ familyDiscoveryInflight.set(famKey, inflight7);
34463
+ }
34464
+ all = await inflight7;
34465
+ }
34466
+ positions = scopedPair ? all.filter((p) => p.pair.toLowerCase() === scopedPair) : all;
34467
+ }
34421
34468
  stash(positions);
34422
34469
  if (positions.length === 0) return [];
34423
34470
  return positions.flatMap(({ pair, collateral }) => [
@@ -34430,6 +34477,7 @@ var buildResupplyUserCall = async (chainId, lender, account, opts) => {
34430
34477
  function __resetResupplyUserCaches() {
34431
34478
  rosterCache5.clear();
34432
34479
  discoveryCache4.clear();
34480
+ familyDiscoveryInflight.clear();
34433
34481
  }
34434
34482
 
34435
34483
  // src/lending/user-data/fraxlend/lens.ts
@@ -37127,8 +37175,8 @@ var getFluidUserDataConverter = (lender, chainId, account, meta) => {
37127
37175
  const constants = vaultData.constantVariables;
37128
37176
  const isSmartCol = !!vaultData.isSmartCol;
37129
37177
  const isSmartDebt = !!vaultData.isSmartDebt;
37130
- const sideLegs = (side, isSmart, sideContract, perShareOf) => {
37131
- const raw = side?.token0 !== void 0 ? side : { token0: side };
37178
+ const sideLegs = (side2, isSmart, sideContract, perShareOf) => {
37179
+ const raw = side2?.token0 !== void 0 ? side2 : { token0: side2 };
37132
37180
  const tokens = [
37133
37181
  normalizeUnderlying2((raw?.token0 ?? "").toString().toLowerCase())
37134
37182
  ];
@@ -39224,7 +39272,8 @@ function sharesToAmount(shares, totalAmount, totalShares) {
39224
39272
  return q * totalShares < shares * totalAmount ? q + 1n : q;
39225
39273
  }
39226
39274
  var getResupplyUserDataConverter = (lender, chainId, account, meta, opts) => {
39227
- const cfg = resupplyConfigFor(lender, chainId);
39275
+ const { family } = resupplyQueryScope(lender);
39276
+ const cfg = resupplyConfigFor(family, chainId);
39228
39277
  const discovery = getCachedResupplyDiscovery(chainId, lender, account, opts);
39229
39278
  const positions = discovery?.positions ?? [];
39230
39279
  const expected = cfg && positions.length > 0 ? positions.length * RESUPPLY_CALLS_PER_PAIR : 0;
@@ -39243,7 +39292,7 @@ var getResupplyUserDataConverter = (lender, chainId, account, meta, opts) => {
39243
39292
  const totalBorrowAmount = tupleAt(accounting, 1);
39244
39293
  const totalBorrowShares = tupleAt(accounting, 2);
39245
39294
  const sharePrice = isFailedCall(data[base + 1]) ? 0n : big18(data[base + 1]);
39246
- const lenderKey = resupplyLenderKey(lender, chainId, pair);
39295
+ const lenderKey = resupplyLenderKey(family, chainId, pair);
39247
39296
  const metaMap = meta?.[lenderKey];
39248
39297
  if (!metaMap) return;
39249
39298
  const debt = sharesToAmount(
@@ -59566,39 +59615,39 @@ function enumerateEmitters(chainId) {
59566
59615
  const siloRows = (markets, keyOf) => {
59567
59616
  for (const m of markets ?? []) {
59568
59617
  const lender = keyOf(m.siloConfig);
59569
- for (const side of [m.silo0, m.silo1]) {
59570
- const mu = uid(lender, side.silo);
59618
+ for (const side2 of [m.silo0, m.silo1]) {
59619
+ const mu = uid(lender, side2.silo);
59571
59620
  push2({
59572
59621
  chainId,
59573
- address: side.silo,
59622
+ address: side2.silo,
59574
59623
  lenderKey: lender,
59575
59624
  family: "silo",
59576
59625
  role: "market",
59577
59626
  marketUid: mu,
59578
- asset: lc(side.token)
59627
+ asset: lc(side2.token)
59579
59628
  });
59580
- if (isAddr3(side.protectedShareToken))
59629
+ if (isAddr3(side2.protectedShareToken))
59581
59630
  push2({
59582
59631
  chainId,
59583
- address: side.protectedShareToken,
59632
+ address: side2.protectedShareToken,
59584
59633
  lenderKey: lender,
59585
59634
  family: "erc20-share",
59586
59635
  role: "shareToken",
59587
59636
  side: "collateral",
59588
59637
  marketUid: mu,
59589
- asset: lc(side.token),
59638
+ asset: lc(side2.token),
59590
59639
  shareEvents: "transfers"
59591
59640
  });
59592
- if (isAddr3(side.debtShareToken))
59641
+ if (isAddr3(side2.debtShareToken))
59593
59642
  push2({
59594
59643
  chainId,
59595
- address: side.debtShareToken,
59644
+ address: side2.debtShareToken,
59596
59645
  lenderKey: lender,
59597
59646
  family: "erc20-share",
59598
59647
  role: "debtToken",
59599
59648
  side: "borrow",
59600
59649
  marketUid: mu,
59601
- asset: lc(side.token),
59650
+ asset: lc(side2.token),
59602
59651
  shareEvents: "transfers"
59603
59652
  });
59604
59653
  }
@@ -59612,11 +59661,11 @@ function enumerateEmitters(chainId) {
59612
59661
  if (!isAddr3(hook)) continue;
59613
59662
  const lender = keyOf(m.siloConfig);
59614
59663
  const legs = {};
59615
- for (const side of [m.silo0, m.silo1])
59616
- if (isAddr3(side?.silo))
59617
- legs[lc(side.silo)] = {
59618
- marketUid: uid(lender, side.silo),
59619
- asset: lc(side.token)
59664
+ for (const side2 of [m.silo0, m.silo1])
59665
+ if (isAddr3(side2?.silo))
59666
+ legs[lc(side2.silo)] = {
59667
+ marketUid: uid(lender, side2.silo),
59668
+ asset: lc(side2.token)
59620
59669
  };
59621
59670
  push2({
59622
59671
  chainId,
@@ -63185,14 +63234,14 @@ function unixSeconds(v) {
63185
63234
  const n = typeof v === "number" ? v : Number(v);
63186
63235
  return Number.isFinite(n) && n > 0 ? n : void 0;
63187
63236
  }
63188
- function buildMerklStreams(opp, side, totalApr, source) {
63237
+ function buildMerklStreams(opp, side2, totalApr, source) {
63189
63238
  const rewardBreakdowns = opp.rewardsRecord?.breakdowns ?? [];
63190
63239
  const endsAt = unixSeconds(opp.earliestCampaignEnd ?? opp.latestCampaignEnd);
63191
63240
  const startsAt = unixSeconds(
63192
63241
  opp.earliestCampaignStart ?? opp.latestCampaignStart
63193
63242
  );
63194
63243
  const base = {
63195
- side,
63244
+ side: side2,
63196
63245
  kind: "token",
63197
63246
  claim: "merkl",
63198
63247
  endsAt,
@@ -67136,22 +67185,22 @@ function parseSiloV2GraphQLResults(items, context) {
67136
67185
  { api: apiSide0, self: registryEntry.silo0, other: registryEntry.silo1 },
67137
67186
  { api: apiSide1, self: registryEntry.silo1, other: registryEntry.silo0 }
67138
67187
  ];
67139
- for (const { api: side, self, other } of sideTuples) {
67140
- const tokenLc = (side.inputTokenId ?? side.inputToken?.id ?? self.token).toLowerCase();
67188
+ for (const { api: side2, self, other } of sideTuples) {
67189
+ const tokenLc = (side2.inputTokenId ?? side2.inputToken?.id ?? self.token).toLowerCase();
67141
67190
  if (!tokenLc) continue;
67142
67191
  const partnerTokenLc = other.token.toLowerCase();
67143
67192
  const dedupKey = `${lenderKey}:${tokenLc}`;
67144
67193
  if (seen.has(dedupKey)) continue;
67145
- const oracleAddr = (side.solvencyOracleAddress ?? side.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67194
+ const oracleAddr = (side2.solvencyOracleAddress ?? side2.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67146
67195
  const isStatic = !oracleAddr || oracleAddr === ZERO_ADDRESS13;
67147
67196
  const siloAddrLc = self.silo.toLowerCase();
67148
67197
  try {
67149
67198
  let priceUSD = 0;
67150
67199
  let rawPrice = 1;
67151
- const supplyNum = safeNumber3(side.supply);
67152
- const supplyUsdNum = side.supplyUsd != null ? Number(side.supplyUsd) : 0;
67153
- const borrowedNum = safeNumber3(side.borrowed);
67154
- const borrowedUsdNum = side.borrowedUsd != null ? Number(side.borrowedUsd) : 0;
67200
+ const supplyNum = safeNumber3(side2.supply);
67201
+ const supplyUsdNum = side2.supplyUsd != null ? Number(side2.supplyUsd) : 0;
67202
+ const borrowedNum = safeNumber3(side2.borrowed);
67203
+ const borrowedUsdNum = side2.borrowedUsd != null ? Number(side2.borrowedUsd) : 0;
67155
67204
  if (supplyNum > 0 && supplyUsdNum > 0) {
67156
67205
  priceUSD = supplyUsdNum / supplyNum;
67157
67206
  rawPrice = isStatic ? 1 : priceUSD;
@@ -67165,12 +67214,12 @@ function parseSiloV2GraphQLResults(items, context) {
67165
67214
  if (!priceUSD) continue;
67166
67215
  rawPrice = 1;
67167
67216
  } else {
67168
- const quoteStr = side.solvencyOracle?.quote;
67217
+ const quoteStr = side2.solvencyOracle?.quote;
67169
67218
  if (!quoteStr) continue;
67170
67219
  const quoteNum = Number(quoteStr);
67171
67220
  if (!Number.isFinite(quoteNum) || quoteNum === 0) continue;
67172
67221
  if (quoteNum < 1e-9) continue;
67173
- const quoteTokenLc = (side.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67222
+ const quoteTokenLc = (side2.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67174
67223
  if (!quoteTokenLc) continue;
67175
67224
  const qtUSD = lookupUSD3(context, quoteTokenLc);
67176
67225
  if (!qtUSD) continue;
@@ -67280,22 +67329,22 @@ function parseSiloV3GraphQLResults(items, context) {
67280
67329
  { api: apiSide0, self: registryEntry.silo0, other: registryEntry.silo1 },
67281
67330
  { api: apiSide1, self: registryEntry.silo1, other: registryEntry.silo0 }
67282
67331
  ];
67283
- for (const { api: side, self, other } of sideTuples) {
67284
- const tokenLc = (side.inputTokenId ?? side.inputToken?.id ?? self.token).toLowerCase();
67332
+ for (const { api: side2, self, other } of sideTuples) {
67333
+ const tokenLc = (side2.inputTokenId ?? side2.inputToken?.id ?? self.token).toLowerCase();
67285
67334
  if (!tokenLc) continue;
67286
67335
  const partnerTokenLc = other.token.toLowerCase();
67287
67336
  const dedupKey = `${lenderKey}:${tokenLc}`;
67288
67337
  if (seen.has(dedupKey)) continue;
67289
- const oracleAddr = (side.solvencyOracleAddress ?? side.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67338
+ const oracleAddr = (side2.solvencyOracleAddress ?? side2.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67290
67339
  const isStatic = !oracleAddr || oracleAddr === ZERO_ADDRESS13;
67291
67340
  const siloAddrLc = self.silo.toLowerCase();
67292
67341
  try {
67293
67342
  let priceUSD = 0;
67294
67343
  let rawPrice = 1;
67295
- const supplyNum = safeNumber4(side.supply);
67296
- const supplyUsdNum = side.supplyUsd != null ? Number(side.supplyUsd) : 0;
67297
- const borrowedNum = safeNumber4(side.borrowed);
67298
- const borrowedUsdNum = side.borrowedUsd != null ? Number(side.borrowedUsd) : 0;
67344
+ const supplyNum = safeNumber4(side2.supply);
67345
+ const supplyUsdNum = side2.supplyUsd != null ? Number(side2.supplyUsd) : 0;
67346
+ const borrowedNum = safeNumber4(side2.borrowed);
67347
+ const borrowedUsdNum = side2.borrowedUsd != null ? Number(side2.borrowedUsd) : 0;
67299
67348
  if (supplyNum > 0 && supplyUsdNum > 0) {
67300
67349
  priceUSD = supplyUsdNum / supplyNum;
67301
67350
  rawPrice = isStatic ? 1 : priceUSD;
@@ -67309,12 +67358,12 @@ function parseSiloV3GraphQLResults(items, context) {
67309
67358
  if (!priceUSD) continue;
67310
67359
  rawPrice = 1;
67311
67360
  } else {
67312
- const quoteStr = side.solvencyOracle?.quote;
67361
+ const quoteStr = side2.solvencyOracle?.quote;
67313
67362
  if (!quoteStr) continue;
67314
67363
  const quoteNum = Number(quoteStr);
67315
67364
  if (!Number.isFinite(quoteNum) || quoteNum === 0) continue;
67316
67365
  if (quoteNum < 1e-9) continue;
67317
- const quoteTokenLc = (side.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67366
+ const quoteTokenLc = (side2.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67318
67367
  if (!quoteTokenLc) continue;
67319
67368
  const qtUSD = lookupUSD4(context, quoteTokenLc);
67320
67369
  if (!qtUSD) continue;
@@ -80317,9 +80366,9 @@ var readerBitfiBfbtc = (entry2) => {
80317
80366
  const totalAssets = totalSupply * exchangeRate * underlyingUnit / (ONE_E1823 * shareUnit);
80318
80367
  const feeOf = (cell) => {
80319
80368
  if (!Array.isArray(cell)) return void 0;
80320
- const pct3 = toBigInt16(cell[0]);
80369
+ const pct4 = toBigInt16(cell[0]);
80321
80370
  const fixed = toBigInt16(cell[1]);
80322
- return pct3 === void 0 || fixed === void 0 ? void 0 : { pct: pct3, fixed };
80371
+ return pct4 === void 0 || fixed === void 0 ? void 0 : { pct: pct4, fixed };
80323
80372
  };
80324
80373
  const evm = feeOf(evmFee);
80325
80374
  const native = feeOf(nativeFee);
@@ -81497,7 +81546,7 @@ var readerLiminalPipe = (entry2) => {
81497
81546
  parse: ([
81498
81547
  supply,
81499
81548
  nav,
81500
- fees,
81549
+ fees2,
81501
81550
  provider,
81502
81551
  redeemPaused,
81503
81552
  lpBalance,
@@ -81510,7 +81559,7 @@ var readerLiminalPipe = (entry2) => {
81510
81559
  if (totalSupply === void 0 || nav18 === void 0) return void 0;
81511
81560
  const exchangeRate = totalSupply > 0n ? nav18 * ONE_E1823 / totalSupply : ONE_E1823;
81512
81561
  const totalAssets = nav18 / navScale;
81513
- const feeBps = toBigInt16(cellAt(fees, 0));
81562
+ const feeBps = toBigInt16(cellAt(fees2, 0));
81514
81563
  const providerMatches = typeof provider === "string" && provider.toLowerCase() === cfg.liquidityProvider;
81515
81564
  const bal = toBigInt16(lpBalance);
81516
81565
  const allow = toBigInt16(lpAllowance);
@@ -85052,17 +85101,17 @@ var priceGmMarkets = async (chainId, multicallRetry, markets, prices) => {
85052
85101
  var computeLiquidityUsd = (poolUsdLong, poolUsdShort, reservedUsdLong, reservedUsdShort, reserveFactorLong, reserveFactorShort) => {
85053
85102
  if (typeof poolUsdLong !== "bigint" || typeof poolUsdShort !== "bigint")
85054
85103
  return void 0;
85055
- const side = (pool, reserved, rf) => {
85104
+ const side2 = (pool, reserved, rf) => {
85056
85105
  const floor = rf > 0n ? reserved * USD_1E30N / rf : 0n;
85057
85106
  const avail = pool - floor;
85058
85107
  return avail > 0n ? avail : 0n;
85059
85108
  };
85060
- const total = side(poolUsdLong, reservedUsdLong, reserveFactorLong) + side(poolUsdShort, reservedUsdShort, reserveFactorShort);
85109
+ const total = side2(poolUsdLong, reservedUsdLong, reserveFactorLong) + side2(poolUsdShort, reservedUsdShort, reserveFactorShort);
85061
85110
  return toUsd(total);
85062
85111
  };
85063
85112
  var computeDepositCapacityUsd = (long, short) => {
85064
85113
  const INF = -1n;
85065
- const side = ([poolAmount, priceMax, maxAmount, maxUsd]) => {
85114
+ const side2 = ([poolAmount, priceMax, maxAmount, maxUsd]) => {
85066
85115
  if (typeof poolAmount !== "bigint") return void 0;
85067
85116
  const poolUsd = poolAmount * priceMax;
85068
85117
  const amountRoom = maxAmount > 0n ? (maxAmount > poolAmount ? maxAmount - poolAmount : 0n) * priceMax : INF;
@@ -85072,8 +85121,8 @@ var computeDepositCapacityUsd = (long, short) => {
85072
85121
  if (usdRoom === INF) return amountRoom;
85073
85122
  return amountRoom < usdRoom ? amountRoom : usdRoom;
85074
85123
  };
85075
- const l = side(long);
85076
- const s = side(short);
85124
+ const l = side2(long);
85125
+ const s = side2(short);
85077
85126
  if (l == null && s == null) return void 0;
85078
85127
  return toUsd((l ?? 0n) + (s ?? 0n));
85079
85128
  };
@@ -86431,6 +86480,18 @@ function deriveBorrowTags(borrow, market = {}) {
86431
86480
  push(out, "full-collateral-seizure");
86432
86481
  return [...out];
86433
86482
  }
86483
+ function deriveSwapTags(sw, side2, governance) {
86484
+ const tags = ["rate-swap", "margined", "rate-liquidation"];
86485
+ tags.push(side2.receives === "fixed" ? "fixed-rate" : "variable-rate");
86486
+ if (sw.maturity.kind === "fixed-date") tags.push("has-maturity");
86487
+ if (sw.exit.close === "market-trade") tags.push("exit-market-sale");
86488
+ if (sw.openInterestCap?.hard != null) tags.push("capped");
86489
+ if (side2.availability.blockedBy === "cap-full") tags.push("cap-full");
86490
+ if (governance?.mutability === "immutable") tags.push("immutable");
86491
+ else if (governance && !governance.timelockSecs) tags.push("no-timelock");
86492
+ if (governance?.controllerKind === "EOA") tags.push("eoa-controlled");
86493
+ return tags;
86494
+ }
86434
86495
 
86435
86496
  // src/terms/format.ts
86436
86497
  var SECS_PER_DAY = 86400;
@@ -86825,6 +86886,51 @@ function borrowDescription(b) {
86825
86886
  }
86826
86887
  return parts.join(" ");
86827
86888
  }
86889
+ function floatingLabel(sw) {
86890
+ return sw.floating.spreadOf?.length ? `the ${sw.floating.spreadOf.join(" \u2212 ")} ${sw.notional.underlying} funding spread` : `${sw.floating.venue} ${sw.notional.underlying} funding`;
86891
+ }
86892
+ function swapSideHeadline(sw, s) {
86893
+ const fixed = s.fixedApr != null ? `fixed ${pct(s.fixedApr)}` : `fixed (no ${s.side === "short" ? "bids" : "asks"} on the book)`;
86894
+ const floating = `${floatingLabel(sw)}${sw.floating.apr != null ? ` (now ${pct(sw.floating.apr)})` : ""}`;
86895
+ const legs = s.receives === "fixed" ? `Receive ${fixed} \xB7 pay ${floating}` : `Receive ${floating} \xB7 pay ${fixed}`;
86896
+ return `${legs} \xB7 to ${shortDate(sw.maturity.maturity)}`;
86897
+ }
86898
+ function swapSideDescription(sw, s) {
86899
+ const unit = sw.notional.unit.symbol ?? "the margin token";
86900
+ const what = s.receives === "fixed" ? `A ${s.side.toUpperCase()} swaps the ${floatingLabel(sw)} for a fixed rate` : `A ${s.side.toUpperCase()} swaps a fixed rate for the ${floatingLabel(sw)}`;
86901
+ const loses = s.adverseMove === "floating-up" ? "if funding rises above the fixed rate" : "if funding falls below the fixed rate";
86902
+ const fees2 = sw.fees.filter((f) => f.when !== "liquidation").map((f) => feePhrase(f)).join("; ");
86903
+ return `${what} on a notional sized in ${unit}, until ${shortDate(sw.maturity.maturity)}. Margin is posted in ${unit} and marked at the implied rate; ${loses} the position loses margin, and it is liquidated at health \u2264 ${sw.liquidation.healthThreshold}.` + (fees2 ? ` ${fees2}.` : "");
86904
+ }
86905
+ function swapSideImplications(sw, s, governance) {
86906
+ const out = [];
86907
+ if (s.carryApr != null && sw.floating.apr != null && s.fixedApr != null) {
86908
+ const verb = s.carryApr >= 0 ? "gains" : "gives up";
86909
+ out.push(
86910
+ `At today's rates this side ${verb} ${pct(Math.abs(s.carryApr))}/yr (fixed ${pct(s.fixedApr)} vs floating ${pct(sw.floating.apr)}); the floating leg resets every ${duration(sw.floating.settlementSecs)}.`
86911
+ );
86912
+ }
86913
+ out.push(
86914
+ `Margin is lost when funding ${s.adverseMove === "floating-up" ? "rises" : "falls"}: liquidation at health \u2264 ${sw.liquidation.healthThreshold}` + (sw.liquidation.forcedDeleverageHealth != null ? `, forced deleverage at \u2264 ${sw.liquidation.forcedDeleverageHealth}` : "") + "."
86915
+ );
86916
+ const unitSym = sw.notional.unit.symbol ?? "the margin token";
86917
+ const sameAsUnderlying = unitSym.toUpperCase().replace(/^W/, "").replace("\u20AE", "T") === sw.notional.underlying.toUpperCase();
86918
+ out.push(
86919
+ sameAsUnderlying ? `Size is in ${unitSym}: one unit of size is one ${sw.notional.underlying} of notional.` : `Size is in ${unitSym}: one unit of size is one ${unitSym} of ${sw.notional.underlying} notional, not one ${sw.notional.underlying}.`
86920
+ );
86921
+ out.push(
86922
+ `The rate is fixed only until ${shortDate(sw.maturity.maturity)}; holding the exposure longer means rolling into a later market at its rate then.`
86923
+ );
86924
+ if (sw.exit.withdrawalCooldownSecs)
86925
+ out.push(
86926
+ `Margin withdrawals are a request plus a cooldown of ${duration(sw.exit.withdrawalCooldownSecs)}` + (sw.exit.requestResetsCooldown ? "; a second request restarts it for the whole pending amount." : ".")
86927
+ );
86928
+ if (governance?.powers?.includes("upgrade-implementation") && !governance.timelockSecs)
86929
+ out.push(
86930
+ `The contracts are upgradeable by ${governance.safe ? `a ${governance.safe.threshold}-of-${governance.safe.owners} Safe` : "an admin"} with no timelock.`
86931
+ );
86932
+ return out;
86933
+ }
86828
86934
 
86829
86935
  // src/terms/profiles.ts
86830
86936
  var P = (p) => p;
@@ -87591,6 +87697,22 @@ var TERM_PROFILES = [
87591
87697
  "Deposits are counterparty to traders \u2014 the pool profits when they lose and loses when they win."
87592
87698
  ]
87593
87699
  }
87700
+ }),
87701
+ // ── Rate swaps ─────────────────────────────────────────────────────────────
87702
+ P({
87703
+ id: "boros.funding-swap@v1",
87704
+ name: "Pendle Boros funding-rate swap",
87705
+ family: "swap",
87706
+ swap: {
87707
+ description: "A fixed-vs-floating swap on one venue\u2019s perpetual-futures funding rate, until a fixed maturity. Nothing is lent or borrowed: each side posts margin. A SHORT pays the floating funding and receives the fixed rate it trades at; a LONG does the opposite.",
87708
+ implications: [
87709
+ "The margin is at risk: the side the floating rate moves against loses margin and is liquidated at health \u2264 1.",
87710
+ "The fixed rate holds only until the market matures \u2014 a longer exposure has to be rolled at whatever the next market prices.",
87711
+ "One market tracks ONE venue\u2019s funding on ONE asset; anything it hedges (an sUSDe yield, a basis trade) is only as well covered as that venue tracks it.",
87712
+ "Positions and margin live on Arbitrum, separate from anything they hedge on another chain \u2014 the two are never netted."
87713
+ ]
87714
+ },
87715
+ docsUrl: "https://pendle.gitbook.io/boros"
87594
87716
  })
87595
87717
  ];
87596
87718
  var BY_ID = new Map(TERM_PROFILES.map((p) => [p.id, p]));
@@ -87750,11 +87872,11 @@ function rateKindOf(input) {
87750
87872
  if (isNum(maturity) && maturity > 0) return "fixed-term";
87751
87873
  return "variable-curve";
87752
87874
  }
87753
- function rewardTerms(input, side) {
87875
+ function rewardTerms(input, side2) {
87754
87876
  if (!input.rewards?.length) return void 0;
87755
87877
  const out = [];
87756
87878
  for (const r of input.rewards) {
87757
- const apr = side === "supply" ? r.depositRate ?? 0 : r.variableBorrowRate ?? r.stableBorrowRate ?? 0;
87879
+ const apr = side2 === "supply" ? r.depositRate ?? 0 : r.variableBorrowRate ?? r.stableBorrowRate ?? 0;
87758
87880
  if (!apr) continue;
87759
87881
  const isPoints = r.kind === "points" || !r.asset;
87760
87882
  out.push({
@@ -87764,7 +87886,7 @@ function rewardTerms(input, side) {
87764
87886
  } : void 0,
87765
87887
  kind: isPoints ? "points" : "token",
87766
87888
  apr,
87767
- side,
87889
+ side: side2,
87768
87890
  claim: r.claim ?? (isPoints ? "none" : "accrual"),
87769
87891
  endsAt: r.endsAt,
87770
87892
  // Points have no priceable value, so they must not inflate `aprTotal`.
@@ -87773,20 +87895,20 @@ function rewardTerms(input, side) {
87773
87895
  }
87774
87896
  return out.length ? out : void 0;
87775
87897
  }
87776
- function buildRate(input, side) {
87898
+ function buildRate(input, side2) {
87777
87899
  const kind = rateKindOf(input);
87778
- const rewards = rewardTerms(input, side);
87900
+ const rewards = rewardTerms(input, side2);
87779
87901
  const priceableRewards = (rewards ?? []).filter((r) => !r.indicative).reduce((s, r) => s + r.apr, 0);
87780
87902
  const menuBest = input.terms?.length ? Math.min(...input.terms.map((t) => t.apr)) : void 0;
87781
87903
  let base;
87782
- if (side === "supply") {
87904
+ if (side2 === "supply") {
87783
87905
  base = input.depositRate ?? 0;
87784
87906
  } else if (kind === "fixed-term") {
87785
87907
  base = menuBest ?? input.stableBorrowRate ?? input.variableBorrowRate ?? 0;
87786
87908
  } else {
87787
87909
  base = input.variableBorrowRate ?? 0;
87788
87910
  }
87789
- const intrinsic = side === "supply" ? input.intrinsicYield ?? 0 : 0;
87911
+ const intrinsic = side2 === "supply" ? input.intrinsicYield ?? 0 : 0;
87790
87912
  return {
87791
87913
  kind,
87792
87914
  apr: base,
@@ -87825,10 +87947,10 @@ function buildMaturity(input, now) {
87825
87947
  }
87826
87948
  return { kind: "perpetual" };
87827
87949
  }
87828
- function buildFees(input, side) {
87950
+ function buildFees(input, side2) {
87829
87951
  const out = [];
87830
87952
  const ft = input.fixedTerm;
87831
- if (side === "borrow") {
87953
+ if (side2 === "borrow") {
87832
87954
  const origination = input.originationFee ?? ft?.fees?.originationFeePercent ?? void 0;
87833
87955
  if (isNum(origination) && origination !== 0) {
87834
87956
  out.push({
@@ -87870,7 +87992,7 @@ function buildFees(input, side) {
87870
87992
  });
87871
87993
  }
87872
87994
  }
87873
- if (side === "supply") {
87995
+ if (side2 === "supply") {
87874
87996
  if (isNum(ft?.fees?.continuousFeeApr) && ft.fees.continuousFeeApr !== 0) {
87875
87997
  out.push({
87876
87998
  id: "continuous",
@@ -87943,15 +88065,15 @@ function capUtil(total, cap) {
87943
88065
  if (!isNum(cap) || cap <= 0 || !isNum(total)) return void 0;
87944
88066
  return clamp013(total / cap);
87945
88067
  }
87946
- function buildAvailability(input, side) {
88068
+ function buildAvailability(input, side2) {
87947
88069
  const frozen = input.isFrozen === true;
87948
88070
  const inactive = input.isActive === false;
87949
- const enabled = side === "supply" ? input.depositsEnabled !== false : input.borrowingEnabled !== false;
87950
- const cap = side === "supply" ? input.supplyCap : input.borrowCap;
87951
- const total = side === "supply" ? input.totalDeposits : input.totalDebt;
88071
+ const enabled = side2 === "supply" ? input.depositsEnabled !== false : input.borrowingEnabled !== false;
88072
+ const cap = side2 === "supply" ? input.supplyCap : input.borrowCap;
88073
+ const total = side2 === "supply" ? input.totalDeposits : input.totalDebt;
87952
88074
  const capUtilization = capUtil(total, cap);
87953
88075
  const capFull = capUtilization != null && capUtilization >= 1;
87954
- const noLiquidity = side === "borrow" && isNum(input.borrowLiquidity) && input.borrowLiquidity <= 0;
88076
+ const noLiquidity = side2 === "borrow" && isNum(input.borrowLiquidity) && input.borrowLiquidity <= 0;
87955
88077
  const canOpen = enabled && !frozen && !inactive && !capFull && !noLiquidity;
87956
88078
  let blockedBy;
87957
88079
  if (!canOpen) {
@@ -87970,10 +88092,10 @@ function buildAvailability(input, side) {
87970
88092
  gating: "permissionless",
87971
88093
  // A borrow below the protocol's floor REVERTS, so gate the CTA on it
87972
88094
  // rather than letting the transaction fail.
87973
- minSize: side === "borrow" ? resolveMinDebt(input) : resolveMinCollateral(input),
88095
+ minSize: side2 === "borrow" ? resolveMinDebt(input) : resolveMinCollateral(input),
87974
88096
  cap: isNum(cap) && cap > 0 ? String(cap) : void 0,
87975
88097
  capUtilization,
87976
- requires: side === "supply" ? ["token-approval"] : void 0
88098
+ requires: side2 === "supply" ? ["token-approval"] : void 0
87977
88099
  };
87978
88100
  }
87979
88101
  function buildUtilization(input) {
@@ -88115,8 +88237,8 @@ function buildSupply(input, now, siblings) {
88115
88237
  return void 0;
88116
88238
  const rate = buildRate(input, "supply");
88117
88239
  const maturity = buildMaturity(input, now);
88118
- const fees = buildFees(input, "supply");
88119
- const availability = buildAvailability(input, "supply");
88240
+ const fees2 = buildFees(input, "supply");
88241
+ const availability2 = buildAvailability(input, "supply");
88120
88242
  const liquidity = isNum(input.totalLiquidity) ? {
88121
88243
  assets: input.totalLiquidity,
88122
88244
  assetsUsd: input.totalLiquidityUsd,
@@ -88132,16 +88254,16 @@ function buildSupply(input, now, siblings) {
88132
88254
  liquidity,
88133
88255
  partialAllowed: true,
88134
88256
  priceRisk: "none",
88135
- fees: fees.filter((f) => f.when === "exit" || f.when === "performance")
88257
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
88136
88258
  },
88137
- fees,
88259
+ fees: fees2,
88138
88260
  backedBy: buildExposures2(input, siblings, "backing"),
88139
88261
  modes: buildModes(input),
88140
88262
  counterparty: {
88141
88263
  kind: "pool",
88142
88264
  solvency: "overcollateralized"
88143
88265
  },
88144
- availability,
88266
+ availability: availability2,
88145
88267
  principal: { protected: true, risks: [] },
88146
88268
  info: { headline: "", description: "", tags: [] }
88147
88269
  };
@@ -88155,7 +88277,7 @@ function buildBorrow(input, now, siblings) {
88155
88277
  return void 0;
88156
88278
  const rate = buildRate(input, "borrow");
88157
88279
  const maturity = buildMaturity(input, now);
88158
- const fees = buildFees(input, "borrow");
88280
+ const fees2 = buildFees(input, "borrow");
88159
88281
  const acceptedCollateral = buildExposures2(input, siblings, "accepted");
88160
88282
  const borrow = {
88161
88283
  rate,
@@ -88169,12 +88291,12 @@ function buildBorrow(input, now, siblings) {
88169
88291
  // The same floor, read as a DUST limit: a partial repay may not leave
88170
88292
  // the position below it.
88171
88293
  minDebt: resolveMinDebt(input),
88172
- fees: fees.filter((f) => f.when === "exit" || f.when === "late")
88294
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "late")
88173
88295
  },
88174
88296
  liquidation: liquidationFrom(cfg, input, acceptedCollateral),
88175
88297
  acceptedCollateral,
88176
88298
  modes: buildModes(input),
88177
- fees,
88299
+ fees: fees2,
88178
88300
  counterparty: { kind: "pool", solvency: "overcollateralized" },
88179
88301
  availability: buildAvailability(input, "borrow"),
88180
88302
  info: { headline: "", description: "", tags: [] }
@@ -88213,6 +88335,17 @@ function finalizeInfo(sheet) {
88213
88335
  tags: deriveSupplyTags(sheet.supply, market)
88214
88336
  };
88215
88337
  }
88338
+ if (sheet.swap) {
88339
+ const sw = sheet.swap;
88340
+ for (const s of [sw.long, sw.short]) {
88341
+ s.info = {
88342
+ headline: s.info?.headline || swapSideHeadline(sw, s),
88343
+ description: s.info?.description || swapSideDescription(sw, s),
88344
+ implications: s.info?.implications ?? swapSideImplications(sw, s, sheet.governance),
88345
+ tags: deriveSwapTags(sw, s, sheet.governance)
88346
+ };
88347
+ }
88348
+ }
88216
88349
  if (sheet.borrow) {
88217
88350
  sheet.borrow.info = {
88218
88351
  headline: sheet.borrow.info.headline || borrowHeadline(sheet.borrow),
@@ -88287,8 +88420,8 @@ function buildTermSheet(input, opts = {}) {
88287
88420
  base.borrow?.acceptedCollateral ?? base.supply?.backedBy
88288
88421
  );
88289
88422
  const merged = mergeDeep(base, opts.patch);
88290
- for (const side of ["supply", "borrow"]) {
88291
- if (merged[side] && !base[side]) merged[side] = void 0;
88423
+ for (const side2 of ["supply", "borrow"]) {
88424
+ if (merged[side2] && !base[side2]) merged[side2] = void 0;
88292
88425
  }
88293
88426
  const withInfo = finalizeInfo(merged);
88294
88427
  withInfo.coverage = mergeAdapterCoverage(
@@ -88823,7 +88956,7 @@ function derivedRoutes(input, mode) {
88823
88956
  });
88824
88957
  return routes2.length > 0 ? routes2 : void 0;
88825
88958
  }
88826
- function buildExit(input, t, fees) {
88959
+ function buildExit(input, t, fees2) {
88827
88960
  const mode = resolveExitMode(input, t);
88828
88961
  const priceRisk = resolvePriceRisk(input, t);
88829
88962
  const ratio = input.instantLiquidityRatio ?? (isNum2(input.liquidity) && isNum2(input.totalAssets) && input.totalAssets > 0 ? clamp014(input.liquidity / input.totalAssets) : void 0);
@@ -88848,7 +88981,7 @@ function buildExit(input, t, fees) {
88848
88981
  priceRisk,
88849
88982
  // Only the request/queue models have something to cancel, and only where
88850
88983
  // the protocol exposes it — left undefined rather than guessed.
88851
- fees: fees.filter((f) => f.when === "exit" || f.when === "performance")
88984
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
88852
88985
  };
88853
88986
  }
88854
88987
  function resolvePriceRisk(input, t) {
@@ -89055,15 +89188,15 @@ function buildVaultTermSheet(input, opts = {}) {
89055
89188
  const now = opts.now ?? Math.floor(Date.now() / 1e3);
89056
89189
  const t = vaultTraits(input.provider) ?? FALLBACK_TRAITS;
89057
89190
  const maturity = buildMaturity2(input, now);
89058
- const fees = buildFees2(input, t);
89191
+ const fees2 = buildFees2(input, t);
89059
89192
  const supply = {
89060
89193
  // A vault share is never collateral IN the vault — it earns, full stop.
89061
89194
  // (It may be collateral somewhere else; that is the other market's sheet.)
89062
89195
  role: "yield",
89063
89196
  rate: buildRate2(input, t, maturity),
89064
89197
  maturity,
89065
- exit: buildExit(input, t, fees),
89066
- fees,
89198
+ exit: buildExit(input, t, fees2),
89199
+ fees: fees2,
89067
89200
  backedBy: buildBacking(input),
89068
89201
  counterparty: buildCounterparty(input, t),
89069
89202
  availability: buildAvailability2(input, now),
@@ -89740,7 +89873,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
89740
89873
  },
89741
89874
  maturity
89742
89875
  );
89743
- const availability = resolveAvailability(meta, maturity);
89876
+ const availability2 = resolveAvailability(meta, maturity);
89744
89877
  const exitMode = resolveExitMode2(provider, meta, tvl, liq);
89745
89878
  const market = {
89746
89879
  earnUid: buildVaultEarnUid(provider, chainId, address),
@@ -89838,7 +89971,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
89838
89971
  // not disagree about what the legs out are.
89839
89972
  routes: Array.isArray(meta.exitRoutes) ? meta.exitRoutes : void 0
89840
89973
  },
89841
- availability,
89974
+ availability: availability2,
89842
89975
  risk: {
89843
89976
  yieldProfile: yieldProfile(info.yieldProfile),
89844
89977
  denomination: denomination(info.denomination),
@@ -90013,15 +90146,15 @@ function sdkRates(row, provider) {
90013
90146
  totalRate: num15(row.depositRate)
90014
90147
  };
90015
90148
  }
90016
- const pct3 = (v) => {
90149
+ const pct4 = (v) => {
90017
90150
  const n = num15(v);
90018
90151
  return n === void 0 ? void 0 : n * 100;
90019
90152
  };
90020
90153
  return {
90021
90154
  // GMX splits fee APY from incentive APR; HyperCore reports one number.
90022
- supplyRate: pct3(row.baseApy ?? row.apr),
90023
- rewardsRate: pct3(row.bonusApr),
90024
- totalRate: pct3(row.apy ?? row.apr)
90155
+ supplyRate: pct4(row.baseApy ?? row.apr),
90156
+ rewardsRate: pct4(row.bonusApr),
90157
+ totalRate: pct4(row.apy ?? row.apr)
90025
90158
  };
90026
90159
  }
90027
90160
  function toVaultTermInput(vault, provider, chainId) {
@@ -90513,12 +90646,12 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
90513
90646
  tasks.push(
90514
90647
  (async () => {
90515
90648
  const gasPrice = await getEvmClient(chainId).getGasPrice();
90516
- const fees = await fetchGmxExecutionFees(
90649
+ const fees2 = await fetchGmxExecutionFees(
90517
90650
  chainId,
90518
90651
  multicallRetry,
90519
90652
  gasPrice
90520
90653
  );
90521
- if (fees) out.gmxExecutionFees = fees;
90654
+ if (fees2) out.gmxExecutionFees = fees2;
90522
90655
  })().catch((e) => {
90523
90656
  warn8(
90524
90657
  `[vaults] gmx execution-fee fetch failed for chain ${chainId}:`,
@@ -91635,12 +91768,12 @@ function assetFindings(sheet) {
91635
91768
  }
91636
91769
  return out;
91637
91770
  }
91638
- function findingsFor(sheet, side) {
91639
- const sideFindings = side === "supply" ? sheet.supply ? [...supplyFindings(sheet.supply), ...assetFindings(sheet)] : [] : sheet.borrow ? borrowFindings(sheet.borrow) : [];
91771
+ function findingsFor(sheet, side2) {
91772
+ const sideFindings = side2 === "supply" ? sheet.supply ? [...supplyFindings(sheet.supply), ...assetFindings(sheet)] : [] : sheet.borrow ? borrowFindings(sheet.borrow) : [];
91640
91773
  return rankFindings([...sideFindings, ...marketFindings(sheet)]);
91641
91774
  }
91642
- function hasCritical(sheet, side) {
91643
- return findingsFor(sheet, side).some((f) => f.severity === "critical");
91775
+ function hasCritical(sheet, side2) {
91776
+ return findingsFor(sheet, side2).some((f) => f.severity === "critical");
91644
91777
  }
91645
91778
  var exactlyAdapter = {
91646
91779
  id: "exactly",
@@ -92294,9 +92427,9 @@ var alchemixAdapter = {
92294
92427
  const isCollateralRow = input.collateralActive !== false;
92295
92428
  const protocolFeeBps = num17(a.protocolFeeBps);
92296
92429
  const liquidatorFeeBps = num17(a.liquidatorFeeBps);
92297
- const fees = [];
92430
+ const fees2 = [];
92298
92431
  if (protocolFeeBps != null)
92299
- fees.push({
92432
+ fees2.push({
92300
92433
  id: "redemption",
92301
92434
  label: "Redemption fee",
92302
92435
  // Charged whenever a Transmuter redemption settles part of the debt —
@@ -92312,7 +92445,7 @@ var alchemixAdapter = {
92312
92445
  description: "Taken from your collateral on the part of your debt that redemptions settle; the rest of the debt pays nothing."
92313
92446
  });
92314
92447
  if (liquidatorFeeBps != null)
92315
- fees.push({
92448
+ fees2.push({
92316
92449
  id: "liquidation-bonus",
92317
92450
  label: "Liquidator fee",
92318
92451
  when: "liquidation",
@@ -92412,7 +92545,7 @@ var alchemixAdapter = {
92412
92545
  defence: "Nothing exempts a position \u2014 redemptions are spread over every borrower in proportion to debt. They settle debt against your collateral at face value, so your LTV does not rise; the cost is the redemption fee on the settled part."
92413
92546
  }
92414
92547
  },
92415
- fees,
92548
+ fees: fees2,
92416
92549
  counterparty: {
92417
92550
  kind: "cdp",
92418
92551
  solvency: "overcollateralized",
@@ -92630,7 +92763,7 @@ var frankencoinAdapter = {
92630
92763
  const challengerPct = ppmToPercent(fc.challengerRewardPPM);
92631
92764
  const expiration = Number(fc.expiration ?? 0);
92632
92765
  const challengePeriod = Number(fc.challengePeriod ?? 0);
92633
- const fees = [
92766
+ const fees2 = [
92634
92767
  reservePct != null && reservePct > 0 ? {
92635
92768
  id: "reserve-contribution",
92636
92769
  label: "Equity-reserve contribution",
@@ -92701,7 +92834,7 @@ var frankencoinAdapter = {
92701
92834
  ] : void 0,
92702
92835
  badDebt: "socialized"
92703
92836
  },
92704
- fees,
92837
+ fees: fees2,
92705
92838
  counterparty: { kind: "cdp", solvency: "overcollateralized" }
92706
92839
  },
92707
92840
  constraints: {
@@ -93348,7 +93481,7 @@ function build2(input) {
93348
93481
  };
93349
93482
  if (!isNum4(input.originationFee) && input.borrowingEnabled === true)
93350
93483
  pending["borrow.fees"] = "the vault's borrow fee is not on the row";
93351
- const fees = isNum4(input.originationFee) && input.originationFee > 0 ? [
93484
+ const fees2 = isNum4(input.originationFee) && input.originationFee > 0 ? [
93352
93485
  {
93353
93486
  id: "origination",
93354
93487
  label: "Borrow fee",
@@ -93379,7 +93512,7 @@ function build2(input) {
93379
93512
  trigger: "price",
93380
93513
  seizure: "proportional"
93381
93514
  },
93382
- ...fees ? { fees } : {},
93515
+ ...fees2 ? { fees: fees2 } : {},
93383
93516
  ext: {
93384
93517
  jupiterLend: {
93385
93518
  fullLiquidationRule: "Past the liquidation threshold a liquidator repays part of the debt and takes collateral plus the penalty; past the max liquidation limit the position is liquidated entirely.",
@@ -94407,6 +94540,24 @@ function toDigest(sheet) {
94407
94540
  tags: sheet.borrow.info.tags,
94408
94541
  acceptedCollateral: strip(sheet.borrow.acceptedCollateral)
94409
94542
  } : void 0,
94543
+ swap: sheet.swap ? {
94544
+ kind: sheet.swap.kind,
94545
+ underlying: sheet.swap.notional.underlying,
94546
+ venue: sheet.swap.floating.venue,
94547
+ maturity: sheet.swap.maturity.maturity,
94548
+ markApr: sheet.swap.fixed.markApr,
94549
+ floatingApr: sheet.swap.floating.apr,
94550
+ long: {
94551
+ headline: sheet.swap.long.info.headline,
94552
+ canOpen: sheet.swap.long.availability.canOpen,
94553
+ fixedApr: sheet.swap.long.fixedApr
94554
+ },
94555
+ short: {
94556
+ headline: sheet.swap.short.info.headline,
94557
+ canOpen: sheet.swap.short.availability.canOpen,
94558
+ fixedApr: sheet.swap.short.fixedApr
94559
+ }
94560
+ } : void 0,
94410
94561
  oracle: sheet.oracle ? {
94411
94562
  kind: sheet.oracle.kind,
94412
94563
  address: sheet.oracle.address,
@@ -94546,42 +94697,42 @@ function validateTermSheet(sheet) {
94546
94697
  if (sheet.schemaVersion !== TERM_SHEET_SCHEMA_VERSION)
94547
94698
  fail("schema-version", `unexpected schemaVersion ${sheet.schemaVersion}`);
94548
94699
  if (!sheet.profileId) fail("profile-id", "missing profileId");
94549
- for (const side of ["supply", "borrow"]) {
94550
- const s = sheet[side];
94700
+ for (const side2 of ["supply", "borrow"]) {
94701
+ const s = sheet[side2];
94551
94702
  if (!s) continue;
94552
94703
  const c = s.rate.components;
94553
94704
  const expected = (c.base ?? 0) + (c.rewards ?? 0) + (c.intrinsic ?? 0);
94554
94705
  if (!approx(s.rate.aprTotal, expected, 1e-6))
94555
94706
  fail(
94556
94707
  "apr-total",
94557
- `${side}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
94708
+ `${side2}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
94558
94709
  );
94559
94710
  const priceable = (s.rate.rewards ?? []).filter((r) => !r.indicative).reduce((sum3, r) => sum3 + r.apr, 0);
94560
94711
  if (s.rate.rewards && !approx(c.rewards ?? 0, priceable, 1e-6))
94561
94712
  fail(
94562
94713
  "rewards-priceable",
94563
- `${side}.rate.components.rewards ${c.rewards} != sum of non-indicative rewards ${priceable}`
94714
+ `${side2}.rate.components.rewards ${c.rewards} != sum of non-indicative rewards ${priceable}`
94564
94715
  );
94565
94716
  if (s.rate.basis !== "apr-nominal")
94566
- fail("rate-basis", `${side}.rate.basis must be apr-nominal`);
94717
+ fail("rate-basis", `${side2}.rate.basis must be apr-nominal`);
94567
94718
  if (s.maturity.kind === "fixed-date" && s.maturity.maturity == null)
94568
94719
  fail(
94569
94720
  "maturity-missing",
94570
- `${side}.maturity.kind is fixed-date with no maturity`
94721
+ `${side2}.maturity.kind is fixed-date with no maturity`
94571
94722
  );
94572
94723
  if ((s.rate.kind === "fixed-term" || s.rate.kind === "fixed-open") && s.rate.kind === "fixed-term" && s.maturity.kind === "perpetual")
94573
94724
  fail(
94574
94725
  "fixed-term-perpetual",
94575
- `${side} is fixed-term but maturity.kind is perpetual`
94726
+ `${side2} is fixed-term but maturity.kind is perpetual`
94576
94727
  );
94577
94728
  if (s.availability.canOpen === false && !s.availability.blockedBy)
94578
94729
  fail(
94579
94730
  "blocked-reason",
94580
- `${side}.availability.canOpen is false with no blockedBy`
94731
+ `${side2}.availability.canOpen is false with no blockedBy`
94581
94732
  );
94582
- if (!s.info.headline) fail("headline", `${side}.info.headline is empty`);
94733
+ if (!s.info.headline) fail("headline", `${side2}.info.headline is empty`);
94583
94734
  if (!Array.isArray(s.info.tags))
94584
- fail("tags", `${side}.info.tags is not an array`);
94735
+ fail("tags", `${side2}.info.tags is not an array`);
94585
94736
  }
94586
94737
  if (sheet.supply) {
94587
94738
  const e = sheet.supply.exit;
@@ -94592,6 +94743,44 @@ function validateTermSheet(sheet) {
94592
94743
  fail("instant-cooldown", "exit.mode instant must not carry a cooldown");
94593
94744
  }
94594
94745
  }
94746
+ const sw = sheet.swap;
94747
+ if (sw) {
94748
+ if (sheet.supply || sheet.borrow)
94749
+ fail("swap-exclusive", "a swap sheet must not also carry supply/borrow");
94750
+ if (sw.maturity.kind !== "fixed-date" || sw.maturity.maturity == null)
94751
+ fail("swap-maturity", "a rate swap must carry a fixed-date maturity");
94752
+ const m = sw.margin;
94753
+ if (!(m.initialFactor > 0) || !(m.maintenanceFactor > 0))
94754
+ fail("swap-margin-factors", "margin factors must be > 0");
94755
+ else if (m.maintenanceFactor > m.initialFactor)
94756
+ fail(
94757
+ "swap-margin-order",
94758
+ `maintenance factor ${m.maintenanceFactor} above initial ${m.initialFactor}`
94759
+ );
94760
+ if (!(m.rateFloor >= 0) || !Number.isFinite(m.rateFloor))
94761
+ fail(
94762
+ "swap-rate-floor",
94763
+ `margin.rateFloor ${m.rateFloor} is not a finite APR fraction`
94764
+ );
94765
+ for (const s of [sw.long, sw.short]) {
94766
+ if (s.pays === s.receives)
94767
+ fail("swap-legs", `${s.side} pays and receives the same leg`);
94768
+ const expected = s.receives === "fixed" ? "floating-up" : "floating-down";
94769
+ if (s.adverseMove !== expected)
94770
+ fail("swap-adverse", `${s.side}.adverseMove must be ${expected}`);
94771
+ if (!s.info?.headline)
94772
+ fail("headline", `swap.${s.side}.info.headline is empty`);
94773
+ if (s.availability.canOpen === false && !s.availability.blockedBy)
94774
+ fail(
94775
+ "blocked-reason",
94776
+ `swap.${s.side}.availability.canOpen is false with no blockedBy`
94777
+ );
94778
+ }
94779
+ if (sw.long.receives === sw.short.receives)
94780
+ fail("swap-sides", "long and short receive the same leg");
94781
+ if (sw.fees.some((f) => f.basis !== "notional"))
94782
+ fail("swap-fee-basis", "every swap fee is charged on notional");
94783
+ }
94595
94784
  if (sheet.borrow) {
94596
94785
  const l = sheet.borrow.liquidation;
94597
94786
  if (l.seizure === "full-collateral") {
@@ -94709,11 +94898,11 @@ function validateTermSheet(sheet) {
94709
94898
  `timelockSecs set but controllerKind is ${g.controllerKind}`
94710
94899
  );
94711
94900
  }
94712
- for (const side of ["supply", "borrow"]) {
94713
- const modes = sheet[side]?.modes;
94901
+ for (const side2 of ["supply", "borrow"]) {
94902
+ const modes = sheet[side2]?.modes;
94714
94903
  if (!modes) continue;
94715
94904
  if (modes.filter((m) => m.isDefault).length > 1)
94716
- fail("multiple-defaults", `${side}.modes has more than one isDefault`);
94905
+ fail("multiple-defaults", `${side2}.modes has more than one isDefault`);
94717
94906
  }
94718
94907
  return v;
94719
94908
  }
@@ -94916,7 +95105,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
94916
95105
  kind: resolveRateKind2(venue),
94917
95106
  source: "chain"
94918
95107
  };
94919
- const availability = resolveAvailability2(row, flags, rate.total ?? 0);
95108
+ const availability2 = resolveAvailability2(row, flags, rate.total ?? 0);
94920
95109
  const basket = resolveBasket(row, chainId);
94921
95110
  return {
94922
95111
  earnUid,
@@ -94981,7 +95170,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
94981
95170
  // utilization cannot be exited, and calling that `instant` is the kind of
94982
95171
  // small lie that produces a stuck user.
94983
95172
  exit: { mode: "instant-capped", settlement: "sync" },
94984
- availability,
95173
+ availability: availability2,
94985
95174
  risk: {
94986
95175
  score: num14(row.risk?.score),
94987
95176
  label: str6(row.risk?.label),
@@ -95929,6 +96118,655 @@ function earnPositionTotals(items) {
95929
96118
  };
95930
96119
  }
95931
96120
 
95932
- export { ALCHEMIX_BLOCK_SECONDS, ApiBookSource, 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, 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, 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, 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, borrowDescription, borrowFindings, borrowHeadline, buildExposures2 as buildExposures, buildFluidFTokensCall, buildLendingPositionUid, buildLiquityUserCall, buildLoopResult, buildMorphoTypeCall, buildMorphoTypeUserCallWithLens, buildPortfolioTotals, buildQueriesFromMeta, 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, convertCoolerMarketsToResponse, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFlyingTulipMarketsToResponse, convertFrankencoinMarketsToResponse, convertFraxlendPairsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRipeMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMultiAccountTypeUserState, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, detectInterfaceKinds, dexResolverFor, disambiguateEarnNames, disambiguateOrderBookNames, 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, fetchCoolerMarkets, fetchDolomiteAccountNumbers, fetchDolomiteSubAccounts, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, 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, formatRaw, frankencoinKeyParts, frankencoinLenderKey, fraxlendAssetPerCollateral, fraxlendKeyParts, fraxlendLenderKey, 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, isSecondaryMarketOnly, isStablecoinSymbol, isSyntheticQuoteUnit, isUnearnableEarnRate, isUnrealizableEarnRate, isVaultPosition, isVaultVenue, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, 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, assetKey as pendleAssetKey, pickPool as pickSpectraPool, positivePart2 as positivePart, predictInverseEscrow, prepareLenderUserDataRpcCalls, prepareMergedMulticallParams, prepareMergedRpcCalls, prepareMulticallInputs, prepareTokenBalanceRpcCalls, priceGlvVaults, priceGmMarkets, probeAaveFeedTimestamps, protocolConsensus, protocolOf, pruneFeedStats, 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, stampVaultClassification, stampVaultTermSheets, stripLeadingBrand, subAccountsOf, supplyDescription, supplyFindings, supplyHeadline, svmEarnBuildability, svmEarnBuilderKey, swapRoutedProvidersArePriceConsistent, 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, withMaturityLabel, withTrancheLabel };
96121
+ // src/boros/api.ts
96122
+ var BOROS_API_BASE = "https://api.boros.finance/open-api";
96123
+ var TIMEOUT_MS7 = 8e3;
96124
+ var BorosApiError = class extends Error {
96125
+ constructor(message2, status, errorCode) {
96126
+ super(message2);
96127
+ this.status = status;
96128
+ this.errorCode = errorCode;
96129
+ }
96130
+ status;
96131
+ errorCode;
96132
+ };
96133
+ async function borosApi(path, init, fetchImpl = fetch) {
96134
+ const res = await fetchImpl.call(globalThis, `${BOROS_API_BASE}${path}`, {
96135
+ method: init?.method ?? "GET",
96136
+ headers: {
96137
+ accept: "application/json",
96138
+ ...init?.body !== void 0 ? { "content-type": "application/json" } : {}
96139
+ },
96140
+ body: init?.body !== void 0 ? JSON.stringify(init.body) : void 0,
96141
+ signal: AbortSignal.timeout(TIMEOUT_MS7)
96142
+ });
96143
+ const text = await res.text();
96144
+ let json;
96145
+ try {
96146
+ json = text ? JSON.parse(text) : void 0;
96147
+ } catch {
96148
+ json = void 0;
96149
+ }
96150
+ if (!res.ok) {
96151
+ const msg = Array.isArray(json?.message) ? json.message.map((m) => `${m?.property}: ${(m?.messages ?? []).join(", ")}`).join("; ") : json?.message ?? text.slice(0, 200);
96152
+ throw new BorosApiError(
96153
+ `Boros API ${path.split("?")[0]}: HTTP ${res.status} \u2014 ${msg}`,
96154
+ res.status,
96155
+ json?.errorCode
96156
+ );
96157
+ }
96158
+ return json;
96159
+ }
96160
+ var fromWad = (v) => {
96161
+ if (v === null || v === void 0 || v === "") return 0;
96162
+ try {
96163
+ const b = BigInt(String(v));
96164
+ const neg = b < 0n;
96165
+ const a = neg ? -b : b;
96166
+ const out = Number(a / 10n ** 12n) / 1e6;
96167
+ return neg ? -out : out;
96168
+ } catch {
96169
+ const n = Number(v);
96170
+ return Number.isFinite(n) ? n / 1e18 : 0;
96171
+ }
96172
+ };
96173
+
96174
+ // src/boros/termSheet.ts
96175
+ var BOROS_PROFILE_ID = "boros.funding-swap@v1";
96176
+ var ARBITRUM = "42161";
96177
+ var BOROS_GOVERNANCE = {
96178
+ mutability: "governed",
96179
+ controller: "0x7417407a24194180017201bfec07fb4fe5a566e0",
96180
+ controllerKind: "SAFE",
96181
+ safe: { threshold: 2, owners: 3 },
96182
+ powers: [
96183
+ "upgrade-implementation",
96184
+ "change-fees",
96185
+ "change-ltv",
96186
+ "set-caps",
96187
+ "freeze-market"
96188
+ ]
96189
+ };
96190
+ var MIN_CASH_USD = 10;
96191
+ var WITHDRAWAL_COOLDOWN_SECS = 900;
96192
+ var FORCED_DELEVERAGE_HEALTH = 0.7;
96193
+ var spreadVenues = (m) => {
96194
+ if (!m.isSpread) return void 0;
96195
+ const parts = m.name.split(" - ").map((p) => p.trim().split(/\s+/)[0]);
96196
+ return parts.length >= 2 ? parts : void 0;
96197
+ };
96198
+ function fees(m) {
96199
+ const out = [
96200
+ {
96201
+ id: "origination",
96202
+ label: "Taker fee (\xD7 years to maturity)",
96203
+ when: "entry",
96204
+ unit: "apr-percent",
96205
+ basis: "notional",
96206
+ value: m.fees.takerFee * 100,
96207
+ payee: "protocol",
96208
+ mutable: true,
96209
+ description: "Charged once on the filled size, scaled by the time left to maturity. Resting (maker) orders pay none."
96210
+ }
96211
+ ];
96212
+ if (m.fees.settleFee != null)
96213
+ out.push({
96214
+ id: "settlement",
96215
+ label: "Settlement fee",
96216
+ when: "ongoing",
96217
+ unit: "apr-percent",
96218
+ basis: "notional",
96219
+ value: m.fees.settleFee * 100,
96220
+ payee: "protocol",
96221
+ mutable: true,
96222
+ description: "Charged on the open size at every funding settlement."
96223
+ });
96224
+ if (m.margin.liquidation)
96225
+ out.push({
96226
+ id: "liquidation-bonus",
96227
+ label: "Liquidation fee (\xD7 years to maturity)",
96228
+ when: "liquidation",
96229
+ unit: "apr-percent",
96230
+ basis: "notional",
96231
+ value: m.margin.liquidation.feeRate * 100,
96232
+ payee: "protocol",
96233
+ mutable: true,
96234
+ description: "Treasury fee on the liquidated size, on top of the liquidator incentive."
96235
+ });
96236
+ return out;
96237
+ }
96238
+ function availability(m, fixedApr) {
96239
+ const tradable = m.state === "Normal" && m.timeToMaturitySec > 0;
96240
+ const capFull = m.openInterestCap?.hard != null && m.openInterest != null && m.openInterest.units >= m.openInterestCap.hard;
96241
+ const canOpen = tradable && !capFull && fixedApr != null;
96242
+ return {
96243
+ canOpen,
96244
+ canClose: tradable,
96245
+ ...canOpen ? {} : {
96246
+ blockedBy: !tradable ? m.timeToMaturitySec > 0 ? "paused" : "shutdown" : capFull ? "cap-full" : "no-liquidity"
96247
+ },
96248
+ gating: "permissionless",
96249
+ requires: ["token-approval"],
96250
+ ...m.openInterestCap?.hard != null ? {
96251
+ cap: String(m.openInterestCap.hard),
96252
+ capUtilization: m.openInterest && m.openInterestCap.hard > 0 ? Math.min(1, m.openInterest.units / m.openInterestCap.hard) : void 0
96253
+ } : {}
96254
+ };
96255
+ }
96256
+ function side(m, s) {
96257
+ const fixedApr = (s === "long" ? m.rates.bestAskApr : m.rates.bestBidApr) ?? void 0;
96258
+ const floating = m.rates.floatingApr ?? void 0;
96259
+ const carryApr = fixedApr != null && floating != null ? s === "short" ? fixedApr - floating : floating - fixedApr : void 0;
96260
+ return {
96261
+ side: s,
96262
+ pays: s === "long" ? "fixed" : "floating",
96263
+ receives: s === "long" ? "floating" : "fixed",
96264
+ ...fixedApr != null ? { fixedApr } : {},
96265
+ ...carryApr != null ? { carryApr } : {},
96266
+ adverseMove: s === "short" ? "floating-up" : "floating-down",
96267
+ availability: availability(m, fixedApr),
96268
+ // filled by finalizeInfo from the structured fields
96269
+ info: { headline: "", description: "", tags: [] }
96270
+ };
96271
+ }
96272
+ function buildBorosTermSheet(m, nowSec9 = Math.floor(Date.now() / 1e3)) {
96273
+ const collateral = {
96274
+ chainId: ARBITRUM,
96275
+ address: m.collateral.address,
96276
+ symbol: m.collateral.symbol,
96277
+ decimals: m.collateral.decimals
96278
+ };
96279
+ const swap = {
96280
+ kind: "funding-rate-swap",
96281
+ notional: { unit: collateral, underlying: m.asset },
96282
+ floating: {
96283
+ source: "perp-funding",
96284
+ venue: m.venue,
96285
+ ...spreadVenues(m) ? { spreadOf: spreadVenues(m) } : {},
96286
+ ...m.rates.floatingApr != null ? { apr: m.rates.floatingApr } : {},
96287
+ ...m.paymentPeriodSec ? { settlementSecs: m.paymentPeriodSec } : {}
96288
+ },
96289
+ fixed: {
96290
+ source: m.ammId ? "orderbook-amm" : "orderbook",
96291
+ ...m.rates.markApr != null ? { markApr: m.rates.markApr } : {},
96292
+ ...m.rates.bestBidApr != null ? { bestBidApr: m.rates.bestBidApr } : {},
96293
+ ...m.rates.bestAskApr != null ? { bestAskApr: m.rates.bestAskApr } : {}
96294
+ },
96295
+ maturity: {
96296
+ kind: "fixed-date",
96297
+ maturity: m.maturity,
96298
+ maturityIso: new Date(m.maturity * 1e3).toISOString(),
96299
+ secondsToMaturity: Math.max(0, m.maturity - nowSec9),
96300
+ atMaturity: "settles"
96301
+ },
96302
+ margin: {
96303
+ model: m.isIsolatedOnly ? "isolated" : "cross-or-isolated",
96304
+ initialFactor: m.margin.kIM,
96305
+ maintenanceFactor: m.margin.kMM,
96306
+ rateFloor: m.margin.rateFloor,
96307
+ timeFloorSecs: m.margin.tThreshSec,
96308
+ ...m.maxLeverage != null ? { maxLeverage: m.maxLeverage } : {},
96309
+ minCashUsd: MIN_CASH_USD,
96310
+ formula: "IM = |size| \xD7 max(|rate|, rateFloor) \xD7 initialFactor \xD7 max(timeToMaturity, timeFloor); MM uses maintenanceFactor at the mark rate"
96311
+ },
96312
+ liquidation: {
96313
+ healthThreshold: 1,
96314
+ forcedDeleverageHealth: FORCED_DELEVERAGE_HEALTH,
96315
+ ...m.margin.liquidation ? {
96316
+ incentive: {
96317
+ base: m.margin.liquidation.incentiveBase,
96318
+ slope: m.margin.liquidation.incentiveSlope
96319
+ }
96320
+ } : {},
96321
+ model: "position-transfer"
96322
+ },
96323
+ exit: {
96324
+ close: "market-trade",
96325
+ priceRisk: "market-price",
96326
+ withdrawalCooldownSecs: WITHDRAWAL_COOLDOWN_SECS,
96327
+ requestResetsCooldown: true,
96328
+ finalizePermissionless: true
96329
+ },
96330
+ fees: fees(m),
96331
+ counterparty: {
96332
+ kind: "orderbook",
96333
+ address: m.address,
96334
+ solvency: "margined"
96335
+ },
96336
+ ...m.openInterestCap ? {
96337
+ openInterestCap: {
96338
+ hard: m.openInterestCap.hard,
96339
+ ...m.openInterestCap.softPct != null ? { softPct: m.openInterestCap.softPct } : {},
96340
+ ...m.openInterest ? { current: m.openInterest.units } : {}
96341
+ }
96342
+ } : {},
96343
+ principal: {
96344
+ protected: false,
96345
+ risks: ["margin-loss", "liquidation", "basis", "roll"]
96346
+ },
96347
+ long: side(m, "long"),
96348
+ short: side(m, "short")
96349
+ };
96350
+ const sheet = {
96351
+ schemaVersion: TERM_SHEET_SCHEMA_VERSION,
96352
+ asOf: nowSec9,
96353
+ profileId: BOROS_PROFILE_ID,
96354
+ marketUid: `BOROS:${ARBITRUM}:${m.marketId}`,
96355
+ lender: "BOROS",
96356
+ chainId: ARBITRUM,
96357
+ asset: collateral,
96358
+ swap,
96359
+ governance: BOROS_GOVERNANCE,
96360
+ ...m.fundingOracle ? {
96361
+ oracle: {
96362
+ kind: "rate-feed",
96363
+ address: m.fundingOracle.address,
96364
+ provider: "Pendle Boros funding index",
96365
+ priceDescription: `${m.venue} ${m.asset} funding`,
96366
+ ...m.fundingOracle.maxUpdateDelaySec ? { heartbeatSecs: m.fundingOracle.maxUpdateDelaySec } : {}
96367
+ }
96368
+ } : {},
96369
+ coverage: {
96370
+ present: ["swap", "governance", ...m.fundingOracle ? ["oracle"] : []],
96371
+ notApplicable: {
96372
+ supply: "a rate swap lends nothing",
96373
+ borrow: "a rate swap borrows nothing",
96374
+ utilization: "no pool \u2014 rates are set by the order book",
96375
+ exposures: "no collateral backs a loan; each side posts its own margin"
96376
+ },
96377
+ pending: {
96378
+ ...m.fundingOracle ? {} : { oracle: "funding-index oracle not published for this market" },
96379
+ "governance.markets": "market contracts are beacon proxies; the beacon owner is not resolved",
96380
+ "governance.roles": "parameter setters are role-gated (PendleRoles); the role holders are not enumerated"
96381
+ }
96382
+ }
96383
+ };
96384
+ return finalizeInfo(sheet);
96385
+ }
96386
+
96387
+ // src/boros/markets.ts
96388
+ var pct3 = (v) => {
96389
+ const n = typeof v === "number" ? v : Number(v);
96390
+ return v === null || v === void 0 || !Number.isFinite(n) ? null : n * 100;
96391
+ };
96392
+ async function fetchBorosCollaterals(fetchImpl) {
96393
+ const r = await borosApi(
96394
+ "/v1/assets/all",
96395
+ void 0,
96396
+ fetchImpl
96397
+ );
96398
+ return (r?.assets ?? []).filter((a) => Number(a.tokenId) > 0).map((a) => ({
96399
+ tokenId: Number(a.tokenId),
96400
+ address: a.address.toLowerCase(),
96401
+ symbol: a.symbol,
96402
+ decimals: Number(a.decimals),
96403
+ priceUsd: Number(a.usdPrice) || 0
96404
+ }));
96405
+ }
96406
+ function convertBorosMarket(m, collaterals, nowSec9 = Math.floor(Date.now() / 1e3)) {
96407
+ const tokenId = Number(m?.tokenId);
96408
+ const collateral = collaterals.get(tokenId);
96409
+ if (!collateral || !m?.imData) return null;
96410
+ const d = m.data ?? {};
96411
+ const cfg = m.config ?? {};
96412
+ const ext = m.extConfig ?? {};
96413
+ const meta = m.metadata ?? {};
96414
+ const ammId = Number(ext.ammId ?? meta.ammId ?? 0);
96415
+ const ammAddress = ext.ammAddress ?? meta.ammAddress;
96416
+ const usd = (units) => units * collateral.priceUsd;
96417
+ const oi = Number(d.notionalOI);
96418
+ const vol = Number(d.volume24h);
96419
+ const maturity = Number(m.imData.maturity);
96420
+ const market = {
96421
+ marketId: Number(m.marketId),
96422
+ address: String(m.address).toLowerCase(),
96423
+ symbol: m.imData.symbol,
96424
+ name: m.imData.name,
96425
+ venue: meta.platformName ?? "",
96426
+ asset: meta.assetSymbol ?? "",
96427
+ isSpread: Boolean(meta.isSpreadMarket),
96428
+ maturity,
96429
+ timeToMaturitySec: Math.max(0, maturity - nowSec9),
96430
+ collateral,
96431
+ isIsolatedOnly: Boolean(m.imData.isIsolatedOnly),
96432
+ state: m.state ?? "",
96433
+ maxLeverage: Number.isFinite(Number(meta.maxLeverage)) ? Number(meta.maxLeverage) : null,
96434
+ tickStep: Number(m.imData.tickStep),
96435
+ ammId: ammId > 0 ? ammId : null,
96436
+ ammAddress: ammAddress && !/^0x0{40}$/i.test(ammAddress) ? String(ammAddress).toLowerCase() : null,
96437
+ paymentPeriodSec: Number(ext.paymentPeriod) || null,
96438
+ rates: {
96439
+ markApr: pct3(d.markApr),
96440
+ floatingApr: pct3(d.floatingApr),
96441
+ midApr: pct3(d.midApr),
96442
+ bestBidApr: pct3(d.bestBid),
96443
+ bestAskApr: pct3(d.bestAsk),
96444
+ lastTradedApr: pct3(d.lastTradedApr),
96445
+ ammImpliedApr: pct3(d.ammImpliedApr)
96446
+ },
96447
+ openInterest: Number.isFinite(oi) ? { units: oi, usd: usd(oi) } : null,
96448
+ volume24h: Number.isFinite(vol) ? { units: vol, usd: usd(vol) } : null,
96449
+ fees: {
96450
+ takerFee: fromWad(cfg.takerFee),
96451
+ otcFee: fromWad(cfg.otcFee),
96452
+ settleFee: ext.settleFeeRate != null ? fromWad(ext.settleFeeRate) : null
96453
+ },
96454
+ margin: {
96455
+ kIM: fromWad(cfg.kIM),
96456
+ kMM: fromWad(cfg.kMM),
96457
+ rateFloor: Number(m.imData.marginFloor) || 0,
96458
+ iTickThresh: Number(m.imData.iTickThresh),
96459
+ tThreshSec: Number(cfg.tThresh) || 0,
96460
+ liquidation: cfg.liqSettings ? {
96461
+ incentiveBase: fromWad(cfg.liqSettings.base),
96462
+ incentiveSlope: fromWad(cfg.liqSettings.slope),
96463
+ feeRate: fromWad(cfg.liqSettings.feeRate)
96464
+ } : null
96465
+ },
96466
+ openInterestCap: cfg.hardOICap != null ? {
96467
+ hard: fromWad(cfg.hardOICap),
96468
+ softPct: cfg.softOICap != null ? Number(cfg.softOICap) / 100 : null
96469
+ } : null,
96470
+ fundingOracle: cfg.fIndexOracle && !/^0x0{40}$/i.test(cfg.fIndexOracle) ? {
96471
+ address: String(cfg.fIndexOracle).toLowerCase(),
96472
+ maxUpdateDelaySec: Number(ext.maxUpdateDelay) || null
96473
+ } : null
96474
+ };
96475
+ market.termSheet = buildBorosTermSheet(market, nowSec9);
96476
+ return market;
96477
+ }
96478
+ var MEMO_MS2 = 3e4;
96479
+ var memo2;
96480
+ async function fetchBorosMarkets(opts = {}) {
96481
+ const now = Date.now();
96482
+ if (!opts.fresh && memo2 && now - memo2.at < MEMO_MS2) return memo2.value;
96483
+ const value = (async () => {
96484
+ const [collaterals, list] = await Promise.all([
96485
+ fetchBorosCollaterals(opts.fetchImpl),
96486
+ borosApi(
96487
+ "/v1/markets?limit=100&isWhitelisted=true",
96488
+ void 0,
96489
+ opts.fetchImpl
96490
+ )
96491
+ ]);
96492
+ const byId = new Map(collaterals.map((c) => [c.tokenId, c]));
96493
+ const nowSec9 = Math.floor(Date.now() / 1e3);
96494
+ return (list?.results ?? []).map((m) => convertBorosMarket(m, byId, nowSec9)).filter((m) => m !== null).sort((a, b) => a.maturity - b.maturity || a.marketId - b.marketId);
96495
+ })();
96496
+ memo2 = { at: now, value };
96497
+ value.catch(() => {
96498
+ if (memo2?.value === value) memo2 = void 0;
96499
+ });
96500
+ return value;
96501
+ }
96502
+ async function fetchBorosMarket(marketId, opts = {}) {
96503
+ return (await fetchBorosMarkets(opts)).find((m) => m.marketId === marketId);
96504
+ }
96505
+
96506
+ // src/boros/book.ts
96507
+ var TICK_SIZE = 1e-4;
96508
+ async function fetchBorosOrderBook(marketId, fetchImpl) {
96509
+ const r = await borosApi(
96510
+ `/v2/markets/order-books?marketId=${marketId}&tickSize=${TICK_SIZE}&includeAmm=true`,
96511
+ void 0,
96512
+ fetchImpl
96513
+ );
96514
+ const side2 = (s) => {
96515
+ const ia = Array.isArray(s?.ia) ? s.ia : [];
96516
+ const sz = Array.isArray(s?.sz) ? s.sz : [];
96517
+ return ia.map((t, i) => ({ aprPct: t * TICK_SIZE * 100, size: fromWad(sz[i]) })).filter((l) => l.size > 0);
96518
+ };
96519
+ return {
96520
+ marketId,
96521
+ bids: side2(r?.long).sort((a, b) => b.aprPct - a.aprPct),
96522
+ asks: side2(r?.short).sort((a, b) => a.aprPct - b.aprPct)
96523
+ };
96524
+ }
96525
+
96526
+ // src/boros/positions.ts
96527
+ var CROSS = "ffffff";
96528
+ var marketAccOf = (root, tokenId, marketHex = CROSS) => `${root.toLowerCase()}00${tokenId.toString(16).padStart(4, "0")}${marketHex}`;
96529
+ var pctOrNull = (v) => v === null || v === void 0 || v === "" ? null : fromWad(v) * 100;
96530
+ async function fetchBorosAccount(account, fetchImpl) {
96531
+ const root = account.toLowerCase();
96532
+ const [active, collaterals] = await Promise.all([
96533
+ borosApi(
96534
+ `/v1/accounts/active-positions?userAddress=${root}&accountId=0`,
96535
+ void 0,
96536
+ fetchImpl
96537
+ ),
96538
+ fetchBorosCollaterals(fetchImpl)
96539
+ ]);
96540
+ const positionsRaw = active?.results ?? [];
96541
+ const marketAccs = collaterals.map((c) => marketAccOf(root, c.tokenId));
96542
+ const infos = marketAccs.length ? await borosApi(
96543
+ "/v1/accounts/market-acc-infos",
96544
+ { method: "POST", body: { marketAccs } },
96545
+ fetchImpl
96546
+ ) : { results: [] };
96547
+ const byMarket = /* @__PURE__ */ new Map();
96548
+ const crossAccounts = [];
96549
+ for (const info of infos?.results ?? []) {
96550
+ const acc = String(info?.marketAcc ?? "").toLowerCase();
96551
+ const tokenId = parseInt(acc.slice(44, 48), 16);
96552
+ const positions2 = Array.isArray(info?.positions) ? info.positions : [];
96553
+ for (const p of positions2) byMarket.set(Number(p.marketId), p);
96554
+ const maint = positions2.reduce((s, p) => s + fromWad(p?.maintMargin), 0);
96555
+ const net = fromWad(info?.netBalance);
96556
+ const cash = fromWad(info?.totalCash);
96557
+ if (cash === 0 && net === 0 && positions2.length === 0) continue;
96558
+ crossAccounts.push({
96559
+ tokenId,
96560
+ marketAcc: acc,
96561
+ collateral: collaterals.find((c) => c.tokenId === tokenId) ?? null,
96562
+ totalCash: cash,
96563
+ netBalance: net,
96564
+ initialMargin: fromWad(info?.initialMargin),
96565
+ availableInitialMargin: fromWad(info?.availableInitialMargin),
96566
+ availableMaintMargin: fromWad(info?.availableMaintMargin),
96567
+ healthRatio: maint > 0 ? net / maint : null
96568
+ });
96569
+ }
96570
+ const positions = positionsRaw.map((p) => {
96571
+ const info = byMarket.get(Number(p.marketId));
96572
+ const size = fromWad(p.signedSize);
96573
+ return {
96574
+ marketId: Number(p.marketId),
96575
+ marketAcc: String(p.marketAcc).toLowerCase(),
96576
+ isCross: Boolean(p.isCross),
96577
+ side: Number(p.side) === 1 ? "short" : "long",
96578
+ signedSize: String(p.signedSize),
96579
+ size: Math.abs(size),
96580
+ fixedAprPct: p.fixedApr === null || p.fixedApr === void 0 ? null : Number(p.fixedApr) * 100,
96581
+ cumulativePnl: p.cumulativePnl != null ? fromWad(p.cumulativePnl) : null,
96582
+ isMatured: Boolean(p.isMatured),
96583
+ liquidationAprPct: info ? pctOrNull(info.liquidationApr) : null,
96584
+ initialMargin: info ? fromWad(info.initialMargin) : null,
96585
+ maintMargin: info ? fromWad(info.maintMargin) : null,
96586
+ positionValue: info ? fromWad(info.positionValue) : null
96587
+ };
96588
+ });
96589
+ return { account: root, positions, crossAccounts };
96590
+ }
96591
+
96592
+ // src/boros/margin.ts
96593
+ var SECONDS_PER_YEAR20 = 365 * 24 * 3600;
96594
+ var ttmYears = (m, ttmSec) => Math.max(ttmSec ?? m.timeToMaturitySec, m.margin.tThreshSec) / SECONDS_PER_YEAR20;
96595
+ function borosInitialMargin(m, size, ratePct, ttmSec) {
96596
+ const r = Math.max(Math.abs(ratePct) / 100, m.margin.rateFloor);
96597
+ return Math.abs(size) * r * m.margin.kIM * ttmYears(m, ttmSec);
96598
+ }
96599
+ function borosMaintenanceMargin(m, size, markPct, ttmSec) {
96600
+ const r = Math.max(Math.abs(markPct) / 100, m.margin.rateFloor);
96601
+ return Math.abs(size) * r * m.margin.kMM * ttmYears(m, ttmSec);
96602
+ }
96603
+ function borosTakerFee(m, size) {
96604
+ return Math.abs(size) * m.fees.takerFee * m.timeToMaturitySec / SECONDS_PER_YEAR20;
96605
+ }
96606
+ function walkBorosBook(levels, size) {
96607
+ let left = size;
96608
+ let cost = 0;
96609
+ let worst = null;
96610
+ for (const l of levels) {
96611
+ if (left <= 0) break;
96612
+ const take = Math.min(left, l.size);
96613
+ cost += take * l.aprPct;
96614
+ left -= take;
96615
+ worst = l.aprPct;
96616
+ }
96617
+ const filled = size - Math.max(0, left);
96618
+ return {
96619
+ filled,
96620
+ avgAprPct: filled > 0 ? cost / filled : null,
96621
+ worstAprPct: worst,
96622
+ partial: left > 1e-12
96623
+ };
96624
+ }
96625
+ function borosRateMoveToLiquidation(m, size, equity, markPct) {
96626
+ const ttm = m.timeToMaturitySec / SECONDS_PER_YEAR20;
96627
+ if (!(Math.abs(size) > 0) || !(ttm > 0)) return null;
96628
+ const mm = borosMaintenanceMargin(m, size, markPct);
96629
+ const slack = equity - mm;
96630
+ if (slack <= 0) return 0;
96631
+ return slack / (Math.abs(size) * ttm) * 100;
96632
+ }
96633
+
96634
+ // src/boros/hedge.ts
96635
+ function borosSideTerms(m, side2) {
96636
+ const sheet = m.termSheet;
96637
+ const s = sheet?.swap?.[side2];
96638
+ return sheet && s ? {
96639
+ profileId: sheet.profileId,
96640
+ marketUid: sheet.marketUid,
96641
+ side: side2,
96642
+ info: s.info
96643
+ } : void 0;
96644
+ }
96645
+ var FUNDING_EXPOSURE_PROFILES = {
96646
+ ethena: {
96647
+ id: "ethena",
96648
+ label: "Ethena (USDe / sUSDe)",
96649
+ assets: { BTC: 0.5, ETH: 0.5 },
96650
+ venues: ["Binance", "Bybit", "OKX", "Hyperliquid", "Gate"],
96651
+ fundingShare: "most \u2014 the remainder is ETH staking and the USDtb/T-bill leg",
96652
+ notes: [
96653
+ "sUSDe yield is Ethena\u2019s perp funding net of costs, blended across venues and assets and smoothed by its reserve fund; a single Boros market tracks one venue\u2019s funding on one asset."
96654
+ ]
96655
+ },
96656
+ resolv: {
96657
+ id: "resolv",
96658
+ label: "Resolv (USR / stUSR / wstUSR)",
96659
+ assets: { ETH: 0.7, BTC: 0.3 },
96660
+ venues: ["Binance", "Hyperliquid", "Bybit", "OKX"],
96661
+ fundingShare: "part \u2014 the rest is staked-ETH yield, and RLP takes losses first",
96662
+ notes: [
96663
+ "Resolv hedges staked ETH/BTC with short perps; stUSR receives the senior share of that funding, so its sensitivity to funding is below 1."
96664
+ ]
96665
+ }
96666
+ };
96667
+ var SYMBOL_PROFILE = {
96668
+ USDE: "ethena",
96669
+ SUSDE: "ethena",
96670
+ USR: "resolv",
96671
+ STUSR: "resolv",
96672
+ WSTUSR: "resolv"
96673
+ };
96674
+ function fundingExposureOf(symbol) {
96675
+ if (!symbol) return void 0;
96676
+ const base = symbol.toUpperCase().replace(/^PT[-_]/, "").replace(/[-_ ]\d{1,2}[A-Z]{3}\d{2,4}$/, "").replace(/[-_ ](\d{4}-\d{2}-\d{2})$/, "");
96677
+ const id = SYMBOL_PROFILE[base];
96678
+ return id ? FUNDING_EXPOSURE_PROFILES[id] : void 0;
96679
+ }
96680
+ var normSym = (s) => s.toUpperCase().replace(/₮/g, "T");
96681
+ function rankBorosHedgeMarkets(markets, f) {
96682
+ const minSec = (f.minDays ?? 7) * 86400;
96683
+ const coll = (f.collateralSymbols ?? ["USDT0", "USDT", f.asset ?? ""]).map(
96684
+ normSym
96685
+ );
96686
+ const collRank = (m) => {
96687
+ const s = normSym(m.collateral.symbol);
96688
+ const i = coll.findIndex((c) => c && (s === c || s === `W${c}`));
96689
+ return i < 0 ? coll.length : i;
96690
+ };
96691
+ const venueRank = (m) => {
96692
+ const i = (f.venues ?? []).findIndex(
96693
+ (v) => v.toLowerCase() === m.venue.toLowerCase()
96694
+ );
96695
+ return i < 0 ? 99 : i;
96696
+ };
96697
+ return markets.filter(
96698
+ (m) => m.state === "Normal" && !m.isSpread && !m.isIsolatedOnly && m.timeToMaturitySec >= minSec && (!f.asset || m.asset.toUpperCase() === f.asset.toUpperCase())
96699
+ ).sort(
96700
+ (a, b) => collRank(a) - collRank(b) || venueRank(a) - venueRank(b) || a.maturity - b.maturity || (b.openInterest?.usd ?? 0) - (a.openInterest?.usd ?? 0)
96701
+ );
96702
+ }
96703
+ var BOROS_MIN_CASH_USD = 10;
96704
+ function quoteBorosHedgeLeg(p) {
96705
+ const m = p.market;
96706
+ const side2 = p.side ?? "short";
96707
+ const price2 = m.collateral.priceUsd;
96708
+ if (!(price2 > 0))
96709
+ throw new Error(`Boros: no USD price for ${m.collateral.symbol}`);
96710
+ const size = p.notionalUsd / price2;
96711
+ const fill = walkBorosBook(side2 === "short" ? p.book.bids : p.book.asks, size);
96712
+ const fixed = fill.avgAprPct;
96713
+ const floating = m.rates.floatingApr;
96714
+ const takerFee = borosTakerFee(m, size);
96715
+ const ttmYears2 = m.timeToMaturitySec / SECONDS_PER_YEAR20;
96716
+ const settleAprPct = m.fees.settleFee != null ? m.fees.settleFee * 100 : null;
96717
+ const allIn = ttmYears2 > 0 ? takerFee / size / ttmYears2 * 100 + (settleAprPct ?? 0) : null;
96718
+ const rateForMargin = fixed ?? m.rates.markApr ?? 0;
96719
+ const initial = borosInitialMargin(m, size, rateForMargin);
96720
+ const maintenance = borosMaintenanceMargin(
96721
+ m,
96722
+ size,
96723
+ m.rates.markApr ?? rateForMargin
96724
+ );
96725
+ const buffer = p.marginBuffer ?? 2;
96726
+ const floorUnits = BOROS_MIN_CASH_USD / price2;
96727
+ const needed = Math.max(initial * buffer + takerFee, floorUnits);
96728
+ const deposit = Math.max(0, needed - (p.existingFreeMargin ?? 0));
96729
+ const equity = (p.existingFreeMargin ?? 0) + deposit - takerFee;
96730
+ return {
96731
+ marketId: m.marketId,
96732
+ symbol: m.symbol,
96733
+ venue: m.venue,
96734
+ asset: m.asset,
96735
+ maturity: m.maturity,
96736
+ daysToMaturity: m.timeToMaturitySec / 86400,
96737
+ collateral: m.collateral,
96738
+ side: side2,
96739
+ notionalUsd: p.notionalUsd,
96740
+ size,
96741
+ fixedAprPct: fixed,
96742
+ worstAprPct: fill.worstAprPct,
96743
+ floatingAprPct: floating,
96744
+ lockSpreadPct: fixed != null && floating != null ? side2 === "short" ? fixed - floating : floating - fixed : null,
96745
+ fillRatio: size > 0 ? fill.filled / size : 0,
96746
+ costs: {
96747
+ takerFee,
96748
+ takerFeeUsd: takerFee * price2,
96749
+ settleFeeAprPct: settleAprPct,
96750
+ allInAprPct: allIn
96751
+ },
96752
+ margin: {
96753
+ initial,
96754
+ initialUsd: initial * price2,
96755
+ maintenance,
96756
+ deposit,
96757
+ depositUsd: deposit * price2,
96758
+ buffer,
96759
+ rateMoveToLiquidationPct: borosRateMoveToLiquidation(
96760
+ m,
96761
+ size,
96762
+ equity,
96763
+ m.rates.markApr ?? rateForMargin
96764
+ )
96765
+ },
96766
+ terms: borosSideTerms(m, side2)
96767
+ };
96768
+ }
96769
+
96770
+ 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, 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, 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, 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, convertBorosMarket, convertCoolerMarketsToResponse, convertDssMarketsToResponse, convertExactlyMarketsToResponse, convertFlyingTulipMarketsToResponse, convertFrankencoinMarketsToResponse, convertFraxlendPairsToResponse, convertInverseMarketsToResponse, convertLenderUserDataResult, convertLiquityMarketsToResponse, convertLlamaLendMarketsToResponse, convertResupplyMarketsToResponse, convertRipeMarketsToResponse, convertRiverMarketsToResponse, convertTellerMarketsToResponse, convertTermMarketsToResponse, convertTermMaxMarketsToResponse, convertUsddMarketsToResponse, createMarketUid, createMidnightBookSource, createMultiAccountTypeUserState, createMulticallRpcCall, createRawRpcCalls, createTermBookSource, createTermMaxDataSource, decodeListaMarkets, decodeMarkets, decodePackedListaUserDataset, decodePackedMorphoUserDataset, deriveBorrowTags, deriveSupplyTags, deriveSwapTags, detectInterfaceKinds, dexResolverFor, disambiguateEarnNames, disambiguateOrderBookNames, 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, fetchBorosMarkets, fetchBorosOrderBook, fetchCoolerMarkets, fetchDolomiteAccountNumbers, fetchDolomiteSubAccounts, fetchDssMarkets, fetchEulerEarnVaults, fetchEulerEarnVaultsFromSubgraph, fetchEulerSubAccountIndexes, fetchExactlyMarkets, fetchFlashLiquidityForChain, 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, 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, isSecondaryMarketOnly, isStablecoinSymbol, isSyntheticQuoteUnit, isUnearnableEarnRate, isUnrealizableEarnRate, isVaultPosition, isVaultVenue, isYearnV3, keySegmentToIlk, keysFromMaps, lenderApiOnly, lenderFamily, 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, 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, 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 };
95933
96771
  //# sourceMappingURL=index.js.map
95934
96772
  //# sourceMappingURL=index.js.map