@1delta/margin-fetcher 5.0.129 → 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.d.ts +601 -5
- package/dist/index.js +991 -134
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
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
|
|
12717
|
-
const a = out[
|
|
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[
|
|
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 = (
|
|
20694
|
-
const raw =
|
|
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,
|
|
22081
|
+
async walkBooksSide(chainId, side2) {
|
|
22082
22082
|
const out = /* @__PURE__ */ new Map();
|
|
22083
|
-
const sort =
|
|
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?.[
|
|
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(
|
|
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,
|
|
22255
|
+
async getOfferMakers(marketId, side2, assets) {
|
|
22256
22256
|
const map = {};
|
|
22257
|
-
const url = `${this.baseUrl}/books/${marketId}/${
|
|
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,
|
|
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
|
|
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) => [
|
|
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
|
|
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) => [
|
|
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 = (
|
|
37131
|
-
const raw =
|
|
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
|
|
59570
|
-
const mu = uid(lender,
|
|
59569
|
+
for (const side2 of [m.silo0, m.silo1]) {
|
|
59570
|
+
const mu = uid(lender, side2.silo);
|
|
59571
59571
|
push2({
|
|
59572
59572
|
chainId,
|
|
59573
|
-
address:
|
|
59573
|
+
address: side2.silo,
|
|
59574
59574
|
lenderKey: lender,
|
|
59575
59575
|
family: "silo",
|
|
59576
59576
|
role: "market",
|
|
59577
59577
|
marketUid: mu,
|
|
59578
|
-
asset: lc(
|
|
59578
|
+
asset: lc(side2.token)
|
|
59579
59579
|
});
|
|
59580
|
-
if (isAddr3(
|
|
59580
|
+
if (isAddr3(side2.protectedShareToken))
|
|
59581
59581
|
push2({
|
|
59582
59582
|
chainId,
|
|
59583
|
-
address:
|
|
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(
|
|
59589
|
+
asset: lc(side2.token),
|
|
59590
59590
|
shareEvents: "transfers"
|
|
59591
59591
|
});
|
|
59592
|
-
if (isAddr3(
|
|
59592
|
+
if (isAddr3(side2.debtShareToken))
|
|
59593
59593
|
push2({
|
|
59594
59594
|
chainId,
|
|
59595
|
-
address:
|
|
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(
|
|
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
|
|
59616
|
-
if (isAddr3(
|
|
59617
|
-
legs[lc(
|
|
59618
|
-
marketUid: uid(lender,
|
|
59619
|
-
asset: lc(
|
|
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,
|
|
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:
|
|
67140
|
-
const tokenLc = (
|
|
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 = (
|
|
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(
|
|
67152
|
-
const supplyUsdNum =
|
|
67153
|
-
const borrowedNum = safeNumber3(
|
|
67154
|
-
const borrowedUsdNum =
|
|
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 =
|
|
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 = (
|
|
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:
|
|
67284
|
-
const tokenLc = (
|
|
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 = (
|
|
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(
|
|
67296
|
-
const supplyUsdNum =
|
|
67297
|
-
const borrowedNum = safeNumber4(
|
|
67298
|
-
const borrowedUsdNum =
|
|
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 =
|
|
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 = (
|
|
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
|
|
80320
|
+
const pct4 = toBigInt16(cell[0]);
|
|
80321
80321
|
const fixed = toBigInt16(cell[1]);
|
|
80322
|
-
return
|
|
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
|
-
|
|
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(
|
|
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
|
|
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 =
|
|
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
|
|
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 =
|
|
85076
|
-
const s =
|
|
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]));
|
|
@@ -87745,13 +87818,16 @@ var RATE_MODEL_TO_KIND = {
|
|
|
87745
87818
|
};
|
|
87746
87819
|
function rateKindOf(input) {
|
|
87747
87820
|
const mapped = input.rateModel ? RATE_MODEL_TO_KIND[input.rateModel] : void 0;
|
|
87748
|
-
|
|
87821
|
+
if (mapped) return mapped;
|
|
87822
|
+
const maturity = input.fixedTerm?.maturity;
|
|
87823
|
+
if (isNum(maturity) && maturity > 0) return "fixed-term";
|
|
87824
|
+
return "variable-curve";
|
|
87749
87825
|
}
|
|
87750
|
-
function rewardTerms(input,
|
|
87826
|
+
function rewardTerms(input, side2) {
|
|
87751
87827
|
if (!input.rewards?.length) return void 0;
|
|
87752
87828
|
const out = [];
|
|
87753
87829
|
for (const r of input.rewards) {
|
|
87754
|
-
const apr =
|
|
87830
|
+
const apr = side2 === "supply" ? r.depositRate ?? 0 : r.variableBorrowRate ?? r.stableBorrowRate ?? 0;
|
|
87755
87831
|
if (!apr) continue;
|
|
87756
87832
|
const isPoints = r.kind === "points" || !r.asset;
|
|
87757
87833
|
out.push({
|
|
@@ -87761,7 +87837,7 @@ function rewardTerms(input, side) {
|
|
|
87761
87837
|
} : void 0,
|
|
87762
87838
|
kind: isPoints ? "points" : "token",
|
|
87763
87839
|
apr,
|
|
87764
|
-
side,
|
|
87840
|
+
side: side2,
|
|
87765
87841
|
claim: r.claim ?? (isPoints ? "none" : "accrual"),
|
|
87766
87842
|
endsAt: r.endsAt,
|
|
87767
87843
|
// Points have no priceable value, so they must not inflate `aprTotal`.
|
|
@@ -87770,20 +87846,20 @@ function rewardTerms(input, side) {
|
|
|
87770
87846
|
}
|
|
87771
87847
|
return out.length ? out : void 0;
|
|
87772
87848
|
}
|
|
87773
|
-
function buildRate(input,
|
|
87849
|
+
function buildRate(input, side2) {
|
|
87774
87850
|
const kind = rateKindOf(input);
|
|
87775
|
-
const rewards = rewardTerms(input,
|
|
87851
|
+
const rewards = rewardTerms(input, side2);
|
|
87776
87852
|
const priceableRewards = (rewards ?? []).filter((r) => !r.indicative).reduce((s, r) => s + r.apr, 0);
|
|
87777
87853
|
const menuBest = input.terms?.length ? Math.min(...input.terms.map((t) => t.apr)) : void 0;
|
|
87778
87854
|
let base;
|
|
87779
|
-
if (
|
|
87855
|
+
if (side2 === "supply") {
|
|
87780
87856
|
base = input.depositRate ?? 0;
|
|
87781
87857
|
} else if (kind === "fixed-term") {
|
|
87782
87858
|
base = menuBest ?? input.stableBorrowRate ?? input.variableBorrowRate ?? 0;
|
|
87783
87859
|
} else {
|
|
87784
87860
|
base = input.variableBorrowRate ?? 0;
|
|
87785
87861
|
}
|
|
87786
|
-
const intrinsic =
|
|
87862
|
+
const intrinsic = side2 === "supply" ? input.intrinsicYield ?? 0 : 0;
|
|
87787
87863
|
return {
|
|
87788
87864
|
kind,
|
|
87789
87865
|
apr: base,
|
|
@@ -87822,10 +87898,10 @@ function buildMaturity(input, now) {
|
|
|
87822
87898
|
}
|
|
87823
87899
|
return { kind: "perpetual" };
|
|
87824
87900
|
}
|
|
87825
|
-
function buildFees(input,
|
|
87901
|
+
function buildFees(input, side2) {
|
|
87826
87902
|
const out = [];
|
|
87827
87903
|
const ft = input.fixedTerm;
|
|
87828
|
-
if (
|
|
87904
|
+
if (side2 === "borrow") {
|
|
87829
87905
|
const origination = input.originationFee ?? ft?.fees?.originationFeePercent ?? void 0;
|
|
87830
87906
|
if (isNum(origination) && origination !== 0) {
|
|
87831
87907
|
out.push({
|
|
@@ -87867,7 +87943,7 @@ function buildFees(input, side) {
|
|
|
87867
87943
|
});
|
|
87868
87944
|
}
|
|
87869
87945
|
}
|
|
87870
|
-
if (
|
|
87946
|
+
if (side2 === "supply") {
|
|
87871
87947
|
if (isNum(ft?.fees?.continuousFeeApr) && ft.fees.continuousFeeApr !== 0) {
|
|
87872
87948
|
out.push({
|
|
87873
87949
|
id: "continuous",
|
|
@@ -87940,15 +88016,15 @@ function capUtil(total, cap) {
|
|
|
87940
88016
|
if (!isNum(cap) || cap <= 0 || !isNum(total)) return void 0;
|
|
87941
88017
|
return clamp013(total / cap);
|
|
87942
88018
|
}
|
|
87943
|
-
function buildAvailability(input,
|
|
88019
|
+
function buildAvailability(input, side2) {
|
|
87944
88020
|
const frozen = input.isFrozen === true;
|
|
87945
88021
|
const inactive = input.isActive === false;
|
|
87946
|
-
const enabled =
|
|
87947
|
-
const cap =
|
|
87948
|
-
const total =
|
|
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;
|
|
87949
88025
|
const capUtilization = capUtil(total, cap);
|
|
87950
88026
|
const capFull = capUtilization != null && capUtilization >= 1;
|
|
87951
|
-
const noLiquidity =
|
|
88027
|
+
const noLiquidity = side2 === "borrow" && isNum(input.borrowLiquidity) && input.borrowLiquidity <= 0;
|
|
87952
88028
|
const canOpen = enabled && !frozen && !inactive && !capFull && !noLiquidity;
|
|
87953
88029
|
let blockedBy;
|
|
87954
88030
|
if (!canOpen) {
|
|
@@ -87967,10 +88043,10 @@ function buildAvailability(input, side) {
|
|
|
87967
88043
|
gating: "permissionless",
|
|
87968
88044
|
// A borrow below the protocol's floor REVERTS, so gate the CTA on it
|
|
87969
88045
|
// rather than letting the transaction fail.
|
|
87970
|
-
minSize:
|
|
88046
|
+
minSize: side2 === "borrow" ? resolveMinDebt(input) : resolveMinCollateral(input),
|
|
87971
88047
|
cap: isNum(cap) && cap > 0 ? String(cap) : void 0,
|
|
87972
88048
|
capUtilization,
|
|
87973
|
-
requires:
|
|
88049
|
+
requires: side2 === "supply" ? ["token-approval"] : void 0
|
|
87974
88050
|
};
|
|
87975
88051
|
}
|
|
87976
88052
|
function buildUtilization(input) {
|
|
@@ -88112,8 +88188,8 @@ function buildSupply(input, now, siblings) {
|
|
|
88112
88188
|
return void 0;
|
|
88113
88189
|
const rate = buildRate(input, "supply");
|
|
88114
88190
|
const maturity = buildMaturity(input, now);
|
|
88115
|
-
const
|
|
88116
|
-
const
|
|
88191
|
+
const fees2 = buildFees(input, "supply");
|
|
88192
|
+
const availability2 = buildAvailability(input, "supply");
|
|
88117
88193
|
const liquidity = isNum(input.totalLiquidity) ? {
|
|
88118
88194
|
assets: input.totalLiquidity,
|
|
88119
88195
|
assetsUsd: input.totalLiquidityUsd,
|
|
@@ -88129,16 +88205,16 @@ function buildSupply(input, now, siblings) {
|
|
|
88129
88205
|
liquidity,
|
|
88130
88206
|
partialAllowed: true,
|
|
88131
88207
|
priceRisk: "none",
|
|
88132
|
-
fees:
|
|
88208
|
+
fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
|
|
88133
88209
|
},
|
|
88134
|
-
fees,
|
|
88210
|
+
fees: fees2,
|
|
88135
88211
|
backedBy: buildExposures2(input, siblings, "backing"),
|
|
88136
88212
|
modes: buildModes(input),
|
|
88137
88213
|
counterparty: {
|
|
88138
88214
|
kind: "pool",
|
|
88139
88215
|
solvency: "overcollateralized"
|
|
88140
88216
|
},
|
|
88141
|
-
availability,
|
|
88217
|
+
availability: availability2,
|
|
88142
88218
|
principal: { protected: true, risks: [] },
|
|
88143
88219
|
info: { headline: "", description: "", tags: [] }
|
|
88144
88220
|
};
|
|
@@ -88152,7 +88228,7 @@ function buildBorrow(input, now, siblings) {
|
|
|
88152
88228
|
return void 0;
|
|
88153
88229
|
const rate = buildRate(input, "borrow");
|
|
88154
88230
|
const maturity = buildMaturity(input, now);
|
|
88155
|
-
const
|
|
88231
|
+
const fees2 = buildFees(input, "borrow");
|
|
88156
88232
|
const acceptedCollateral = buildExposures2(input, siblings, "accepted");
|
|
88157
88233
|
const borrow = {
|
|
88158
88234
|
rate,
|
|
@@ -88166,12 +88242,12 @@ function buildBorrow(input, now, siblings) {
|
|
|
88166
88242
|
// The same floor, read as a DUST limit: a partial repay may not leave
|
|
88167
88243
|
// the position below it.
|
|
88168
88244
|
minDebt: resolveMinDebt(input),
|
|
88169
|
-
fees:
|
|
88245
|
+
fees: fees2.filter((f) => f.when === "exit" || f.when === "late")
|
|
88170
88246
|
},
|
|
88171
88247
|
liquidation: liquidationFrom(cfg, input, acceptedCollateral),
|
|
88172
88248
|
acceptedCollateral,
|
|
88173
88249
|
modes: buildModes(input),
|
|
88174
|
-
fees,
|
|
88250
|
+
fees: fees2,
|
|
88175
88251
|
counterparty: { kind: "pool", solvency: "overcollateralized" },
|
|
88176
88252
|
availability: buildAvailability(input, "borrow"),
|
|
88177
88253
|
info: { headline: "", description: "", tags: [] }
|
|
@@ -88210,6 +88286,17 @@ function finalizeInfo(sheet) {
|
|
|
88210
88286
|
tags: deriveSupplyTags(sheet.supply, market)
|
|
88211
88287
|
};
|
|
88212
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
|
+
}
|
|
88213
88300
|
if (sheet.borrow) {
|
|
88214
88301
|
sheet.borrow.info = {
|
|
88215
88302
|
headline: sheet.borrow.info.headline || borrowHeadline(sheet.borrow),
|
|
@@ -88284,8 +88371,8 @@ function buildTermSheet(input, opts = {}) {
|
|
|
88284
88371
|
base.borrow?.acceptedCollateral ?? base.supply?.backedBy
|
|
88285
88372
|
);
|
|
88286
88373
|
const merged = mergeDeep(base, opts.patch);
|
|
88287
|
-
for (const
|
|
88288
|
-
if (merged[
|
|
88374
|
+
for (const side2 of ["supply", "borrow"]) {
|
|
88375
|
+
if (merged[side2] && !base[side2]) merged[side2] = void 0;
|
|
88289
88376
|
}
|
|
88290
88377
|
const withInfo = finalizeInfo(merged);
|
|
88291
88378
|
withInfo.coverage = mergeAdapterCoverage(
|
|
@@ -88820,7 +88907,7 @@ function derivedRoutes(input, mode) {
|
|
|
88820
88907
|
});
|
|
88821
88908
|
return routes2.length > 0 ? routes2 : void 0;
|
|
88822
88909
|
}
|
|
88823
|
-
function buildExit(input, t,
|
|
88910
|
+
function buildExit(input, t, fees2) {
|
|
88824
88911
|
const mode = resolveExitMode(input, t);
|
|
88825
88912
|
const priceRisk = resolvePriceRisk(input, t);
|
|
88826
88913
|
const ratio = input.instantLiquidityRatio ?? (isNum2(input.liquidity) && isNum2(input.totalAssets) && input.totalAssets > 0 ? clamp014(input.liquidity / input.totalAssets) : void 0);
|
|
@@ -88845,7 +88932,7 @@ function buildExit(input, t, fees) {
|
|
|
88845
88932
|
priceRisk,
|
|
88846
88933
|
// Only the request/queue models have something to cancel, and only where
|
|
88847
88934
|
// the protocol exposes it — left undefined rather than guessed.
|
|
88848
|
-
fees:
|
|
88935
|
+
fees: fees2.filter((f) => f.when === "exit" || f.when === "performance")
|
|
88849
88936
|
};
|
|
88850
88937
|
}
|
|
88851
88938
|
function resolvePriceRisk(input, t) {
|
|
@@ -89052,15 +89139,15 @@ function buildVaultTermSheet(input, opts = {}) {
|
|
|
89052
89139
|
const now = opts.now ?? Math.floor(Date.now() / 1e3);
|
|
89053
89140
|
const t = vaultTraits(input.provider) ?? FALLBACK_TRAITS;
|
|
89054
89141
|
const maturity = buildMaturity2(input, now);
|
|
89055
|
-
const
|
|
89142
|
+
const fees2 = buildFees2(input, t);
|
|
89056
89143
|
const supply = {
|
|
89057
89144
|
// A vault share is never collateral IN the vault — it earns, full stop.
|
|
89058
89145
|
// (It may be collateral somewhere else; that is the other market's sheet.)
|
|
89059
89146
|
role: "yield",
|
|
89060
89147
|
rate: buildRate2(input, t, maturity),
|
|
89061
89148
|
maturity,
|
|
89062
|
-
exit: buildExit(input, t,
|
|
89063
|
-
fees,
|
|
89149
|
+
exit: buildExit(input, t, fees2),
|
|
89150
|
+
fees: fees2,
|
|
89064
89151
|
backedBy: buildBacking(input),
|
|
89065
89152
|
counterparty: buildCounterparty(input, t),
|
|
89066
89153
|
availability: buildAvailability2(input, now),
|
|
@@ -89737,7 +89824,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
|
|
|
89737
89824
|
},
|
|
89738
89825
|
maturity
|
|
89739
89826
|
);
|
|
89740
|
-
const
|
|
89827
|
+
const availability2 = resolveAvailability(meta, maturity);
|
|
89741
89828
|
const exitMode = resolveExitMode2(provider, meta, tvl, liq);
|
|
89742
89829
|
const market = {
|
|
89743
89830
|
earnUid: buildVaultEarnUid(provider, chainId, address),
|
|
@@ -89835,7 +89922,7 @@ function earnMarketFromVault(row, chainId, opts = {}) {
|
|
|
89835
89922
|
// not disagree about what the legs out are.
|
|
89836
89923
|
routes: Array.isArray(meta.exitRoutes) ? meta.exitRoutes : void 0
|
|
89837
89924
|
},
|
|
89838
|
-
availability,
|
|
89925
|
+
availability: availability2,
|
|
89839
89926
|
risk: {
|
|
89840
89927
|
yieldProfile: yieldProfile(info.yieldProfile),
|
|
89841
89928
|
denomination: denomination(info.denomination),
|
|
@@ -90010,15 +90097,15 @@ function sdkRates(row, provider) {
|
|
|
90010
90097
|
totalRate: num15(row.depositRate)
|
|
90011
90098
|
};
|
|
90012
90099
|
}
|
|
90013
|
-
const
|
|
90100
|
+
const pct4 = (v) => {
|
|
90014
90101
|
const n = num15(v);
|
|
90015
90102
|
return n === void 0 ? void 0 : n * 100;
|
|
90016
90103
|
};
|
|
90017
90104
|
return {
|
|
90018
90105
|
// GMX splits fee APY from incentive APR; HyperCore reports one number.
|
|
90019
|
-
supplyRate:
|
|
90020
|
-
rewardsRate:
|
|
90021
|
-
totalRate:
|
|
90106
|
+
supplyRate: pct4(row.baseApy ?? row.apr),
|
|
90107
|
+
rewardsRate: pct4(row.bonusApr),
|
|
90108
|
+
totalRate: pct4(row.apy ?? row.apr)
|
|
90022
90109
|
};
|
|
90023
90110
|
}
|
|
90024
90111
|
function toVaultTermInput(vault, provider, chainId) {
|
|
@@ -90510,12 +90597,12 @@ var getVaultPublicDataAll = async (chainId, providers, multicallRetry, prices =
|
|
|
90510
90597
|
tasks.push(
|
|
90511
90598
|
(async () => {
|
|
90512
90599
|
const gasPrice = await getEvmClient(chainId).getGasPrice();
|
|
90513
|
-
const
|
|
90600
|
+
const fees2 = await fetchGmxExecutionFees(
|
|
90514
90601
|
chainId,
|
|
90515
90602
|
multicallRetry,
|
|
90516
90603
|
gasPrice
|
|
90517
90604
|
);
|
|
90518
|
-
if (
|
|
90605
|
+
if (fees2) out.gmxExecutionFees = fees2;
|
|
90519
90606
|
})().catch((e) => {
|
|
90520
90607
|
warn8(
|
|
90521
90608
|
`[vaults] gmx execution-fee fetch failed for chain ${chainId}:`,
|
|
@@ -91632,12 +91719,12 @@ function assetFindings(sheet) {
|
|
|
91632
91719
|
}
|
|
91633
91720
|
return out;
|
|
91634
91721
|
}
|
|
91635
|
-
function findingsFor(sheet,
|
|
91636
|
-
const sideFindings =
|
|
91722
|
+
function findingsFor(sheet, side2) {
|
|
91723
|
+
const sideFindings = side2 === "supply" ? sheet.supply ? [...supplyFindings(sheet.supply), ...assetFindings(sheet)] : [] : sheet.borrow ? borrowFindings(sheet.borrow) : [];
|
|
91637
91724
|
return rankFindings([...sideFindings, ...marketFindings(sheet)]);
|
|
91638
91725
|
}
|
|
91639
|
-
function hasCritical(sheet,
|
|
91640
|
-
return findingsFor(sheet,
|
|
91726
|
+
function hasCritical(sheet, side2) {
|
|
91727
|
+
return findingsFor(sheet, side2).some((f) => f.severity === "critical");
|
|
91641
91728
|
}
|
|
91642
91729
|
var exactlyAdapter = {
|
|
91643
91730
|
id: "exactly",
|
|
@@ -91730,10 +91817,17 @@ var termAdapter = {
|
|
|
91730
91817
|
const auction = input.fixedTerm?.auction;
|
|
91731
91818
|
return {
|
|
91732
91819
|
supply: {
|
|
91820
|
+
// A repo-token holder is paid by `redeemTermRepoTokens`, which opens
|
|
91821
|
+
// only after the repurchase window closes. A secondary listing
|
|
91822
|
+
// (`createListing`) exists in the protocol but no route of ours sells
|
|
91823
|
+
// through it, so the exit a lender can take is the redemption — and
|
|
91824
|
+
// the withdraw builder refuses before it (FIXED_RATE_EARN_GAPS.md §2).
|
|
91733
91825
|
exit: {
|
|
91734
|
-
mode: "
|
|
91826
|
+
mode: "at-maturity",
|
|
91735
91827
|
settlement: "sync",
|
|
91736
|
-
|
|
91828
|
+
// Par, unless the repo defaulted: then the servicer pays the
|
|
91829
|
+
// haircut redemption value.
|
|
91830
|
+
priceRisk: "haircut-formula",
|
|
91737
91831
|
partialAllowed: true
|
|
91738
91832
|
},
|
|
91739
91833
|
counterparty: { kind: "auction", solvency: "overcollateralized" },
|
|
@@ -92284,9 +92378,9 @@ var alchemixAdapter = {
|
|
|
92284
92378
|
const isCollateralRow = input.collateralActive !== false;
|
|
92285
92379
|
const protocolFeeBps = num17(a.protocolFeeBps);
|
|
92286
92380
|
const liquidatorFeeBps = num17(a.liquidatorFeeBps);
|
|
92287
|
-
const
|
|
92381
|
+
const fees2 = [];
|
|
92288
92382
|
if (protocolFeeBps != null)
|
|
92289
|
-
|
|
92383
|
+
fees2.push({
|
|
92290
92384
|
id: "redemption",
|
|
92291
92385
|
label: "Redemption fee",
|
|
92292
92386
|
// Charged whenever a Transmuter redemption settles part of the debt —
|
|
@@ -92302,7 +92396,7 @@ var alchemixAdapter = {
|
|
|
92302
92396
|
description: "Taken from your collateral on the part of your debt that redemptions settle; the rest of the debt pays nothing."
|
|
92303
92397
|
});
|
|
92304
92398
|
if (liquidatorFeeBps != null)
|
|
92305
|
-
|
|
92399
|
+
fees2.push({
|
|
92306
92400
|
id: "liquidation-bonus",
|
|
92307
92401
|
label: "Liquidator fee",
|
|
92308
92402
|
when: "liquidation",
|
|
@@ -92402,7 +92496,7 @@ var alchemixAdapter = {
|
|
|
92402
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."
|
|
92403
92497
|
}
|
|
92404
92498
|
},
|
|
92405
|
-
fees,
|
|
92499
|
+
fees: fees2,
|
|
92406
92500
|
counterparty: {
|
|
92407
92501
|
kind: "cdp",
|
|
92408
92502
|
solvency: "overcollateralized",
|
|
@@ -92620,7 +92714,7 @@ var frankencoinAdapter = {
|
|
|
92620
92714
|
const challengerPct = ppmToPercent(fc.challengerRewardPPM);
|
|
92621
92715
|
const expiration = Number(fc.expiration ?? 0);
|
|
92622
92716
|
const challengePeriod = Number(fc.challengePeriod ?? 0);
|
|
92623
|
-
const
|
|
92717
|
+
const fees2 = [
|
|
92624
92718
|
reservePct != null && reservePct > 0 ? {
|
|
92625
92719
|
id: "reserve-contribution",
|
|
92626
92720
|
label: "Equity-reserve contribution",
|
|
@@ -92691,7 +92785,7 @@ var frankencoinAdapter = {
|
|
|
92691
92785
|
] : void 0,
|
|
92692
92786
|
badDebt: "socialized"
|
|
92693
92787
|
},
|
|
92694
|
-
fees,
|
|
92788
|
+
fees: fees2,
|
|
92695
92789
|
counterparty: { kind: "cdp", solvency: "overcollateralized" }
|
|
92696
92790
|
},
|
|
92697
92791
|
constraints: {
|
|
@@ -93338,7 +93432,7 @@ function build2(input) {
|
|
|
93338
93432
|
};
|
|
93339
93433
|
if (!isNum4(input.originationFee) && input.borrowingEnabled === true)
|
|
93340
93434
|
pending["borrow.fees"] = "the vault's borrow fee is not on the row";
|
|
93341
|
-
const
|
|
93435
|
+
const fees2 = isNum4(input.originationFee) && input.originationFee > 0 ? [
|
|
93342
93436
|
{
|
|
93343
93437
|
id: "origination",
|
|
93344
93438
|
label: "Borrow fee",
|
|
@@ -93369,7 +93463,7 @@ function build2(input) {
|
|
|
93369
93463
|
trigger: "price",
|
|
93370
93464
|
seizure: "proportional"
|
|
93371
93465
|
},
|
|
93372
|
-
...
|
|
93466
|
+
...fees2 ? { fees: fees2 } : {},
|
|
93373
93467
|
ext: {
|
|
93374
93468
|
jupiterLend: {
|
|
93375
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.",
|
|
@@ -94397,6 +94491,24 @@ function toDigest(sheet) {
|
|
|
94397
94491
|
tags: sheet.borrow.info.tags,
|
|
94398
94492
|
acceptedCollateral: strip(sheet.borrow.acceptedCollateral)
|
|
94399
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,
|
|
94400
94512
|
oracle: sheet.oracle ? {
|
|
94401
94513
|
kind: sheet.oracle.kind,
|
|
94402
94514
|
address: sheet.oracle.address,
|
|
@@ -94536,42 +94648,42 @@ function validateTermSheet(sheet) {
|
|
|
94536
94648
|
if (sheet.schemaVersion !== TERM_SHEET_SCHEMA_VERSION)
|
|
94537
94649
|
fail("schema-version", `unexpected schemaVersion ${sheet.schemaVersion}`);
|
|
94538
94650
|
if (!sheet.profileId) fail("profile-id", "missing profileId");
|
|
94539
|
-
for (const
|
|
94540
|
-
const s = sheet[
|
|
94651
|
+
for (const side2 of ["supply", "borrow"]) {
|
|
94652
|
+
const s = sheet[side2];
|
|
94541
94653
|
if (!s) continue;
|
|
94542
94654
|
const c = s.rate.components;
|
|
94543
94655
|
const expected = (c.base ?? 0) + (c.rewards ?? 0) + (c.intrinsic ?? 0);
|
|
94544
94656
|
if (!approx(s.rate.aprTotal, expected, 1e-6))
|
|
94545
94657
|
fail(
|
|
94546
94658
|
"apr-total",
|
|
94547
|
-
`${
|
|
94659
|
+
`${side2}.rate.aprTotal ${s.rate.aprTotal} != base+rewards+intrinsic ${expected}`
|
|
94548
94660
|
);
|
|
94549
94661
|
const priceable = (s.rate.rewards ?? []).filter((r) => !r.indicative).reduce((sum3, r) => sum3 + r.apr, 0);
|
|
94550
94662
|
if (s.rate.rewards && !approx(c.rewards ?? 0, priceable, 1e-6))
|
|
94551
94663
|
fail(
|
|
94552
94664
|
"rewards-priceable",
|
|
94553
|
-
`${
|
|
94665
|
+
`${side2}.rate.components.rewards ${c.rewards} != sum of non-indicative rewards ${priceable}`
|
|
94554
94666
|
);
|
|
94555
94667
|
if (s.rate.basis !== "apr-nominal")
|
|
94556
|
-
fail("rate-basis", `${
|
|
94668
|
+
fail("rate-basis", `${side2}.rate.basis must be apr-nominal`);
|
|
94557
94669
|
if (s.maturity.kind === "fixed-date" && s.maturity.maturity == null)
|
|
94558
94670
|
fail(
|
|
94559
94671
|
"maturity-missing",
|
|
94560
|
-
`${
|
|
94672
|
+
`${side2}.maturity.kind is fixed-date with no maturity`
|
|
94561
94673
|
);
|
|
94562
94674
|
if ((s.rate.kind === "fixed-term" || s.rate.kind === "fixed-open") && s.rate.kind === "fixed-term" && s.maturity.kind === "perpetual")
|
|
94563
94675
|
fail(
|
|
94564
94676
|
"fixed-term-perpetual",
|
|
94565
|
-
`${
|
|
94677
|
+
`${side2} is fixed-term but maturity.kind is perpetual`
|
|
94566
94678
|
);
|
|
94567
94679
|
if (s.availability.canOpen === false && !s.availability.blockedBy)
|
|
94568
94680
|
fail(
|
|
94569
94681
|
"blocked-reason",
|
|
94570
|
-
`${
|
|
94682
|
+
`${side2}.availability.canOpen is false with no blockedBy`
|
|
94571
94683
|
);
|
|
94572
|
-
if (!s.info.headline) fail("headline", `${
|
|
94684
|
+
if (!s.info.headline) fail("headline", `${side2}.info.headline is empty`);
|
|
94573
94685
|
if (!Array.isArray(s.info.tags))
|
|
94574
|
-
fail("tags", `${
|
|
94686
|
+
fail("tags", `${side2}.info.tags is not an array`);
|
|
94575
94687
|
}
|
|
94576
94688
|
if (sheet.supply) {
|
|
94577
94689
|
const e = sheet.supply.exit;
|
|
@@ -94582,6 +94694,44 @@ function validateTermSheet(sheet) {
|
|
|
94582
94694
|
fail("instant-cooldown", "exit.mode instant must not carry a cooldown");
|
|
94583
94695
|
}
|
|
94584
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
|
+
}
|
|
94585
94735
|
if (sheet.borrow) {
|
|
94586
94736
|
const l = sheet.borrow.liquidation;
|
|
94587
94737
|
if (l.seizure === "full-collateral") {
|
|
@@ -94699,17 +94849,75 @@ function validateTermSheet(sheet) {
|
|
|
94699
94849
|
`timelockSecs set but controllerKind is ${g.controllerKind}`
|
|
94700
94850
|
);
|
|
94701
94851
|
}
|
|
94702
|
-
for (const
|
|
94703
|
-
const modes = sheet[
|
|
94852
|
+
for (const side2 of ["supply", "borrow"]) {
|
|
94853
|
+
const modes = sheet[side2]?.modes;
|
|
94704
94854
|
if (!modes) continue;
|
|
94705
94855
|
if (modes.filter((m) => m.isDefault).length > 1)
|
|
94706
|
-
fail("multiple-defaults", `${
|
|
94856
|
+
fail("multiple-defaults", `${side2}.modes has more than one isDefault`);
|
|
94707
94857
|
}
|
|
94708
94858
|
return v;
|
|
94709
94859
|
}
|
|
94710
94860
|
function validateTermSheets(sheets) {
|
|
94711
94861
|
return sheets.flatMap((s) => validateTermSheet(s));
|
|
94712
94862
|
}
|
|
94863
|
+
function isOrderBookLendRow(m) {
|
|
94864
|
+
return m.venueKind === "lending" && (isMidnight(m.venue) || isTerm(m.venue));
|
|
94865
|
+
}
|
|
94866
|
+
function stampOrderBookLendRow(m, facts, nowSec9 = Math.floor(Date.now() / 1e3)) {
|
|
94867
|
+
const midnight = isMidnight(m.venue);
|
|
94868
|
+
m.maturity = {
|
|
94869
|
+
kind: "fixed-date",
|
|
94870
|
+
maturity: facts.maturity,
|
|
94871
|
+
maturityIso: new Date(facts.maturity * 1e3).toISOString(),
|
|
94872
|
+
secondsToMaturity: Math.max(0, facts.maturity - nowSec9)
|
|
94873
|
+
};
|
|
94874
|
+
if (m.tvl) m.depth = { ...m.tvl };
|
|
94875
|
+
delete m.liquidity;
|
|
94876
|
+
delete m.utilization;
|
|
94877
|
+
m.exit = {
|
|
94878
|
+
...m.exit,
|
|
94879
|
+
mode: midnight ? "market-sale" : "at-maturity"
|
|
94880
|
+
};
|
|
94881
|
+
delete m.exit.history;
|
|
94882
|
+
let name = m.name?.replace(HEX_SUFFIX, "");
|
|
94883
|
+
if (facts.collateral.length > 0) {
|
|
94884
|
+
m.collateral = facts.collateral;
|
|
94885
|
+
const symbols = facts.collateral.map((c) => c.symbol).filter((s) => !!s);
|
|
94886
|
+
if (symbols.length > 0 && !namesAny(name, symbols)) {
|
|
94887
|
+
const asset = m.asset?.symbol ?? "";
|
|
94888
|
+
name = asset ? `${asset} \xB7 vs ${symbols.join(" + ")}` : `vs ${symbols.join(" + ")}`;
|
|
94889
|
+
}
|
|
94890
|
+
}
|
|
94891
|
+
if (name) m.name = withMaturityLabel(name, m.maturity) ?? name;
|
|
94892
|
+
if (facts.exitOpensAt !== void 0 && facts.exitOpensAt > nowSec9) {
|
|
94893
|
+
m.capabilities = (m.capabilities ?? []).map(
|
|
94894
|
+
(c) => c.action === "withdraw" ? { ...c, availableFrom: facts.exitOpensAt } : c
|
|
94895
|
+
);
|
|
94896
|
+
}
|
|
94897
|
+
}
|
|
94898
|
+
var HEX_SUFFIX = / · 0x[0-9a-fA-F]{4}$/;
|
|
94899
|
+
function namesAny(name, symbols) {
|
|
94900
|
+
if (!name) return false;
|
|
94901
|
+
const lower4 = name.toLowerCase();
|
|
94902
|
+
return symbols.some((s) => lower4.includes(s.toLowerCase()));
|
|
94903
|
+
}
|
|
94904
|
+
function disambiguateOrderBookNames(rows) {
|
|
94905
|
+
const groups = /* @__PURE__ */ new Map();
|
|
94906
|
+
for (const m of rows) {
|
|
94907
|
+
if (!isOrderBookLendRow(m) || !m.name) continue;
|
|
94908
|
+
const k = `${m.chainId}:${m.name}`;
|
|
94909
|
+
const g = groups.get(k);
|
|
94910
|
+
if (g) g.push(m);
|
|
94911
|
+
else groups.set(k, [m]);
|
|
94912
|
+
}
|
|
94913
|
+
for (const g of groups.values()) {
|
|
94914
|
+
if (g.length < 2) continue;
|
|
94915
|
+
for (const m of g) {
|
|
94916
|
+
const id = m.venue.split("_").pop() ?? "";
|
|
94917
|
+
m.name = `${m.name} \xB7 0x${id.slice(0, 4).toUpperCase()}`;
|
|
94918
|
+
}
|
|
94919
|
+
}
|
|
94920
|
+
}
|
|
94713
94921
|
var FIXED_YIELD_EARN_VENUE_PREFIXES = [
|
|
94714
94922
|
"MORPHO_MIDNIGHT",
|
|
94715
94923
|
"TERM_FINANCE",
|
|
@@ -94848,7 +95056,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
|
|
|
94848
95056
|
kind: resolveRateKind2(venue),
|
|
94849
95057
|
source: "chain"
|
|
94850
95058
|
};
|
|
94851
|
-
const
|
|
95059
|
+
const availability2 = resolveAvailability2(row, flags, rate.total ?? 0);
|
|
94852
95060
|
const basket = resolveBasket(row, chainId);
|
|
94853
95061
|
return {
|
|
94854
95062
|
earnUid,
|
|
@@ -94913,7 +95121,7 @@ function earnMarketFromPool(row, fallbackChainId, venueCollaterals) {
|
|
|
94913
95121
|
// utilization cannot be exited, and calling that `instant` is the kind of
|
|
94914
95122
|
// small lie that produces a stuck user.
|
|
94915
95123
|
exit: { mode: "instant-capped", settlement: "sync" },
|
|
94916
|
-
availability,
|
|
95124
|
+
availability: availability2,
|
|
94917
95125
|
risk: {
|
|
94918
95126
|
score: num14(row.risk?.score),
|
|
94919
95127
|
label: str6(row.risk?.label),
|
|
@@ -95861,6 +96069,655 @@ function earnPositionTotals(items) {
|
|
|
95861
96069
|
};
|
|
95862
96070
|
}
|
|
95863
96071
|
|
|
95864
|
-
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, 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, 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, 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 };
|
|
95865
96722
|
//# sourceMappingURL=index.js.map
|
|
95866
96723
|
//# sourceMappingURL=index.js.map
|