@1delta/margin-fetcher 5.0.130 → 5.0.131

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"),
@@ -33089,7 +33089,7 @@ var usesSiloLens = (chainId) => getPositionLensFor(chainId, LENS_FAMILY.SILO) !=
33089
33089
  var buildSiloLensCall = (chainId, roster, account) => {
33090
33090
  const lens = getPositionLensFor(chainId, LENS_FAMILY.SILO);
33091
33091
  if (!lens || roster.length === 0) return [];
33092
- const side = (h) => [
33092
+ const side2 = (h) => [
33093
33093
  h.silo,
33094
33094
  h.protectedShareToken,
33095
33095
  h.debtShareToken,
@@ -33099,7 +33099,7 @@ var buildSiloLensCall = (chainId, roster, account) => {
33099
33099
  parseAbiParameters(
33100
33100
  "((address,address,address,uint8),(address,address,address,uint8))[]"
33101
33101
  ),
33102
- [roster.map((r) => [side(r.market.silo0), side(r.market.silo1)])]
33102
+ [roster.map((r) => [side2(r.market.silo0), side2(r.market.silo1)])]
33103
33103
  );
33104
33104
  return [
33105
33105
  {
@@ -33151,7 +33151,7 @@ var buildSiloV3UserCall = (chainId, lender, account, params) => {
33151
33151
  if (roster.length === 0) return [];
33152
33152
  const lens = getPositionLensFor(chainId, LENS_FAMILY.SILO);
33153
33153
  if (lens) {
33154
- const side = (h) => [
33154
+ const side2 = (h) => [
33155
33155
  h.silo,
33156
33156
  h.protectedShareToken,
33157
33157
  h.debtShareToken,
@@ -33161,7 +33161,7 @@ var buildSiloV3UserCall = (chainId, lender, account, params) => {
33161
33161
  parseAbiParameters(
33162
33162
  "((address,address,address,uint8),(address,address,address,uint8))[]"
33163
33163
  ),
33164
- [roster.map((r) => [side(r.market.silo0), side(r.market.silo1)])]
33164
+ [roster.map((r) => [side2(r.market.silo0), side2(r.market.silo1)])]
33165
33165
  );
33166
33166
  return [
33167
33167
  {
@@ -37127,8 +37127,8 @@ var getFluidUserDataConverter = (lender, chainId, account, meta) => {
37127
37127
  const constants = vaultData.constantVariables;
37128
37128
  const isSmartCol = !!vaultData.isSmartCol;
37129
37129
  const isSmartDebt = !!vaultData.isSmartDebt;
37130
- const sideLegs = (side, isSmart, sideContract, perShareOf) => {
37131
- const raw = side?.token0 !== void 0 ? side : { token0: side };
37130
+ const sideLegs = (side2, isSmart, sideContract, perShareOf) => {
37131
+ const raw = side2?.token0 !== void 0 ? side2 : { token0: side2 };
37132
37132
  const tokens = [
37133
37133
  normalizeUnderlying2((raw?.token0 ?? "").toString().toLowerCase())
37134
37134
  ];
@@ -59566,39 +59566,39 @@ function enumerateEmitters(chainId) {
59566
59566
  const siloRows = (markets, keyOf) => {
59567
59567
  for (const m of markets ?? []) {
59568
59568
  const lender = keyOf(m.siloConfig);
59569
- for (const side of [m.silo0, m.silo1]) {
59570
- const mu = uid(lender, side.silo);
59569
+ for (const side2 of [m.silo0, m.silo1]) {
59570
+ const mu = uid(lender, side2.silo);
59571
59571
  push2({
59572
59572
  chainId,
59573
- address: side.silo,
59573
+ address: side2.silo,
59574
59574
  lenderKey: lender,
59575
59575
  family: "silo",
59576
59576
  role: "market",
59577
59577
  marketUid: mu,
59578
- asset: lc(side.token)
59578
+ asset: lc(side2.token)
59579
59579
  });
59580
- if (isAddr3(side.protectedShareToken))
59580
+ if (isAddr3(side2.protectedShareToken))
59581
59581
  push2({
59582
59582
  chainId,
59583
- address: side.protectedShareToken,
59583
+ address: side2.protectedShareToken,
59584
59584
  lenderKey: lender,
59585
59585
  family: "erc20-share",
59586
59586
  role: "shareToken",
59587
59587
  side: "collateral",
59588
59588
  marketUid: mu,
59589
- asset: lc(side.token),
59589
+ asset: lc(side2.token),
59590
59590
  shareEvents: "transfers"
59591
59591
  });
59592
- if (isAddr3(side.debtShareToken))
59592
+ if (isAddr3(side2.debtShareToken))
59593
59593
  push2({
59594
59594
  chainId,
59595
- address: side.debtShareToken,
59595
+ address: side2.debtShareToken,
59596
59596
  lenderKey: lender,
59597
59597
  family: "erc20-share",
59598
59598
  role: "debtToken",
59599
59599
  side: "borrow",
59600
59600
  marketUid: mu,
59601
- asset: lc(side.token),
59601
+ asset: lc(side2.token),
59602
59602
  shareEvents: "transfers"
59603
59603
  });
59604
59604
  }
@@ -59612,11 +59612,11 @@ function enumerateEmitters(chainId) {
59612
59612
  if (!isAddr3(hook)) continue;
59613
59613
  const lender = keyOf(m.siloConfig);
59614
59614
  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)
59615
+ for (const side2 of [m.silo0, m.silo1])
59616
+ if (isAddr3(side2?.silo))
59617
+ legs[lc(side2.silo)] = {
59618
+ marketUid: uid(lender, side2.silo),
59619
+ asset: lc(side2.token)
59620
59620
  };
59621
59621
  push2({
59622
59622
  chainId,
@@ -63185,14 +63185,14 @@ function unixSeconds(v) {
63185
63185
  const n = typeof v === "number" ? v : Number(v);
63186
63186
  return Number.isFinite(n) && n > 0 ? n : void 0;
63187
63187
  }
63188
- function buildMerklStreams(opp, side, totalApr, source) {
63188
+ function buildMerklStreams(opp, side2, totalApr, source) {
63189
63189
  const rewardBreakdowns = opp.rewardsRecord?.breakdowns ?? [];
63190
63190
  const endsAt = unixSeconds(opp.earliestCampaignEnd ?? opp.latestCampaignEnd);
63191
63191
  const startsAt = unixSeconds(
63192
63192
  opp.earliestCampaignStart ?? opp.latestCampaignStart
63193
63193
  );
63194
63194
  const base = {
63195
- side,
63195
+ side: side2,
63196
63196
  kind: "token",
63197
63197
  claim: "merkl",
63198
63198
  endsAt,
@@ -67136,22 +67136,22 @@ function parseSiloV2GraphQLResults(items, context) {
67136
67136
  { api: apiSide0, self: registryEntry.silo0, other: registryEntry.silo1 },
67137
67137
  { api: apiSide1, self: registryEntry.silo1, other: registryEntry.silo0 }
67138
67138
  ];
67139
- for (const { api: side, self, other } of sideTuples) {
67140
- const tokenLc = (side.inputTokenId ?? side.inputToken?.id ?? self.token).toLowerCase();
67139
+ for (const { api: side2, self, other } of sideTuples) {
67140
+ const tokenLc = (side2.inputTokenId ?? side2.inputToken?.id ?? self.token).toLowerCase();
67141
67141
  if (!tokenLc) continue;
67142
67142
  const partnerTokenLc = other.token.toLowerCase();
67143
67143
  const dedupKey = `${lenderKey}:${tokenLc}`;
67144
67144
  if (seen.has(dedupKey)) continue;
67145
- const oracleAddr = (side.solvencyOracleAddress ?? side.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67145
+ const oracleAddr = (side2.solvencyOracleAddress ?? side2.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67146
67146
  const isStatic = !oracleAddr || oracleAddr === ZERO_ADDRESS13;
67147
67147
  const siloAddrLc = self.silo.toLowerCase();
67148
67148
  try {
67149
67149
  let priceUSD = 0;
67150
67150
  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;
67151
+ const supplyNum = safeNumber3(side2.supply);
67152
+ const supplyUsdNum = side2.supplyUsd != null ? Number(side2.supplyUsd) : 0;
67153
+ const borrowedNum = safeNumber3(side2.borrowed);
67154
+ const borrowedUsdNum = side2.borrowedUsd != null ? Number(side2.borrowedUsd) : 0;
67155
67155
  if (supplyNum > 0 && supplyUsdNum > 0) {
67156
67156
  priceUSD = supplyUsdNum / supplyNum;
67157
67157
  rawPrice = isStatic ? 1 : priceUSD;
@@ -67165,12 +67165,12 @@ function parseSiloV2GraphQLResults(items, context) {
67165
67165
  if (!priceUSD) continue;
67166
67166
  rawPrice = 1;
67167
67167
  } else {
67168
- const quoteStr = side.solvencyOracle?.quote;
67168
+ const quoteStr = side2.solvencyOracle?.quote;
67169
67169
  if (!quoteStr) continue;
67170
67170
  const quoteNum = Number(quoteStr);
67171
67171
  if (!Number.isFinite(quoteNum) || quoteNum === 0) continue;
67172
67172
  if (quoteNum < 1e-9) continue;
67173
- const quoteTokenLc = (side.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67173
+ const quoteTokenLc = (side2.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67174
67174
  if (!quoteTokenLc) continue;
67175
67175
  const qtUSD = lookupUSD3(context, quoteTokenLc);
67176
67176
  if (!qtUSD) continue;
@@ -67280,22 +67280,22 @@ function parseSiloV3GraphQLResults(items, context) {
67280
67280
  { api: apiSide0, self: registryEntry.silo0, other: registryEntry.silo1 },
67281
67281
  { api: apiSide1, self: registryEntry.silo1, other: registryEntry.silo0 }
67282
67282
  ];
67283
- for (const { api: side, self, other } of sideTuples) {
67284
- const tokenLc = (side.inputTokenId ?? side.inputToken?.id ?? self.token).toLowerCase();
67283
+ for (const { api: side2, self, other } of sideTuples) {
67284
+ const tokenLc = (side2.inputTokenId ?? side2.inputToken?.id ?? self.token).toLowerCase();
67285
67285
  if (!tokenLc) continue;
67286
67286
  const partnerTokenLc = other.token.toLowerCase();
67287
67287
  const dedupKey = `${lenderKey}:${tokenLc}`;
67288
67288
  if (seen.has(dedupKey)) continue;
67289
- const oracleAddr = (side.solvencyOracleAddress ?? side.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67289
+ const oracleAddr = (side2.solvencyOracleAddress ?? side2.solvencyOracle?.id ?? self.solvencyOracle ?? ZERO_ADDRESS13).toLowerCase();
67290
67290
  const isStatic = !oracleAddr || oracleAddr === ZERO_ADDRESS13;
67291
67291
  const siloAddrLc = self.silo.toLowerCase();
67292
67292
  try {
67293
67293
  let priceUSD = 0;
67294
67294
  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;
67295
+ const supplyNum = safeNumber4(side2.supply);
67296
+ const supplyUsdNum = side2.supplyUsd != null ? Number(side2.supplyUsd) : 0;
67297
+ const borrowedNum = safeNumber4(side2.borrowed);
67298
+ const borrowedUsdNum = side2.borrowedUsd != null ? Number(side2.borrowedUsd) : 0;
67299
67299
  if (supplyNum > 0 && supplyUsdNum > 0) {
67300
67300
  priceUSD = supplyUsdNum / supplyNum;
67301
67301
  rawPrice = isStatic ? 1 : priceUSD;
@@ -67309,12 +67309,12 @@ function parseSiloV3GraphQLResults(items, context) {
67309
67309
  if (!priceUSD) continue;
67310
67310
  rawPrice = 1;
67311
67311
  } else {
67312
- const quoteStr = side.solvencyOracle?.quote;
67312
+ const quoteStr = side2.solvencyOracle?.quote;
67313
67313
  if (!quoteStr) continue;
67314
67314
  const quoteNum = Number(quoteStr);
67315
67315
  if (!Number.isFinite(quoteNum) || quoteNum === 0) continue;
67316
67316
  if (quoteNum < 1e-9) continue;
67317
- const quoteTokenLc = (side.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67317
+ const quoteTokenLc = (side2.solvencyOracle?.quoteTokenId ?? "").toLowerCase();
67318
67318
  if (!quoteTokenLc) continue;
67319
67319
  const qtUSD = lookupUSD4(context, quoteTokenLc);
67320
67320
  if (!qtUSD) continue;
@@ -80317,9 +80317,9 @@ var readerBitfiBfbtc = (entry2) => {
80317
80317
  const totalAssets = totalSupply * exchangeRate * underlyingUnit / (ONE_E1823 * shareUnit);
80318
80318
  const feeOf = (cell) => {
80319
80319
  if (!Array.isArray(cell)) return void 0;
80320
- const pct3 = toBigInt16(cell[0]);
80320
+ const pct4 = toBigInt16(cell[0]);
80321
80321
  const fixed = toBigInt16(cell[1]);
80322
- return pct3 === void 0 || fixed === void 0 ? void 0 : { pct: pct3, fixed };
80322
+ return pct4 === void 0 || fixed === void 0 ? void 0 : { pct: pct4, fixed };
80323
80323
  };
80324
80324
  const evm = feeOf(evmFee);
80325
80325
  const native = feeOf(nativeFee);
@@ -81497,7 +81497,7 @@ var readerLiminalPipe = (entry2) => {
81497
81497
  parse: ([
81498
81498
  supply,
81499
81499
  nav,
81500
- fees,
81500
+ fees2,
81501
81501
  provider,
81502
81502
  redeemPaused,
81503
81503
  lpBalance,
@@ -81510,7 +81510,7 @@ var readerLiminalPipe = (entry2) => {
81510
81510
  if (totalSupply === void 0 || nav18 === void 0) return void 0;
81511
81511
  const exchangeRate = totalSupply > 0n ? nav18 * ONE_E1823 / totalSupply : ONE_E1823;
81512
81512
  const totalAssets = nav18 / navScale;
81513
- const feeBps = toBigInt16(cellAt(fees, 0));
81513
+ const feeBps = toBigInt16(cellAt(fees2, 0));
81514
81514
  const providerMatches = typeof provider === "string" && provider.toLowerCase() === cfg.liquidityProvider;
81515
81515
  const bal = toBigInt16(lpBalance);
81516
81516
  const allow = toBigInt16(lpAllowance);
@@ -85052,17 +85052,17 @@ var priceGmMarkets = async (chainId, multicallRetry, markets, prices) => {
85052
85052
  var computeLiquidityUsd = (poolUsdLong, poolUsdShort, reservedUsdLong, reservedUsdShort, reserveFactorLong, reserveFactorShort) => {
85053
85053
  if (typeof poolUsdLong !== "bigint" || typeof poolUsdShort !== "bigint")
85054
85054
  return void 0;
85055
- const side = (pool, reserved, rf) => {
85055
+ const side2 = (pool, reserved, rf) => {
85056
85056
  const floor = rf > 0n ? reserved * USD_1E30N / rf : 0n;
85057
85057
  const avail = pool - floor;
85058
85058
  return avail > 0n ? avail : 0n;
85059
85059
  };
85060
- const total = side(poolUsdLong, reservedUsdLong, reserveFactorLong) + side(poolUsdShort, reservedUsdShort, reserveFactorShort);
85060
+ const total = side2(poolUsdLong, reservedUsdLong, reserveFactorLong) + side2(poolUsdShort, reservedUsdShort, reserveFactorShort);
85061
85061
  return toUsd(total);
85062
85062
  };
85063
85063
  var computeDepositCapacityUsd = (long, short) => {
85064
85064
  const INF = -1n;
85065
- const side = ([poolAmount, priceMax, maxAmount, maxUsd]) => {
85065
+ const side2 = ([poolAmount, priceMax, maxAmount, maxUsd]) => {
85066
85066
  if (typeof poolAmount !== "bigint") return void 0;
85067
85067
  const poolUsd = poolAmount * priceMax;
85068
85068
  const amountRoom = maxAmount > 0n ? (maxAmount > poolAmount ? maxAmount - poolAmount : 0n) * priceMax : INF;
@@ -85072,8 +85072,8 @@ var computeDepositCapacityUsd = (long, short) => {
85072
85072
  if (usdRoom === INF) return amountRoom;
85073
85073
  return amountRoom < usdRoom ? amountRoom : usdRoom;
85074
85074
  };
85075
- const l = side(long);
85076
- const s = side(short);
85075
+ const l = side2(long);
85076
+ const s = side2(short);
85077
85077
  if (l == null && s == null) return void 0;
85078
85078
  return toUsd((l ?? 0n) + (s ?? 0n));
85079
85079
  };
@@ -86431,6 +86431,18 @@ function deriveBorrowTags(borrow, market = {}) {
86431
86431
  push(out, "full-collateral-seizure");
86432
86432
  return [...out];
86433
86433
  }
86434
+ function deriveSwapTags(sw, side2, governance) {
86435
+ const tags = ["rate-swap", "margined", "rate-liquidation"];
86436
+ tags.push(side2.receives === "fixed" ? "fixed-rate" : "variable-rate");
86437
+ if (sw.maturity.kind === "fixed-date") tags.push("has-maturity");
86438
+ if (sw.exit.close === "market-trade") tags.push("exit-market-sale");
86439
+ if (sw.openInterestCap?.hard != null) tags.push("capped");
86440
+ if (side2.availability.blockedBy === "cap-full") tags.push("cap-full");
86441
+ if (governance?.mutability === "immutable") tags.push("immutable");
86442
+ else if (governance && !governance.timelockSecs) tags.push("no-timelock");
86443
+ if (governance?.controllerKind === "EOA") tags.push("eoa-controlled");
86444
+ return tags;
86445
+ }
86434
86446
 
86435
86447
  // src/terms/format.ts
86436
86448
  var SECS_PER_DAY = 86400;
@@ -86825,6 +86837,51 @@ function borrowDescription(b) {
86825
86837
  }
86826
86838
  return parts.join(" ");
86827
86839
  }
86840
+ function floatingLabel(sw) {
86841
+ return sw.floating.spreadOf?.length ? `the ${sw.floating.spreadOf.join(" \u2212 ")} ${sw.notional.underlying} funding spread` : `${sw.floating.venue} ${sw.notional.underlying} funding`;
86842
+ }
86843
+ function swapSideHeadline(sw, s) {
86844
+ const fixed = s.fixedApr != null ? `fixed ${pct(s.fixedApr)}` : `fixed (no ${s.side === "short" ? "bids" : "asks"} on the book)`;
86845
+ const floating = `${floatingLabel(sw)}${sw.floating.apr != null ? ` (now ${pct(sw.floating.apr)})` : ""}`;
86846
+ const legs = s.receives === "fixed" ? `Receive ${fixed} \xB7 pay ${floating}` : `Receive ${floating} \xB7 pay ${fixed}`;
86847
+ return `${legs} \xB7 to ${shortDate(sw.maturity.maturity)}`;
86848
+ }
86849
+ function swapSideDescription(sw, s) {
86850
+ const unit = sw.notional.unit.symbol ?? "the margin token";
86851
+ 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)}`;
86852
+ const loses = s.adverseMove === "floating-up" ? "if funding rises above the fixed rate" : "if funding falls below the fixed rate";
86853
+ const fees2 = sw.fees.filter((f) => f.when !== "liquidation").map((f) => feePhrase(f)).join("; ");
86854
+ 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}.` : "");
86855
+ }
86856
+ function swapSideImplications(sw, s, governance) {
86857
+ const out = [];
86858
+ if (s.carryApr != null && sw.floating.apr != null && s.fixedApr != null) {
86859
+ const verb = s.carryApr >= 0 ? "gains" : "gives up";
86860
+ out.push(
86861
+ `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)}.`
86862
+ );
86863
+ }
86864
+ out.push(
86865
+ `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}` : "") + "."
86866
+ );
86867
+ const unitSym = sw.notional.unit.symbol ?? "the margin token";
86868
+ const sameAsUnderlying = unitSym.toUpperCase().replace(/^W/, "").replace("\u20AE", "T") === sw.notional.underlying.toUpperCase();
86869
+ out.push(
86870
+ 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}.`
86871
+ );
86872
+ out.push(
86873
+ `The rate is fixed only until ${shortDate(sw.maturity.maturity)}; holding the exposure longer means rolling into a later market at its rate then.`
86874
+ );
86875
+ if (sw.exit.withdrawalCooldownSecs)
86876
+ out.push(
86877
+ `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." : ".")
86878
+ );
86879
+ if (governance?.powers?.includes("upgrade-implementation") && !governance.timelockSecs)
86880
+ out.push(
86881
+ `The contracts are upgradeable by ${governance.safe ? `a ${governance.safe.threshold}-of-${governance.safe.owners} Safe` : "an admin"} with no timelock.`
86882
+ );
86883
+ return out;
86884
+ }
86828
86885
 
86829
86886
  // src/terms/profiles.ts
86830
86887
  var P = (p) => p;
@@ -87591,6 +87648,22 @@ var TERM_PROFILES = [
87591
87648
  "Deposits are counterparty to traders \u2014 the pool profits when they lose and loses when they win."
87592
87649
  ]
87593
87650
  }
87651
+ }),
87652
+ // ── Rate swaps ─────────────────────────────────────────────────────────────
87653
+ P({
87654
+ id: "boros.funding-swap@v1",
87655
+ name: "Pendle Boros funding-rate swap",
87656
+ family: "swap",
87657
+ swap: {
87658
+ 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.",
87659
+ implications: [
87660
+ "The margin is at risk: the side the floating rate moves against loses margin and is liquidated at health \u2264 1.",
87661
+ "The fixed rate holds only until the market matures \u2014 a longer exposure has to be rolled at whatever the next market prices.",
87662
+ "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.",
87663
+ "Positions and margin live on Arbitrum, separate from anything they hedge on another chain \u2014 the two are never netted."
87664
+ ]
87665
+ },
87666
+ docsUrl: "https://pendle.gitbook.io/boros"
87594
87667
  })
87595
87668
  ];
87596
87669
  var BY_ID = new Map(TERM_PROFILES.map((p) => [p.id, p]));
@@ -87750,11 +87823,11 @@ function rateKindOf(input) {
87750
87823
  if (isNum(maturity) && maturity > 0) return "fixed-term";
87751
87824
  return "variable-curve";
87752
87825
  }
87753
- function rewardTerms(input, side) {
87826
+ function rewardTerms(input, side2) {
87754
87827
  if (!input.rewards?.length) return void 0;
87755
87828
  const out = [];
87756
87829
  for (const r of input.rewards) {
87757
- const apr = side === "supply" ? r.depositRate ?? 0 : r.variableBorrowRate ?? r.stableBorrowRate ?? 0;
87830
+ const apr = side2 === "supply" ? r.depositRate ?? 0 : r.variableBorrowRate ?? r.stableBorrowRate ?? 0;
87758
87831
  if (!apr) continue;
87759
87832
  const isPoints = r.kind === "points" || !r.asset;
87760
87833
  out.push({
@@ -87764,7 +87837,7 @@ function rewardTerms(input, side) {
87764
87837
  } : void 0,
87765
87838
  kind: isPoints ? "points" : "token",
87766
87839
  apr,
87767
- side,
87840
+ side: side2,
87768
87841
  claim: r.claim ?? (isPoints ? "none" : "accrual"),
87769
87842
  endsAt: r.endsAt,
87770
87843
  // Points have no priceable value, so they must not inflate `aprTotal`.
@@ -87773,20 +87846,20 @@ function rewardTerms(input, side) {
87773
87846
  }
87774
87847
  return out.length ? out : void 0;
87775
87848
  }
87776
- function buildRate(input, side) {
87849
+ function buildRate(input, side2) {
87777
87850
  const kind = rateKindOf(input);
87778
- const rewards = rewardTerms(input, side);
87851
+ const rewards = rewardTerms(input, side2);
87779
87852
  const priceableRewards = (rewards ?? []).filter((r) => !r.indicative).reduce((s, r) => s + r.apr, 0);
87780
87853
  const menuBest = input.terms?.length ? Math.min(...input.terms.map((t) => t.apr)) : void 0;
87781
87854
  let base;
87782
- if (side === "supply") {
87855
+ if (side2 === "supply") {
87783
87856
  base = input.depositRate ?? 0;
87784
87857
  } else if (kind === "fixed-term") {
87785
87858
  base = menuBest ?? input.stableBorrowRate ?? input.variableBorrowRate ?? 0;
87786
87859
  } else {
87787
87860
  base = input.variableBorrowRate ?? 0;
87788
87861
  }
87789
- const intrinsic = side === "supply" ? input.intrinsicYield ?? 0 : 0;
87862
+ const intrinsic = side2 === "supply" ? input.intrinsicYield ?? 0 : 0;
87790
87863
  return {
87791
87864
  kind,
87792
87865
  apr: base,
@@ -87825,10 +87898,10 @@ function buildMaturity(input, now) {
87825
87898
  }
87826
87899
  return { kind: "perpetual" };
87827
87900
  }
87828
- function buildFees(input, side) {
87901
+ function buildFees(input, side2) {
87829
87902
  const out = [];
87830
87903
  const ft = input.fixedTerm;
87831
- if (side === "borrow") {
87904
+ if (side2 === "borrow") {
87832
87905
  const origination = input.originationFee ?? ft?.fees?.originationFeePercent ?? void 0;
87833
87906
  if (isNum(origination) && origination !== 0) {
87834
87907
  out.push({
@@ -87870,7 +87943,7 @@ function buildFees(input, side) {
87870
87943
  });
87871
87944
  }
87872
87945
  }
87873
- if (side === "supply") {
87946
+ if (side2 === "supply") {
87874
87947
  if (isNum(ft?.fees?.continuousFeeApr) && ft.fees.continuousFeeApr !== 0) {
87875
87948
  out.push({
87876
87949
  id: "continuous",
@@ -87943,15 +88016,15 @@ function capUtil(total, cap) {
87943
88016
  if (!isNum(cap) || cap <= 0 || !isNum(total)) return void 0;
87944
88017
  return clamp013(total / cap);
87945
88018
  }
87946
- function buildAvailability(input, side) {
88019
+ function buildAvailability(input, side2) {
87947
88020
  const frozen = input.isFrozen === true;
87948
88021
  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;
88022
+ const enabled = side2 === "supply" ? input.depositsEnabled !== false : input.borrowingEnabled !== false;
88023
+ const cap = side2 === "supply" ? input.supplyCap : input.borrowCap;
88024
+ const total = side2 === "supply" ? input.totalDeposits : input.totalDebt;
87952
88025
  const capUtilization = capUtil(total, cap);
87953
88026
  const capFull = capUtilization != null && capUtilization >= 1;
87954
- const noLiquidity = side === "borrow" && isNum(input.borrowLiquidity) && input.borrowLiquidity <= 0;
88027
+ const noLiquidity = side2 === "borrow" && isNum(input.borrowLiquidity) && input.borrowLiquidity <= 0;
87955
88028
  const canOpen = enabled && !frozen && !inactive && !capFull && !noLiquidity;
87956
88029
  let blockedBy;
87957
88030
  if (!canOpen) {
@@ -87970,10 +88043,10 @@ function buildAvailability(input, side) {
87970
88043
  gating: "permissionless",
87971
88044
  // A borrow below the protocol's floor REVERTS, so gate the CTA on it
87972
88045
  // rather than letting the transaction fail.
87973
- minSize: side === "borrow" ? resolveMinDebt(input) : resolveMinCollateral(input),
88046
+ minSize: side2 === "borrow" ? resolveMinDebt(input) : resolveMinCollateral(input),
87974
88047
  cap: isNum(cap) && cap > 0 ? String(cap) : void 0,
87975
88048
  capUtilization,
87976
- requires: side === "supply" ? ["token-approval"] : void 0
88049
+ requires: side2 === "supply" ? ["token-approval"] : void 0
87977
88050
  };
87978
88051
  }
87979
88052
  function buildUtilization(input) {
@@ -88115,8 +88188,8 @@ function buildSupply(input, now, siblings) {
88115
88188
  return void 0;
88116
88189
  const rate = buildRate(input, "supply");
88117
88190
  const maturity = buildMaturity(input, now);
88118
- const fees = buildFees(input, "supply");
88119
- const availability = buildAvailability(input, "supply");
88191
+ const fees2 = buildFees(input, "supply");
88192
+ const availability2 = buildAvailability(input, "supply");
88120
88193
  const liquidity = isNum(input.totalLiquidity) ? {
88121
88194
  assets: input.totalLiquidity,
88122
88195
  assetsUsd: input.totalLiquidityUsd,
@@ -88132,16 +88205,16 @@ function buildSupply(input, now, siblings) {
88132
88205
  liquidity,
88133
88206
  partialAllowed: true,
88134
88207
  priceRisk: "none",
88135
- fees: fees.filter((f) => f.when === "exit" || f.when === "performance")
88208
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
88136
88209
  },
88137
- fees,
88210
+ fees: fees2,
88138
88211
  backedBy: buildExposures2(input, siblings, "backing"),
88139
88212
  modes: buildModes(input),
88140
88213
  counterparty: {
88141
88214
  kind: "pool",
88142
88215
  solvency: "overcollateralized"
88143
88216
  },
88144
- availability,
88217
+ availability: availability2,
88145
88218
  principal: { protected: true, risks: [] },
88146
88219
  info: { headline: "", description: "", tags: [] }
88147
88220
  };
@@ -88155,7 +88228,7 @@ function buildBorrow(input, now, siblings) {
88155
88228
  return void 0;
88156
88229
  const rate = buildRate(input, "borrow");
88157
88230
  const maturity = buildMaturity(input, now);
88158
- const fees = buildFees(input, "borrow");
88231
+ const fees2 = buildFees(input, "borrow");
88159
88232
  const acceptedCollateral = buildExposures2(input, siblings, "accepted");
88160
88233
  const borrow = {
88161
88234
  rate,
@@ -88169,12 +88242,12 @@ function buildBorrow(input, now, siblings) {
88169
88242
  // The same floor, read as a DUST limit: a partial repay may not leave
88170
88243
  // the position below it.
88171
88244
  minDebt: resolveMinDebt(input),
88172
- fees: fees.filter((f) => f.when === "exit" || f.when === "late")
88245
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "late")
88173
88246
  },
88174
88247
  liquidation: liquidationFrom(cfg, input, acceptedCollateral),
88175
88248
  acceptedCollateral,
88176
88249
  modes: buildModes(input),
88177
- fees,
88250
+ fees: fees2,
88178
88251
  counterparty: { kind: "pool", solvency: "overcollateralized" },
88179
88252
  availability: buildAvailability(input, "borrow"),
88180
88253
  info: { headline: "", description: "", tags: [] }
@@ -88213,6 +88286,17 @@ function finalizeInfo(sheet) {
88213
88286
  tags: deriveSupplyTags(sheet.supply, market)
88214
88287
  };
88215
88288
  }
88289
+ if (sheet.swap) {
88290
+ const sw = sheet.swap;
88291
+ for (const s of [sw.long, sw.short]) {
88292
+ s.info = {
88293
+ headline: s.info?.headline || swapSideHeadline(sw, s),
88294
+ description: s.info?.description || swapSideDescription(sw, s),
88295
+ implications: s.info?.implications ?? swapSideImplications(sw, s, sheet.governance),
88296
+ tags: deriveSwapTags(sw, s, sheet.governance)
88297
+ };
88298
+ }
88299
+ }
88216
88300
  if (sheet.borrow) {
88217
88301
  sheet.borrow.info = {
88218
88302
  headline: sheet.borrow.info.headline || borrowHeadline(sheet.borrow),
@@ -88287,8 +88371,8 @@ function buildTermSheet(input, opts = {}) {
88287
88371
  base.borrow?.acceptedCollateral ?? base.supply?.backedBy
88288
88372
  );
88289
88373
  const merged = mergeDeep(base, opts.patch);
88290
- for (const side of ["supply", "borrow"]) {
88291
- if (merged[side] && !base[side]) merged[side] = void 0;
88374
+ for (const side2 of ["supply", "borrow"]) {
88375
+ if (merged[side2] && !base[side2]) merged[side2] = void 0;
88292
88376
  }
88293
88377
  const withInfo = finalizeInfo(merged);
88294
88378
  withInfo.coverage = mergeAdapterCoverage(
@@ -88823,7 +88907,7 @@ function derivedRoutes(input, mode) {
88823
88907
  });
88824
88908
  return routes2.length > 0 ? routes2 : void 0;
88825
88909
  }
88826
- function buildExit(input, t, fees) {
88910
+ function buildExit(input, t, fees2) {
88827
88911
  const mode = resolveExitMode(input, t);
88828
88912
  const priceRisk = resolvePriceRisk(input, t);
88829
88913
  const ratio = input.instantLiquidityRatio ?? (isNum2(input.liquidity) && isNum2(input.totalAssets) && input.totalAssets > 0 ? clamp014(input.liquidity / input.totalAssets) : void 0);
@@ -88848,7 +88932,7 @@ function buildExit(input, t, fees) {
88848
88932
  priceRisk,
88849
88933
  // Only the request/queue models have something to cancel, and only where
88850
88934
  // the protocol exposes it — left undefined rather than guessed.
88851
- fees: fees.filter((f) => f.when === "exit" || f.when === "performance")
88935
+ fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
88852
88936
  };
88853
88937
  }
88854
88938
  function resolvePriceRisk(input, t) {
@@ -89055,15 +89139,15 @@ function buildVaultTermSheet(input, opts = {}) {
89055
89139
  const now = opts.now ?? Math.floor(Date.now() / 1e3);
89056
89140
  const t = vaultTraits(input.provider) ?? FALLBACK_TRAITS;
89057
89141
  const maturity = buildMaturity2(input, now);
89058
- const fees = buildFees2(input, t);
89142
+ const fees2 = buildFees2(input, t);
89059
89143
  const supply = {
89060
89144
  // A vault share is never collateral IN the vault — it earns, full stop.
89061
89145
  // (It may be collateral somewhere else; that is the other market's sheet.)
89062
89146
  role: "yield",
89063
89147
  rate: buildRate2(input, t, maturity),
89064
89148
  maturity,
89065
- exit: buildExit(input, t, fees),
89066
- fees,
89149
+ exit: buildExit(input, t, fees2),
89150
+ fees: fees2,
89067
89151
  backedBy: buildBacking(input),
89068
89152
  counterparty: buildCounterparty(input, t),
89069
89153
  availability: buildAvailability2(input, now),
@@ -89740,7 +89824,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
89740
89824
  },
89741
89825
  maturity
89742
89826
  );
89743
- const availability = resolveAvailability(meta, maturity);
89827
+ const availability2 = resolveAvailability(meta, maturity);
89744
89828
  const exitMode = resolveExitMode2(provider, meta, tvl, liq);
89745
89829
  const market = {
89746
89830
  earnUid: buildVaultEarnUid(provider, chainId, address),
@@ -89838,7 +89922,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
89838
89922
  // not disagree about what the legs out are.
89839
89923
  routes: Array.isArray(meta.exitRoutes) ? meta.exitRoutes : void 0
89840
89924
  },
89841
- availability,
89925
+ availability: availability2,
89842
89926
  risk: {
89843
89927
  yieldProfile: yieldProfile(info.yieldProfile),
89844
89928
  denomination: denomination(info.denomination),
@@ -90013,15 +90097,15 @@ function sdkRates(row, provider) {
90013
90097
  totalRate: num15(row.depositRate)
90014
90098
  };
90015
90099
  }
90016
- const pct3 = (v) => {
90100
+ const pct4 = (v) => {
90017
90101
  const n = num15(v);
90018
90102
  return n === void 0 ? void 0 : n * 100;
90019
90103
  };
90020
90104
  return {
90021
90105
  // 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)
90106
+ supplyRate: pct4(row.baseApy ?? row.apr),
90107
+ rewardsRate: pct4(row.bonusApr),
90108
+ totalRate: pct4(row.apy ?? row.apr)
90025
90109
  };
90026
90110
  }
90027
90111
  function toVaultTermInput(vault, provider, chainId) {
@@ -90513,12 +90597,12 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
90513
90597
  tasks.push(
90514
90598
  (async () => {
90515
90599
  const gasPrice = await getEvmClient(chainId).getGasPrice();
90516
- const fees = await fetchGmxExecutionFees(
90600
+ const fees2 = await fetchGmxExecutionFees(
90517
90601
  chainId,
90518
90602
  multicallRetry,
90519
90603
  gasPrice
90520
90604
  );
90521
- if (fees) out.gmxExecutionFees = fees;
90605
+ if (fees2) out.gmxExecutionFees = fees2;
90522
90606
  })().catch((e) => {
90523
90607
  warn8(
90524
90608
  `[vaults] gmx execution-fee fetch failed for chain ${chainId}:`,
@@ -91635,12 +91719,12 @@ function assetFindings(sheet) {
91635
91719
  }
91636
91720
  return out;
91637
91721
  }
91638
- function findingsFor(sheet, side) {
91639
- const sideFindings = side === "supply" ? sheet.supply ? [...supplyFindings(sheet.supply), ...assetFindings(sheet)] : [] : sheet.borrow ? borrowFindings(sheet.borrow) : [];
91722
+ function findingsFor(sheet, side2) {
91723
+ const sideFindings = side2 === "supply" ? sheet.supply ? [...supplyFindings(sheet.supply), ...assetFindings(sheet)] : [] : sheet.borrow ? borrowFindings(sheet.borrow) : [];
91640
91724
  return rankFindings([...sideFindings, ...marketFindings(sheet)]);
91641
91725
  }
91642
- function hasCritical(sheet, side) {
91643
- return findingsFor(sheet, side).some((f) => f.severity === "critical");
91726
+ function hasCritical(sheet, side2) {
91727
+ return findingsFor(sheet, side2).some((f) => f.severity === "critical");
91644
91728
  }
91645
91729
  var exactlyAdapter = {
91646
91730
  id: "exactly",
@@ -92294,9 +92378,9 @@ var alchemixAdapter = {
92294
92378
  const isCollateralRow = input.collateralActive !== false;
92295
92379
  const protocolFeeBps = num17(a.protocolFeeBps);
92296
92380
  const liquidatorFeeBps = num17(a.liquidatorFeeBps);
92297
- const fees = [];
92381
+ const fees2 = [];
92298
92382
  if (protocolFeeBps != null)
92299
- fees.push({
92383
+ fees2.push({
92300
92384
  id: "redemption",
92301
92385
  label: "Redemption fee",
92302
92386
  // Charged whenever a Transmuter redemption settles part of the debt —
@@ -92312,7 +92396,7 @@ var alchemixAdapter = {
92312
92396
  description: "Taken from your collateral on the part of your debt that redemptions settle; the rest of the debt pays nothing."
92313
92397
  });
92314
92398
  if (liquidatorFeeBps != null)
92315
- fees.push({
92399
+ fees2.push({
92316
92400
  id: "liquidation-bonus",
92317
92401
  label: "Liquidator fee",
92318
92402
  when: "liquidation",
@@ -92412,7 +92496,7 @@ var alchemixAdapter = {
92412
92496
  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
92497
  }
92414
92498
  },
92415
- fees,
92499
+ fees: fees2,
92416
92500
  counterparty: {
92417
92501
  kind: "cdp",
92418
92502
  solvency: "overcollateralized",
@@ -92630,7 +92714,7 @@ var frankencoinAdapter = {
92630
92714
  const challengerPct = ppmToPercent(fc.challengerRewardPPM);
92631
92715
  const expiration = Number(fc.expiration ?? 0);
92632
92716
  const challengePeriod = Number(fc.challengePeriod ?? 0);
92633
- const fees = [
92717
+ const fees2 = [
92634
92718
  reservePct != null && reservePct > 0 ? {
92635
92719
  id: "reserve-contribution",
92636
92720
  label: "Equity-reserve contribution",
@@ -92701,7 +92785,7 @@ var frankencoinAdapter = {
92701
92785
  ] : void 0,
92702
92786
  badDebt: "socialized"
92703
92787
  },
92704
- fees,
92788
+ fees: fees2,
92705
92789
  counterparty: { kind: "cdp", solvency: "overcollateralized" }
92706
92790
  },
92707
92791
  constraints: {
@@ -93348,7 +93432,7 @@ function build2(input) {
93348
93432
  };
93349
93433
  if (!isNum4(input.originationFee) && input.borrowingEnabled === true)
93350
93434
  pending["borrow.fees"] = "the vault's borrow fee is not on the row";
93351
- const fees = isNum4(input.originationFee) && input.originationFee > 0 ? [
93435
+ const fees2 = isNum4(input.originationFee) && input.originationFee > 0 ? [
93352
93436
  {
93353
93437
  id: "origination",
93354
93438
  label: "Borrow fee",
@@ -93379,7 +93463,7 @@ function build2(input) {
93379
93463
  trigger: "price",
93380
93464
  seizure: "proportional"
93381
93465
  },
93382
- ...fees ? { fees } : {},
93466
+ ...fees2 ? { fees: fees2 } : {},
93383
93467
  ext: {
93384
93468
  jupiterLend: {
93385
93469
  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 +94491,24 @@ function toDigest(sheet) {
94407
94491
  tags: sheet.borrow.info.tags,
94408
94492
  acceptedCollateral: strip(sheet.borrow.acceptedCollateral)
94409
94493
  } : void 0,
94494
+ swap: sheet.swap ? {
94495
+ kind: sheet.swap.kind,
94496
+ underlying: sheet.swap.notional.underlying,
94497
+ venue: sheet.swap.floating.venue,
94498
+ maturity: sheet.swap.maturity.maturity,
94499
+ markApr: sheet.swap.fixed.markApr,
94500
+ floatingApr: sheet.swap.floating.apr,
94501
+ long: {
94502
+ headline: sheet.swap.long.info.headline,
94503
+ canOpen: sheet.swap.long.availability.canOpen,
94504
+ fixedApr: sheet.swap.long.fixedApr
94505
+ },
94506
+ short: {
94507
+ headline: sheet.swap.short.info.headline,
94508
+ canOpen: sheet.swap.short.availability.canOpen,
94509
+ fixedApr: sheet.swap.short.fixedApr
94510
+ }
94511
+ } : void 0,
94410
94512
  oracle: sheet.oracle ? {
94411
94513
  kind: sheet.oracle.kind,
94412
94514
  address: sheet.oracle.address,
@@ -94546,42 +94648,42 @@ function validateTermSheet(sheet) {
94546
94648
  if (sheet.schemaVersion !== TERM_SHEET_SCHEMA_VERSION)
94547
94649
  fail("schema-version", `unexpected schemaVersion ${sheet.schemaVersion}`);
94548
94650
  if (!sheet.profileId) fail("profile-id", "missing profileId");
94549
- for (const side of ["supply", "borrow"]) {
94550
- const s = sheet[side];
94651
+ for (const side2 of ["supply", "borrow"]) {
94652
+ const s = sheet[side2];
94551
94653
  if (!s) continue;
94552
94654
  const c = s.rate.components;
94553
94655
  const expected = (c.base ?? 0) + (c.rewards ?? 0) + (c.intrinsic ?? 0);
94554
94656
  if (!approx(s.rate.aprTotal, expected, 1e-6))
94555
94657
  fail(
94556
94658
  "apr-total",
94557
- `${side}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
94659
+ `${side2}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
94558
94660
  );
94559
94661
  const priceable = (s.rate.rewards ?? []).filter((r) => !r.indicative).reduce((sum3, r) => sum3 + r.apr, 0);
94560
94662
  if (s.rate.rewards && !approx(c.rewards ?? 0, priceable, 1e-6))
94561
94663
  fail(
94562
94664
  "rewards-priceable",
94563
- `${side}.rate.components.rewards ${c.rewards} != sum of non-indicative rewards ${priceable}`
94665
+ `${side2}.rate.components.rewards ${c.rewards} != sum of non-indicative rewards ${priceable}`
94564
94666
  );
94565
94667
  if (s.rate.basis !== "apr-nominal")
94566
- fail("rate-basis", `${side}.rate.basis must be apr-nominal`);
94668
+ fail("rate-basis", `${side2}.rate.basis must be apr-nominal`);
94567
94669
  if (s.maturity.kind === "fixed-date" && s.maturity.maturity == null)
94568
94670
  fail(
94569
94671
  "maturity-missing",
94570
- `${side}.maturity.kind is fixed-date with no maturity`
94672
+ `${side2}.maturity.kind is fixed-date with no maturity`
94571
94673
  );
94572
94674
  if ((s.rate.kind === "fixed-term" || s.rate.kind === "fixed-open") && s.rate.kind === "fixed-term" && s.maturity.kind === "perpetual")
94573
94675
  fail(
94574
94676
  "fixed-term-perpetual",
94575
- `${side} is fixed-term but maturity.kind is perpetual`
94677
+ `${side2} is fixed-term but maturity.kind is perpetual`
94576
94678
  );
94577
94679
  if (s.availability.canOpen === false && !s.availability.blockedBy)
94578
94680
  fail(
94579
94681
  "blocked-reason",
94580
- `${side}.availability.canOpen is false with no blockedBy`
94682
+ `${side2}.availability.canOpen is false with no blockedBy`
94581
94683
  );
94582
- if (!s.info.headline) fail("headline", `${side}.info.headline is empty`);
94684
+ if (!s.info.headline) fail("headline", `${side2}.info.headline is empty`);
94583
94685
  if (!Array.isArray(s.info.tags))
94584
- fail("tags", `${side}.info.tags is not an array`);
94686
+ fail("tags", `${side2}.info.tags is not an array`);
94585
94687
  }
94586
94688
  if (sheet.supply) {
94587
94689
  const e = sheet.supply.exit;
@@ -94592,6 +94694,44 @@ function validateTermSheet(sheet) {
94592
94694
  fail("instant-cooldown", "exit.mode instant must not carry a cooldown");
94593
94695
  }
94594
94696
  }
94697
+ const sw = sheet.swap;
94698
+ if (sw) {
94699
+ if (sheet.supply || sheet.borrow)
94700
+ fail("swap-exclusive", "a swap sheet must not also carry supply/borrow");
94701
+ if (sw.maturity.kind !== "fixed-date" || sw.maturity.maturity == null)
94702
+ fail("swap-maturity", "a rate swap must carry a fixed-date maturity");
94703
+ const m = sw.margin;
94704
+ if (!(m.initialFactor > 0) || !(m.maintenanceFactor > 0))
94705
+ fail("swap-margin-factors", "margin factors must be > 0");
94706
+ else if (m.maintenanceFactor > m.initialFactor)
94707
+ fail(
94708
+ "swap-margin-order",
94709
+ `maintenance factor ${m.maintenanceFactor} above initial ${m.initialFactor}`
94710
+ );
94711
+ if (!(m.rateFloor >= 0) || !Number.isFinite(m.rateFloor))
94712
+ fail(
94713
+ "swap-rate-floor",
94714
+ `margin.rateFloor ${m.rateFloor} is not a finite APR fraction`
94715
+ );
94716
+ for (const s of [sw.long, sw.short]) {
94717
+ if (s.pays === s.receives)
94718
+ fail("swap-legs", `${s.side} pays and receives the same leg`);
94719
+ const expected = s.receives === "fixed" ? "floating-up" : "floating-down";
94720
+ if (s.adverseMove !== expected)
94721
+ fail("swap-adverse", `${s.side}.adverseMove must be ${expected}`);
94722
+ if (!s.info?.headline)
94723
+ fail("headline", `swap.${s.side}.info.headline is empty`);
94724
+ if (s.availability.canOpen === false && !s.availability.blockedBy)
94725
+ fail(
94726
+ "blocked-reason",
94727
+ `swap.${s.side}.availability.canOpen is false with no blockedBy`
94728
+ );
94729
+ }
94730
+ if (sw.long.receives === sw.short.receives)
94731
+ fail("swap-sides", "long and short receive the same leg");
94732
+ if (sw.fees.some((f) => f.basis !== "notional"))
94733
+ fail("swap-fee-basis", "every swap fee is charged on notional");
94734
+ }
94595
94735
  if (sheet.borrow) {
94596
94736
  const l = sheet.borrow.liquidation;
94597
94737
  if (l.seizure === "full-collateral") {
@@ -94709,11 +94849,11 @@ function validateTermSheet(sheet) {
94709
94849
  `timelockSecs set but controllerKind is ${g.controllerKind}`
94710
94850
  );
94711
94851
  }
94712
- for (const side of ["supply", "borrow"]) {
94713
- const modes = sheet[side]?.modes;
94852
+ for (const side2 of ["supply", "borrow"]) {
94853
+ const modes = sheet[side2]?.modes;
94714
94854
  if (!modes) continue;
94715
94855
  if (modes.filter((m) => m.isDefault).length > 1)
94716
- fail("multiple-defaults", `${side}.modes has more than one isDefault`);
94856
+ fail("multiple-defaults", `${side2}.modes has more than one isDefault`);
94717
94857
  }
94718
94858
  return v;
94719
94859
  }
@@ -94916,7 +95056,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
94916
95056
  kind: resolveRateKind2(venue),
94917
95057
  source: "chain"
94918
95058
  };
94919
- const availability = resolveAvailability2(row, flags, rate.total ?? 0);
95059
+ const availability2 = resolveAvailability2(row, flags, rate.total ?? 0);
94920
95060
  const basket = resolveBasket(row, chainId);
94921
95061
  return {
94922
95062
  earnUid,
@@ -94981,7 +95121,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
94981
95121
  // utilization cannot be exited, and calling that `instant` is the kind of
94982
95122
  // small lie that produces a stuck user.
94983
95123
  exit: { mode: "instant-capped", settlement: "sync" },
94984
- availability,
95124
+ availability: availability2,
94985
95125
  risk: {
94986
95126
  score: num14(row.risk?.score),
94987
95127
  label: str6(row.risk?.label),
@@ -95929,6 +96069,655 @@ function earnPositionTotals(items) {
95929
96069
  };
95930
96070
  }
95931
96071
 
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 };
96072
+ // src/boros/api.ts
96073
+ var BOROS_API_BASE = "https://api.boros.finance/open-api";
96074
+ var TIMEOUT_MS7 = 8e3;
96075
+ var BorosApiError = class extends Error {
96076
+ constructor(message2, status, errorCode) {
96077
+ super(message2);
96078
+ this.status = status;
96079
+ this.errorCode = errorCode;
96080
+ }
96081
+ status;
96082
+ errorCode;
96083
+ };
96084
+ async function borosApi(path, init, fetchImpl = fetch) {
96085
+ const res = await fetchImpl.call(globalThis, `${BOROS_API_BASE}${path}`, {
96086
+ method: init?.method ?? "GET",
96087
+ headers: {
96088
+ accept: "application/json",
96089
+ ...init?.body !== void 0 ? { "content-type": "application/json" } : {}
96090
+ },
96091
+ body: init?.body !== void 0 ? JSON.stringify(init.body) : void 0,
96092
+ signal: AbortSignal.timeout(TIMEOUT_MS7)
96093
+ });
96094
+ const text = await res.text();
96095
+ let json;
96096
+ try {
96097
+ json = text ? JSON.parse(text) : void 0;
96098
+ } catch {
96099
+ json = void 0;
96100
+ }
96101
+ if (!res.ok) {
96102
+ const msg = Array.isArray(json?.message) ? json.message.map((m) => `${m?.property}: ${(m?.messages ?? []).join(", ")}`).join("; ") : json?.message ?? text.slice(0, 200);
96103
+ throw new BorosApiError(
96104
+ `Boros API ${path.split("?")[0]}: HTTP ${res.status} \u2014 ${msg}`,
96105
+ res.status,
96106
+ json?.errorCode
96107
+ );
96108
+ }
96109
+ return json;
96110
+ }
96111
+ var fromWad = (v) => {
96112
+ if (v === null || v === void 0 || v === "") return 0;
96113
+ try {
96114
+ const b = BigInt(String(v));
96115
+ const neg = b < 0n;
96116
+ const a = neg ? -b : b;
96117
+ const out = Number(a / 10n ** 12n) / 1e6;
96118
+ return neg ? -out : out;
96119
+ } catch {
96120
+ const n = Number(v);
96121
+ return Number.isFinite(n) ? n / 1e18 : 0;
96122
+ }
96123
+ };
96124
+
96125
+ // src/boros/termSheet.ts
96126
+ var BOROS_PROFILE_ID = "boros.funding-swap@v1";
96127
+ var ARBITRUM = "42161";
96128
+ var BOROS_GOVERNANCE = {
96129
+ mutability: "governed",
96130
+ controller: "0x7417407a24194180017201bfec07fb4fe5a566e0",
96131
+ controllerKind: "SAFE",
96132
+ safe: { threshold: 2, owners: 3 },
96133
+ powers: [
96134
+ "upgrade-implementation",
96135
+ "change-fees",
96136
+ "change-ltv",
96137
+ "set-caps",
96138
+ "freeze-market"
96139
+ ]
96140
+ };
96141
+ var MIN_CASH_USD = 10;
96142
+ var WITHDRAWAL_COOLDOWN_SECS = 900;
96143
+ var FORCED_DELEVERAGE_HEALTH = 0.7;
96144
+ var spreadVenues = (m) => {
96145
+ if (!m.isSpread) return void 0;
96146
+ const parts = m.name.split(" - ").map((p) => p.trim().split(/\s+/)[0]);
96147
+ return parts.length >= 2 ? parts : void 0;
96148
+ };
96149
+ function fees(m) {
96150
+ const out = [
96151
+ {
96152
+ id: "origination",
96153
+ label: "Taker fee (\xD7 years to maturity)",
96154
+ when: "entry",
96155
+ unit: "apr-percent",
96156
+ basis: "notional",
96157
+ value: m.fees.takerFee * 100,
96158
+ payee: "protocol",
96159
+ mutable: true,
96160
+ description: "Charged once on the filled size, scaled by the time left to maturity. Resting (maker) orders pay none."
96161
+ }
96162
+ ];
96163
+ if (m.fees.settleFee != null)
96164
+ out.push({
96165
+ id: "settlement",
96166
+ label: "Settlement fee",
96167
+ when: "ongoing",
96168
+ unit: "apr-percent",
96169
+ basis: "notional",
96170
+ value: m.fees.settleFee * 100,
96171
+ payee: "protocol",
96172
+ mutable: true,
96173
+ description: "Charged on the open size at every funding settlement."
96174
+ });
96175
+ if (m.margin.liquidation)
96176
+ out.push({
96177
+ id: "liquidation-bonus",
96178
+ label: "Liquidation fee (\xD7 years to maturity)",
96179
+ when: "liquidation",
96180
+ unit: "apr-percent",
96181
+ basis: "notional",
96182
+ value: m.margin.liquidation.feeRate * 100,
96183
+ payee: "protocol",
96184
+ mutable: true,
96185
+ description: "Treasury fee on the liquidated size, on top of the liquidator incentive."
96186
+ });
96187
+ return out;
96188
+ }
96189
+ function availability(m, fixedApr) {
96190
+ const tradable = m.state === "Normal" && m.timeToMaturitySec > 0;
96191
+ const capFull = m.openInterestCap?.hard != null && m.openInterest != null && m.openInterest.units >= m.openInterestCap.hard;
96192
+ const canOpen = tradable && !capFull && fixedApr != null;
96193
+ return {
96194
+ canOpen,
96195
+ canClose: tradable,
96196
+ ...canOpen ? {} : {
96197
+ blockedBy: !tradable ? m.timeToMaturitySec > 0 ? "paused" : "shutdown" : capFull ? "cap-full" : "no-liquidity"
96198
+ },
96199
+ gating: "permissionless",
96200
+ requires: ["token-approval"],
96201
+ ...m.openInterestCap?.hard != null ? {
96202
+ cap: String(m.openInterestCap.hard),
96203
+ capUtilization: m.openInterest && m.openInterestCap.hard > 0 ? Math.min(1, m.openInterest.units / m.openInterestCap.hard) : void 0
96204
+ } : {}
96205
+ };
96206
+ }
96207
+ function side(m, s) {
96208
+ const fixedApr = (s === "long" ? m.rates.bestAskApr : m.rates.bestBidApr) ?? void 0;
96209
+ const floating = m.rates.floatingApr ?? void 0;
96210
+ const carryApr = fixedApr != null && floating != null ? s === "short" ? fixedApr - floating : floating - fixedApr : void 0;
96211
+ return {
96212
+ side: s,
96213
+ pays: s === "long" ? "fixed" : "floating",
96214
+ receives: s === "long" ? "floating" : "fixed",
96215
+ ...fixedApr != null ? { fixedApr } : {},
96216
+ ...carryApr != null ? { carryApr } : {},
96217
+ adverseMove: s === "short" ? "floating-up" : "floating-down",
96218
+ availability: availability(m, fixedApr),
96219
+ // filled by finalizeInfo from the structured fields
96220
+ info: { headline: "", description: "", tags: [] }
96221
+ };
96222
+ }
96223
+ function buildBorosTermSheet(m, nowSec9 = Math.floor(Date.now() / 1e3)) {
96224
+ const collateral = {
96225
+ chainId: ARBITRUM,
96226
+ address: m.collateral.address,
96227
+ symbol: m.collateral.symbol,
96228
+ decimals: m.collateral.decimals
96229
+ };
96230
+ const swap = {
96231
+ kind: "funding-rate-swap",
96232
+ notional: { unit: collateral, underlying: m.asset },
96233
+ floating: {
96234
+ source: "perp-funding",
96235
+ venue: m.venue,
96236
+ ...spreadVenues(m) ? { spreadOf: spreadVenues(m) } : {},
96237
+ ...m.rates.floatingApr != null ? { apr: m.rates.floatingApr } : {},
96238
+ ...m.paymentPeriodSec ? { settlementSecs: m.paymentPeriodSec } : {}
96239
+ },
96240
+ fixed: {
96241
+ source: m.ammId ? "orderbook-amm" : "orderbook",
96242
+ ...m.rates.markApr != null ? { markApr: m.rates.markApr } : {},
96243
+ ...m.rates.bestBidApr != null ? { bestBidApr: m.rates.bestBidApr } : {},
96244
+ ...m.rates.bestAskApr != null ? { bestAskApr: m.rates.bestAskApr } : {}
96245
+ },
96246
+ maturity: {
96247
+ kind: "fixed-date",
96248
+ maturity: m.maturity,
96249
+ maturityIso: new Date(m.maturity * 1e3).toISOString(),
96250
+ secondsToMaturity: Math.max(0, m.maturity - nowSec9),
96251
+ atMaturity: "settles"
96252
+ },
96253
+ margin: {
96254
+ model: m.isIsolatedOnly ? "isolated" : "cross-or-isolated",
96255
+ initialFactor: m.margin.kIM,
96256
+ maintenanceFactor: m.margin.kMM,
96257
+ rateFloor: m.margin.rateFloor,
96258
+ timeFloorSecs: m.margin.tThreshSec,
96259
+ ...m.maxLeverage != null ? { maxLeverage: m.maxLeverage } : {},
96260
+ minCashUsd: MIN_CASH_USD,
96261
+ formula: "IM = |size| \xD7 max(|rate|, rateFloor) \xD7 initialFactor \xD7 max(timeToMaturity, timeFloor); MM uses maintenanceFactor at the mark rate"
96262
+ },
96263
+ liquidation: {
96264
+ healthThreshold: 1,
96265
+ forcedDeleverageHealth: FORCED_DELEVERAGE_HEALTH,
96266
+ ...m.margin.liquidation ? {
96267
+ incentive: {
96268
+ base: m.margin.liquidation.incentiveBase,
96269
+ slope: m.margin.liquidation.incentiveSlope
96270
+ }
96271
+ } : {},
96272
+ model: "position-transfer"
96273
+ },
96274
+ exit: {
96275
+ close: "market-trade",
96276
+ priceRisk: "market-price",
96277
+ withdrawalCooldownSecs: WITHDRAWAL_COOLDOWN_SECS,
96278
+ requestResetsCooldown: true,
96279
+ finalizePermissionless: true
96280
+ },
96281
+ fees: fees(m),
96282
+ counterparty: {
96283
+ kind: "orderbook",
96284
+ address: m.address,
96285
+ solvency: "margined"
96286
+ },
96287
+ ...m.openInterestCap ? {
96288
+ openInterestCap: {
96289
+ hard: m.openInterestCap.hard,
96290
+ ...m.openInterestCap.softPct != null ? { softPct: m.openInterestCap.softPct } : {},
96291
+ ...m.openInterest ? { current: m.openInterest.units } : {}
96292
+ }
96293
+ } : {},
96294
+ principal: {
96295
+ protected: false,
96296
+ risks: ["margin-loss", "liquidation", "basis", "roll"]
96297
+ },
96298
+ long: side(m, "long"),
96299
+ short: side(m, "short")
96300
+ };
96301
+ const sheet = {
96302
+ schemaVersion: TERM_SHEET_SCHEMA_VERSION,
96303
+ asOf: nowSec9,
96304
+ profileId: BOROS_PROFILE_ID,
96305
+ marketUid: `BOROS:${ARBITRUM}:${m.marketId}`,
96306
+ lender: "BOROS",
96307
+ chainId: ARBITRUM,
96308
+ asset: collateral,
96309
+ swap,
96310
+ governance: BOROS_GOVERNANCE,
96311
+ ...m.fundingOracle ? {
96312
+ oracle: {
96313
+ kind: "rate-feed",
96314
+ address: m.fundingOracle.address,
96315
+ provider: "Pendle Boros funding index",
96316
+ priceDescription: `${m.venue} ${m.asset} funding`,
96317
+ ...m.fundingOracle.maxUpdateDelaySec ? { heartbeatSecs: m.fundingOracle.maxUpdateDelaySec } : {}
96318
+ }
96319
+ } : {},
96320
+ coverage: {
96321
+ present: ["swap", "governance", ...m.fundingOracle ? ["oracle"] : []],
96322
+ notApplicable: {
96323
+ supply: "a rate swap lends nothing",
96324
+ borrow: "a rate swap borrows nothing",
96325
+ utilization: "no pool \u2014 rates are set by the order book",
96326
+ exposures: "no collateral backs a loan; each side posts its own margin"
96327
+ },
96328
+ pending: {
96329
+ ...m.fundingOracle ? {} : { oracle: "funding-index oracle not published for this market" },
96330
+ "governance.markets": "market contracts are beacon proxies; the beacon owner is not resolved",
96331
+ "governance.roles": "parameter setters are role-gated (PendleRoles); the role holders are not enumerated"
96332
+ }
96333
+ }
96334
+ };
96335
+ return finalizeInfo(sheet);
96336
+ }
96337
+
96338
+ // src/boros/markets.ts
96339
+ var pct3 = (v) => {
96340
+ const n = typeof v === "number" ? v : Number(v);
96341
+ return v === null || v === void 0 || !Number.isFinite(n) ? null : n * 100;
96342
+ };
96343
+ async function fetchBorosCollaterals(fetchImpl) {
96344
+ const r = await borosApi(
96345
+ "/v1/assets/all",
96346
+ void 0,
96347
+ fetchImpl
96348
+ );
96349
+ return (r?.assets ?? []).filter((a) => Number(a.tokenId) > 0).map((a) => ({
96350
+ tokenId: Number(a.tokenId),
96351
+ address: a.address.toLowerCase(),
96352
+ symbol: a.symbol,
96353
+ decimals: Number(a.decimals),
96354
+ priceUsd: Number(a.usdPrice) || 0
96355
+ }));
96356
+ }
96357
+ function convertBorosMarket(m, collaterals, nowSec9 = Math.floor(Date.now() / 1e3)) {
96358
+ const tokenId = Number(m?.tokenId);
96359
+ const collateral = collaterals.get(tokenId);
96360
+ if (!collateral || !m?.imData) return null;
96361
+ const d = m.data ?? {};
96362
+ const cfg = m.config ?? {};
96363
+ const ext = m.extConfig ?? {};
96364
+ const meta = m.metadata ?? {};
96365
+ const ammId = Number(ext.ammId ?? meta.ammId ?? 0);
96366
+ const ammAddress = ext.ammAddress ?? meta.ammAddress;
96367
+ const usd = (units) => units * collateral.priceUsd;
96368
+ const oi = Number(d.notionalOI);
96369
+ const vol = Number(d.volume24h);
96370
+ const maturity = Number(m.imData.maturity);
96371
+ const market = {
96372
+ marketId: Number(m.marketId),
96373
+ address: String(m.address).toLowerCase(),
96374
+ symbol: m.imData.symbol,
96375
+ name: m.imData.name,
96376
+ venue: meta.platformName ?? "",
96377
+ asset: meta.assetSymbol ?? "",
96378
+ isSpread: Boolean(meta.isSpreadMarket),
96379
+ maturity,
96380
+ timeToMaturitySec: Math.max(0, maturity - nowSec9),
96381
+ collateral,
96382
+ isIsolatedOnly: Boolean(m.imData.isIsolatedOnly),
96383
+ state: m.state ?? "",
96384
+ maxLeverage: Number.isFinite(Number(meta.maxLeverage)) ? Number(meta.maxLeverage) : null,
96385
+ tickStep: Number(m.imData.tickStep),
96386
+ ammId: ammId > 0 ? ammId : null,
96387
+ ammAddress: ammAddress && !/^0x0{40}$/i.test(ammAddress) ? String(ammAddress).toLowerCase() : null,
96388
+ paymentPeriodSec: Number(ext.paymentPeriod) || null,
96389
+ rates: {
96390
+ markApr: pct3(d.markApr),
96391
+ floatingApr: pct3(d.floatingApr),
96392
+ midApr: pct3(d.midApr),
96393
+ bestBidApr: pct3(d.bestBid),
96394
+ bestAskApr: pct3(d.bestAsk),
96395
+ lastTradedApr: pct3(d.lastTradedApr),
96396
+ ammImpliedApr: pct3(d.ammImpliedApr)
96397
+ },
96398
+ openInterest: Number.isFinite(oi) ? { units: oi, usd: usd(oi) } : null,
96399
+ volume24h: Number.isFinite(vol) ? { units: vol, usd: usd(vol) } : null,
96400
+ fees: {
96401
+ takerFee: fromWad(cfg.takerFee),
96402
+ otcFee: fromWad(cfg.otcFee),
96403
+ settleFee: ext.settleFeeRate != null ? fromWad(ext.settleFeeRate) : null
96404
+ },
96405
+ margin: {
96406
+ kIM: fromWad(cfg.kIM),
96407
+ kMM: fromWad(cfg.kMM),
96408
+ rateFloor: Number(m.imData.marginFloor) || 0,
96409
+ iTickThresh: Number(m.imData.iTickThresh),
96410
+ tThreshSec: Number(cfg.tThresh) || 0,
96411
+ liquidation: cfg.liqSettings ? {
96412
+ incentiveBase: fromWad(cfg.liqSettings.base),
96413
+ incentiveSlope: fromWad(cfg.liqSettings.slope),
96414
+ feeRate: fromWad(cfg.liqSettings.feeRate)
96415
+ } : null
96416
+ },
96417
+ openInterestCap: cfg.hardOICap != null ? {
96418
+ hard: fromWad(cfg.hardOICap),
96419
+ softPct: cfg.softOICap != null ? Number(cfg.softOICap) / 100 : null
96420
+ } : null,
96421
+ fundingOracle: cfg.fIndexOracle && !/^0x0{40}$/i.test(cfg.fIndexOracle) ? {
96422
+ address: String(cfg.fIndexOracle).toLowerCase(),
96423
+ maxUpdateDelaySec: Number(ext.maxUpdateDelay) || null
96424
+ } : null
96425
+ };
96426
+ market.termSheet = buildBorosTermSheet(market, nowSec9);
96427
+ return market;
96428
+ }
96429
+ var MEMO_MS2 = 3e4;
96430
+ var memo2;
96431
+ async function fetchBorosMarkets(opts = {}) {
96432
+ const now = Date.now();
96433
+ if (!opts.fresh && memo2 && now - memo2.at < MEMO_MS2) return memo2.value;
96434
+ const value = (async () => {
96435
+ const [collaterals, list] = await Promise.all([
96436
+ fetchBorosCollaterals(opts.fetchImpl),
96437
+ borosApi(
96438
+ "/v1/markets?limit=100&isWhitelisted=true",
96439
+ void 0,
96440
+ opts.fetchImpl
96441
+ )
96442
+ ]);
96443
+ const byId = new Map(collaterals.map((c) => [c.tokenId, c]));
96444
+ const nowSec9 = Math.floor(Date.now() / 1e3);
96445
+ return (list?.results ?? []).map((m) => convertBorosMarket(m, byId, nowSec9)).filter((m) => m !== null).sort((a, b) => a.maturity - b.maturity || a.marketId - b.marketId);
96446
+ })();
96447
+ memo2 = { at: now, value };
96448
+ value.catch(() => {
96449
+ if (memo2?.value === value) memo2 = void 0;
96450
+ });
96451
+ return value;
96452
+ }
96453
+ async function fetchBorosMarket(marketId, opts = {}) {
96454
+ return (await fetchBorosMarkets(opts)).find((m) => m.marketId === marketId);
96455
+ }
96456
+
96457
+ // src/boros/book.ts
96458
+ var TICK_SIZE = 1e-4;
96459
+ async function fetchBorosOrderBook(marketId, fetchImpl) {
96460
+ const r = await borosApi(
96461
+ `/v2/markets/order-books?marketId=${marketId}&tickSize=${TICK_SIZE}&includeAmm=true`,
96462
+ void 0,
96463
+ fetchImpl
96464
+ );
96465
+ const side2 = (s) => {
96466
+ const ia = Array.isArray(s?.ia) ? s.ia : [];
96467
+ const sz = Array.isArray(s?.sz) ? s.sz : [];
96468
+ return ia.map((t, i) => ({ aprPct: t * TICK_SIZE * 100, size: fromWad(sz[i]) })).filter((l) => l.size > 0);
96469
+ };
96470
+ return {
96471
+ marketId,
96472
+ bids: side2(r?.long).sort((a, b) => b.aprPct - a.aprPct),
96473
+ asks: side2(r?.short).sort((a, b) => a.aprPct - b.aprPct)
96474
+ };
96475
+ }
96476
+
96477
+ // src/boros/positions.ts
96478
+ var CROSS = "ffffff";
96479
+ var marketAccOf = (root, tokenId, marketHex = CROSS) => `${root.toLowerCase()}00${tokenId.toString(16).padStart(4, "0")}${marketHex}`;
96480
+ var pctOrNull = (v) => v === null || v === void 0 || v === "" ? null : fromWad(v) * 100;
96481
+ async function fetchBorosAccount(account, fetchImpl) {
96482
+ const root = account.toLowerCase();
96483
+ const [active, collaterals] = await Promise.all([
96484
+ borosApi(
96485
+ `/v1/accounts/active-positions?userAddress=${root}&accountId=0`,
96486
+ void 0,
96487
+ fetchImpl
96488
+ ),
96489
+ fetchBorosCollaterals(fetchImpl)
96490
+ ]);
96491
+ const positionsRaw = active?.results ?? [];
96492
+ const marketAccs = collaterals.map((c) => marketAccOf(root, c.tokenId));
96493
+ const infos = marketAccs.length ? await borosApi(
96494
+ "/v1/accounts/market-acc-infos",
96495
+ { method: "POST", body: { marketAccs } },
96496
+ fetchImpl
96497
+ ) : { results: [] };
96498
+ const byMarket = /* @__PURE__ */ new Map();
96499
+ const crossAccounts = [];
96500
+ for (const info of infos?.results ?? []) {
96501
+ const acc = String(info?.marketAcc ?? "").toLowerCase();
96502
+ const tokenId = parseInt(acc.slice(44, 48), 16);
96503
+ const positions2 = Array.isArray(info?.positions) ? info.positions : [];
96504
+ for (const p of positions2) byMarket.set(Number(p.marketId), p);
96505
+ const maint = positions2.reduce((s, p) => s + fromWad(p?.maintMargin), 0);
96506
+ const net = fromWad(info?.netBalance);
96507
+ const cash = fromWad(info?.totalCash);
96508
+ if (cash === 0 && net === 0 && positions2.length === 0) continue;
96509
+ crossAccounts.push({
96510
+ tokenId,
96511
+ marketAcc: acc,
96512
+ collateral: collaterals.find((c) => c.tokenId === tokenId) ?? null,
96513
+ totalCash: cash,
96514
+ netBalance: net,
96515
+ initialMargin: fromWad(info?.initialMargin),
96516
+ availableInitialMargin: fromWad(info?.availableInitialMargin),
96517
+ availableMaintMargin: fromWad(info?.availableMaintMargin),
96518
+ healthRatio: maint > 0 ? net / maint : null
96519
+ });
96520
+ }
96521
+ const positions = positionsRaw.map((p) => {
96522
+ const info = byMarket.get(Number(p.marketId));
96523
+ const size = fromWad(p.signedSize);
96524
+ return {
96525
+ marketId: Number(p.marketId),
96526
+ marketAcc: String(p.marketAcc).toLowerCase(),
96527
+ isCross: Boolean(p.isCross),
96528
+ side: Number(p.side) === 1 ? "short" : "long",
96529
+ signedSize: String(p.signedSize),
96530
+ size: Math.abs(size),
96531
+ fixedAprPct: p.fixedApr === null || p.fixedApr === void 0 ? null : Number(p.fixedApr) * 100,
96532
+ cumulativePnl: p.cumulativePnl != null ? fromWad(p.cumulativePnl) : null,
96533
+ isMatured: Boolean(p.isMatured),
96534
+ liquidationAprPct: info ? pctOrNull(info.liquidationApr) : null,
96535
+ initialMargin: info ? fromWad(info.initialMargin) : null,
96536
+ maintMargin: info ? fromWad(info.maintMargin) : null,
96537
+ positionValue: info ? fromWad(info.positionValue) : null
96538
+ };
96539
+ });
96540
+ return { account: root, positions, crossAccounts };
96541
+ }
96542
+
96543
+ // src/boros/margin.ts
96544
+ var SECONDS_PER_YEAR20 = 365 * 24 * 3600;
96545
+ var ttmYears = (m, ttmSec) => Math.max(ttmSec ?? m.timeToMaturitySec, m.margin.tThreshSec) / SECONDS_PER_YEAR20;
96546
+ function borosInitialMargin(m, size, ratePct, ttmSec) {
96547
+ const r = Math.max(Math.abs(ratePct) / 100, m.margin.rateFloor);
96548
+ return Math.abs(size) * r * m.margin.kIM * ttmYears(m, ttmSec);
96549
+ }
96550
+ function borosMaintenanceMargin(m, size, markPct, ttmSec) {
96551
+ const r = Math.max(Math.abs(markPct) / 100, m.margin.rateFloor);
96552
+ return Math.abs(size) * r * m.margin.kMM * ttmYears(m, ttmSec);
96553
+ }
96554
+ function borosTakerFee(m, size) {
96555
+ return Math.abs(size) * m.fees.takerFee * m.timeToMaturitySec / SECONDS_PER_YEAR20;
96556
+ }
96557
+ function walkBorosBook(levels, size) {
96558
+ let left = size;
96559
+ let cost = 0;
96560
+ let worst = null;
96561
+ for (const l of levels) {
96562
+ if (left <= 0) break;
96563
+ const take = Math.min(left, l.size);
96564
+ cost += take * l.aprPct;
96565
+ left -= take;
96566
+ worst = l.aprPct;
96567
+ }
96568
+ const filled = size - Math.max(0, left);
96569
+ return {
96570
+ filled,
96571
+ avgAprPct: filled > 0 ? cost / filled : null,
96572
+ worstAprPct: worst,
96573
+ partial: left > 1e-12
96574
+ };
96575
+ }
96576
+ function borosRateMoveToLiquidation(m, size, equity, markPct) {
96577
+ const ttm = m.timeToMaturitySec / SECONDS_PER_YEAR20;
96578
+ if (!(Math.abs(size) > 0) || !(ttm > 0)) return null;
96579
+ const mm = borosMaintenanceMargin(m, size, markPct);
96580
+ const slack = equity - mm;
96581
+ if (slack <= 0) return 0;
96582
+ return slack / (Math.abs(size) * ttm) * 100;
96583
+ }
96584
+
96585
+ // src/boros/hedge.ts
96586
+ function borosSideTerms(m, side2) {
96587
+ const sheet = m.termSheet;
96588
+ const s = sheet?.swap?.[side2];
96589
+ return sheet && s ? {
96590
+ profileId: sheet.profileId,
96591
+ marketUid: sheet.marketUid,
96592
+ side: side2,
96593
+ info: s.info
96594
+ } : void 0;
96595
+ }
96596
+ var FUNDING_EXPOSURE_PROFILES = {
96597
+ ethena: {
96598
+ id: "ethena",
96599
+ label: "Ethena (USDe / sUSDe)",
96600
+ assets: { BTC: 0.5, ETH: 0.5 },
96601
+ venues: ["Binance", "Bybit", "OKX", "Hyperliquid", "Gate"],
96602
+ fundingShare: "most \u2014 the remainder is ETH staking and the USDtb/T-bill leg",
96603
+ notes: [
96604
+ "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."
96605
+ ]
96606
+ },
96607
+ resolv: {
96608
+ id: "resolv",
96609
+ label: "Resolv (USR / stUSR / wstUSR)",
96610
+ assets: { ETH: 0.7, BTC: 0.3 },
96611
+ venues: ["Binance", "Hyperliquid", "Bybit", "OKX"],
96612
+ fundingShare: "part \u2014 the rest is staked-ETH yield, and RLP takes losses first",
96613
+ notes: [
96614
+ "Resolv hedges staked ETH/BTC with short perps; stUSR receives the senior share of that funding, so its sensitivity to funding is below 1."
96615
+ ]
96616
+ }
96617
+ };
96618
+ var SYMBOL_PROFILE = {
96619
+ USDE: "ethena",
96620
+ SUSDE: "ethena",
96621
+ USR: "resolv",
96622
+ STUSR: "resolv",
96623
+ WSTUSR: "resolv"
96624
+ };
96625
+ function fundingExposureOf(symbol) {
96626
+ if (!symbol) return void 0;
96627
+ const base = symbol.toUpperCase().replace(/^PT[-_]/, "").replace(/[-_ ]\d{1,2}[A-Z]{3}\d{2,4}$/, "").replace(/[-_ ](\d{4}-\d{2}-\d{2})$/, "");
96628
+ const id = SYMBOL_PROFILE[base];
96629
+ return id ? FUNDING_EXPOSURE_PROFILES[id] : void 0;
96630
+ }
96631
+ var normSym = (s) => s.toUpperCase().replace(/₮/g, "T");
96632
+ function rankBorosHedgeMarkets(markets, f) {
96633
+ const minSec = (f.minDays ?? 7) * 86400;
96634
+ const coll = (f.collateralSymbols ?? ["USDT0", "USDT", f.asset ?? ""]).map(
96635
+ normSym
96636
+ );
96637
+ const collRank = (m) => {
96638
+ const s = normSym(m.collateral.symbol);
96639
+ const i = coll.findIndex((c) => c && (s === c || s === `W${c}`));
96640
+ return i < 0 ? coll.length : i;
96641
+ };
96642
+ const venueRank = (m) => {
96643
+ const i = (f.venues ?? []).findIndex(
96644
+ (v) => v.toLowerCase() === m.venue.toLowerCase()
96645
+ );
96646
+ return i < 0 ? 99 : i;
96647
+ };
96648
+ return markets.filter(
96649
+ (m) => m.state === "Normal" && !m.isSpread && !m.isIsolatedOnly && m.timeToMaturitySec >= minSec && (!f.asset || m.asset.toUpperCase() === f.asset.toUpperCase())
96650
+ ).sort(
96651
+ (a, b) => collRank(a) - collRank(b) || venueRank(a) - venueRank(b) || a.maturity - b.maturity || (b.openInterest?.usd ?? 0) - (a.openInterest?.usd ?? 0)
96652
+ );
96653
+ }
96654
+ var BOROS_MIN_CASH_USD = 10;
96655
+ function quoteBorosHedgeLeg(p) {
96656
+ const m = p.market;
96657
+ const side2 = p.side ?? "short";
96658
+ const price2 = m.collateral.priceUsd;
96659
+ if (!(price2 > 0))
96660
+ throw new Error(`Boros: no USD price for ${m.collateral.symbol}`);
96661
+ const size = p.notionalUsd / price2;
96662
+ const fill = walkBorosBook(side2 === "short" ? p.book.bids : p.book.asks, size);
96663
+ const fixed = fill.avgAprPct;
96664
+ const floating = m.rates.floatingApr;
96665
+ const takerFee = borosTakerFee(m, size);
96666
+ const ttmYears2 = m.timeToMaturitySec / SECONDS_PER_YEAR20;
96667
+ const settleAprPct = m.fees.settleFee != null ? m.fees.settleFee * 100 : null;
96668
+ const allIn = ttmYears2 > 0 ? takerFee / size / ttmYears2 * 100 + (settleAprPct ?? 0) : null;
96669
+ const rateForMargin = fixed ?? m.rates.markApr ?? 0;
96670
+ const initial = borosInitialMargin(m, size, rateForMargin);
96671
+ const maintenance = borosMaintenanceMargin(
96672
+ m,
96673
+ size,
96674
+ m.rates.markApr ?? rateForMargin
96675
+ );
96676
+ const buffer = p.marginBuffer ?? 2;
96677
+ const floorUnits = BOROS_MIN_CASH_USD / price2;
96678
+ const needed = Math.max(initial * buffer + takerFee, floorUnits);
96679
+ const deposit = Math.max(0, needed - (p.existingFreeMargin ?? 0));
96680
+ const equity = (p.existingFreeMargin ?? 0) + deposit - takerFee;
96681
+ return {
96682
+ marketId: m.marketId,
96683
+ symbol: m.symbol,
96684
+ venue: m.venue,
96685
+ asset: m.asset,
96686
+ maturity: m.maturity,
96687
+ daysToMaturity: m.timeToMaturitySec / 86400,
96688
+ collateral: m.collateral,
96689
+ side: side2,
96690
+ notionalUsd: p.notionalUsd,
96691
+ size,
96692
+ fixedAprPct: fixed,
96693
+ worstAprPct: fill.worstAprPct,
96694
+ floatingAprPct: floating,
96695
+ lockSpreadPct: fixed != null && floating != null ? side2 === "short" ? fixed - floating : floating - fixed : null,
96696
+ fillRatio: size > 0 ? fill.filled / size : 0,
96697
+ costs: {
96698
+ takerFee,
96699
+ takerFeeUsd: takerFee * price2,
96700
+ settleFeeAprPct: settleAprPct,
96701
+ allInAprPct: allIn
96702
+ },
96703
+ margin: {
96704
+ initial,
96705
+ initialUsd: initial * price2,
96706
+ maintenance,
96707
+ deposit,
96708
+ depositUsd: deposit * price2,
96709
+ buffer,
96710
+ rateMoveToLiquidationPct: borosRateMoveToLiquidation(
96711
+ m,
96712
+ size,
96713
+ equity,
96714
+ m.rates.markApr ?? rateForMargin
96715
+ )
96716
+ },
96717
+ terms: borosSideTerms(m, side2)
96718
+ };
96719
+ }
96720
+
96721
+ 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
96722
  //# sourceMappingURL=index.js.map
95934
96723
  //# sourceMappingURL=index.js.map