@defisaver/positions-sdk 2.1.127-midnight-13-dev → 2.1.127-midnight-15-dev

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.
Files changed (108) hide show
  1. package/cjs/aaveV3/merkl.js +10 -9
  2. package/cjs/aaveV4/merkl.js +5 -6
  3. package/cjs/claiming/aaveV3.d.ts +2 -1
  4. package/cjs/claiming/aaveV3.js +13 -4
  5. package/cjs/compoundV3/index.d.ts +1 -0
  6. package/cjs/compoundV3/index.js +8 -2
  7. package/cjs/compoundV3/merkl.d.ts +16 -0
  8. package/cjs/compoundV3/merkl.js +77 -0
  9. package/cjs/fluid/index.d.ts +9 -0
  10. package/cjs/fluid/index.js +36 -10
  11. package/cjs/fluid/merkl.d.ts +32 -0
  12. package/cjs/fluid/merkl.js +103 -0
  13. package/cjs/helpers/fluidHelpers/index.d.ts +3 -1
  14. package/cjs/helpers/fluidHelpers/index.js +37 -4
  15. package/cjs/helpers/liquityV2Helpers/index.d.ts +2 -1
  16. package/cjs/helpers/liquityV2Helpers/index.js +3 -2
  17. package/cjs/helpers/morphoMidnightHelpers/headroom.d.ts +48 -0
  18. package/cjs/helpers/morphoMidnightHelpers/headroom.js +52 -0
  19. package/cjs/helpers/morphoMidnightHelpers/index.d.ts +2 -1
  20. package/cjs/helpers/morphoMidnightHelpers/index.js +10 -6
  21. package/cjs/liquityV2/index.js +3 -4
  22. package/cjs/moneymarket/moneymarketCommonService.js +2 -0
  23. package/cjs/morphoBlue/index.d.ts +1 -0
  24. package/cjs/morphoBlue/index.js +16 -10
  25. package/cjs/morphoBlue/merkl.d.ts +35 -0
  26. package/cjs/morphoBlue/merkl.js +102 -0
  27. package/cjs/morphoMidnight/index.js +22 -25
  28. package/cjs/portfolio/index.js +5 -5
  29. package/cjs/services/merkl.d.ts +6 -0
  30. package/cjs/services/merkl.js +39 -0
  31. package/cjs/staking/eligibility.d.ts +4 -0
  32. package/cjs/staking/eligibility.js +11 -1
  33. package/cjs/types/claiming.d.ts +12 -1
  34. package/cjs/types/claiming.js +2 -0
  35. package/cjs/types/common.d.ts +6 -1
  36. package/cjs/types/common.js +6 -1
  37. package/cjs/types/fluid.d.ts +2 -0
  38. package/cjs/types/liquityV2.d.ts +3 -0
  39. package/cjs/types/merkl.d.ts +8 -0
  40. package/cjs/types/morphoMidnight.d.ts +1 -4
  41. package/cjs/types/morphoMidnight.js +0 -3
  42. package/esm/aaveV3/merkl.js +11 -10
  43. package/esm/aaveV4/merkl.js +5 -6
  44. package/esm/claiming/aaveV3.d.ts +2 -1
  45. package/esm/claiming/aaveV3.js +12 -4
  46. package/esm/compoundV3/index.d.ts +1 -0
  47. package/esm/compoundV3/index.js +5 -1
  48. package/esm/compoundV3/merkl.d.ts +16 -0
  49. package/esm/compoundV3/merkl.js +72 -0
  50. package/esm/fluid/index.d.ts +9 -0
  51. package/esm/fluid/index.js +31 -9
  52. package/esm/fluid/merkl.d.ts +32 -0
  53. package/esm/fluid/merkl.js +95 -0
  54. package/esm/helpers/fluidHelpers/index.d.ts +3 -1
  55. package/esm/helpers/fluidHelpers/index.js +38 -6
  56. package/esm/helpers/liquityV2Helpers/index.d.ts +2 -1
  57. package/esm/helpers/liquityV2Helpers/index.js +3 -2
  58. package/esm/helpers/morphoMidnightHelpers/headroom.d.ts +48 -0
  59. package/esm/helpers/morphoMidnightHelpers/headroom.js +45 -0
  60. package/esm/helpers/morphoMidnightHelpers/index.d.ts +2 -1
  61. package/esm/helpers/morphoMidnightHelpers/index.js +7 -4
  62. package/esm/liquityV2/index.js +3 -4
  63. package/esm/moneymarket/moneymarketCommonService.js +2 -0
  64. package/esm/morphoBlue/index.d.ts +1 -0
  65. package/esm/morphoBlue/index.js +11 -9
  66. package/esm/morphoBlue/merkl.d.ts +35 -0
  67. package/esm/morphoBlue/merkl.js +96 -0
  68. package/esm/morphoMidnight/index.js +23 -26
  69. package/esm/portfolio/index.js +6 -6
  70. package/esm/services/merkl.d.ts +6 -0
  71. package/esm/services/merkl.js +35 -0
  72. package/esm/staking/eligibility.d.ts +4 -0
  73. package/esm/staking/eligibility.js +9 -0
  74. package/esm/types/claiming.d.ts +12 -1
  75. package/esm/types/claiming.js +2 -0
  76. package/esm/types/common.d.ts +6 -1
  77. package/esm/types/common.js +5 -0
  78. package/esm/types/fluid.d.ts +2 -0
  79. package/esm/types/liquityV2.d.ts +3 -0
  80. package/esm/types/merkl.d.ts +8 -0
  81. package/esm/types/morphoMidnight.d.ts +1 -4
  82. package/esm/types/morphoMidnight.js +0 -3
  83. package/package.json +1 -1
  84. package/src/aaveV3/merkl.ts +7 -7
  85. package/src/aaveV4/merkl.ts +5 -5
  86. package/src/claiming/aaveV3.ts +19 -7
  87. package/src/compoundV3/index.ts +6 -1
  88. package/src/compoundV3/merkl.ts +76 -0
  89. package/src/fluid/index.ts +37 -9
  90. package/src/fluid/merkl.ts +102 -0
  91. package/src/helpers/fluidHelpers/index.ts +68 -6
  92. package/src/helpers/liquityV2Helpers/index.ts +4 -1
  93. package/src/helpers/morphoMidnightHelpers/headroom.ts +82 -0
  94. package/src/helpers/morphoMidnightHelpers/index.ts +11 -7
  95. package/src/liquityV2/index.ts +4 -3
  96. package/src/moneymarket/moneymarketCommonService.ts +2 -0
  97. package/src/morphoBlue/index.ts +24 -9
  98. package/src/morphoBlue/merkl.ts +121 -0
  99. package/src/morphoMidnight/index.ts +25 -27
  100. package/src/portfolio/index.ts +6 -6
  101. package/src/services/merkl.ts +31 -0
  102. package/src/staking/eligibility.ts +10 -0
  103. package/src/types/claiming.ts +13 -0
  104. package/src/types/common.ts +6 -0
  105. package/src/types/fluid.ts +3 -1
  106. package/src/types/liquityV2.ts +3 -0
  107. package/src/types/merkl.ts +6 -0
  108. package/src/types/morphoMidnight.ts +0 -3
@@ -0,0 +1,76 @@
1
+ import { getAssetInfoByAddress } from '@defisaver/tokens';
2
+ import { aprToApy } from '../moneymarket';
3
+ import { fetchAllMerklOpportunities } from '../services/merkl';
4
+ import { compareAddresses, wethToEth } from '../services/utils';
5
+ import {
6
+ CompoundV3AssetData,
7
+ IncentiveData,
8
+ IncentiveEligibilityId,
9
+ IncentiveKind,
10
+ MerklOpportunity,
11
+ NetworkNumber,
12
+ OpportunityAction,
13
+ OpportunityStatus,
14
+ } from '../types';
15
+
16
+ /**
17
+ * Merkl tags Compound V3 reward campaigns with COMPOUND_V3_* opportunity types (e.g.
18
+ * COMPOUND_V3_BORROW_FROM_COLLATERAL) and identifies the comet via `explorerAddress`. Campaign
19
+ * identifiers are opaque hashes, passed through as `eligibilityId` so conditional campaigns —
20
+ * like borrow-from-collateral ones, whose reward is min(collateral * LTV, borrow amount) — can
21
+ * be gated and sized by a curated check in EligibilityMapping; unknown ids apply
22
+ * unconditionally, mirroring Aave V3.
23
+ */
24
+ export const getCompoundV3MerklOpportunities = async (): Promise<MerklOpportunity[]> => {
25
+ try {
26
+ return await fetchAllMerklOpportunities({
27
+ mainProtocolId: 'compound-v3',
28
+ status: OpportunityStatus.LIVE,
29
+ });
30
+ } catch (e) {
31
+ console.error('Failed to fetch Compound V3 Merkl campaigns', e);
32
+ return [];
33
+ }
34
+ };
35
+
36
+ const buildMerklIncentive = (opportunity: MerklOpportunity): IncentiveData => {
37
+ const token = opportunity.rewardsRecord?.breakdowns?.[0]?.token?.symbol || opportunity.tokens?.[0]?.symbol || '';
38
+ return {
39
+ apy: aprToApy(opportunity.apr),
40
+ token,
41
+ incentiveKind: IncentiveKind.Reward,
42
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
43
+ eligibilityId: opportunity.identifier as IncentiveEligibilityId,
44
+ };
45
+ };
46
+
47
+ /**
48
+ * Appends the comet's Merkl campaigns to its assets' incentive arrays (mutating them, like the
49
+ * staking incentives are attached). BORROW campaigns land on the base asset — the only borrowable
50
+ * one — while LEND campaigns land on the asset the campaign's first token resolves to.
51
+ */
52
+ export const attachCompoundV3MerklIncentives = (
53
+ baseAsset: CompoundV3AssetData,
54
+ collAssets: CompoundV3AssetData[],
55
+ baseMarketAddress: string,
56
+ chainId: NetworkNumber,
57
+ opportunities: MerklOpportunity[],
58
+ ): void => {
59
+ opportunities
60
+ .filter((o) => o.chainId === chainId
61
+ && o.status === OpportunityStatus.LIVE
62
+ && typeof o.type === 'string' && o.type.startsWith('COMPOUND_V3')
63
+ && o.explorerAddress && compareAddresses(o.explorerAddress, baseMarketAddress))
64
+ .forEach((o) => {
65
+ const incentive = buildMerklIncentive(o);
66
+ if (o.action === OpportunityAction.BORROW) {
67
+ baseAsset.borrowIncentives.push(incentive);
68
+ } else if (o.action === OpportunityAction.LEND) {
69
+ const campaignTokenAddress = o.tokens?.[0]?.address;
70
+ if (!campaignTokenAddress) return;
71
+ const campaignSymbol = wethToEth(getAssetInfoByAddress(campaignTokenAddress, chainId).symbol);
72
+ const target = [baseAsset, ...collAssets].find((asset) => asset.symbol === campaignSymbol);
73
+ target?.supplyIncentives.push(incentive);
74
+ }
75
+ });
76
+ };
@@ -66,6 +66,14 @@ import {
66
66
  } from '../services/priceService';
67
67
  import { getStakingApy, STAKING_ASSETS } from '../staking';
68
68
  import { getViemProvider } from '../services/viem';
69
+ import { attachFluidMerklIncentives, getFluidMerklCampaigns } from './merkl';
70
+
71
+ export {
72
+ FluidMerklOpportunityType,
73
+ buildFluidMerklRewardMap,
74
+ getFluidMerklCampaigns,
75
+ attachFluidMerklIncentives,
76
+ } from './merkl';
69
77
 
70
78
  export const EMPTY_USED_ASSET = {
71
79
  isSupplied: false,
@@ -1146,6 +1154,8 @@ export const EMPTY_FLUID_DATA = {
1146
1154
  minRatio: '0',
1147
1155
  netApy: '0',
1148
1156
  incentiveUsd: '0',
1157
+ merklSupplyIncentives: [],
1158
+ merklBorrowIncentives: [],
1149
1159
  totalInterestUsd: '0',
1150
1160
  isSubscribedToAutomation: false,
1151
1161
  automationResubscribeRequired: false,
@@ -1442,9 +1452,13 @@ const parseUserData = (userPositionData: FluidUserPositionStructOutputStruct, va
1442
1452
  export const _getFluidMarketData = async (provider: PublicClient, network: NetworkNumber, market: FluidMarketInfo) => {
1443
1453
  const view = FluidViewContractViem(provider, network);
1444
1454
 
1445
- const data = await view.read.getVaultData([market.marketAddress]);
1455
+ const [data, merklCampaigns] = await Promise.all([
1456
+ view.read.getVaultData([market.marketAddress]),
1457
+ getFluidMerklCampaigns(network),
1458
+ ]);
1446
1459
 
1447
- return parseMarketData(provider, data, network);
1460
+ const marketData = await parseMarketData(provider, data, network);
1461
+ return marketData ? attachFluidMerklIncentives(marketData, merklCampaigns) : marketData;
1448
1462
  };
1449
1463
 
1450
1464
  export const getFluidMarketData = async (
@@ -1500,11 +1514,15 @@ export const getFluidPosition = async (
1500
1514
 
1501
1515
  export const _getFluidPositionWithMarket = async (provider: PublicClient, network: NetworkNumber, vaultId: string) => {
1502
1516
  const view = FluidViewContractViem(provider, network);
1503
- const data = await view.read.getPositionByNftId([BigInt(vaultId)]);
1504
- const marketData = await parseMarketData(provider, data[1], network);
1505
- if (!marketData) {
1517
+ const [data, merklCampaigns] = await Promise.all([
1518
+ view.read.getPositionByNftId([BigInt(vaultId)]),
1519
+ getFluidMerklCampaigns(network),
1520
+ ]);
1521
+ const parsedMarketData = await parseMarketData(provider, data[1], network);
1522
+ if (!parsedMarketData) {
1506
1523
  return;
1507
1524
  }
1525
+ const marketData = attachFluidMerklIncentives(parsedMarketData, merklCampaigns);
1508
1526
  const userData = parseUserData(data[0], marketData);
1509
1527
 
1510
1528
  return {
@@ -1522,8 +1540,14 @@ export const getFluidPositionWithMarket = async (
1522
1540
  export const _getAllFluidMarketDataChunked = async (network: NetworkNumber, provider: PublicClient) => {
1523
1541
  const versions = getFluidVersionsDataForNetwork(network);
1524
1542
  const view = FluidViewContractViem(provider, network);
1525
- const data = await Promise.all(versions.map((version) => view.read.getVaultData([version.marketAddress])));
1526
- return Promise.all(data.map(async (item, i) => parseMarketData(provider, item, network)));
1543
+ const [data, merklCampaigns] = await Promise.all([
1544
+ Promise.all(versions.map((version) => view.read.getVaultData([version.marketAddress]))),
1545
+ getFluidMerklCampaigns(network),
1546
+ ]);
1547
+ return Promise.all(data.map(async (item) => {
1548
+ const marketData = await parseMarketData(provider, item, network);
1549
+ return marketData ? attachFluidMerklIncentives(marketData, merklCampaigns) : marketData;
1550
+ }));
1527
1551
  };
1528
1552
 
1529
1553
  export const getAllFluidMarketDataChunked = async (
@@ -1787,9 +1811,13 @@ export const _getUserPositionsPortfolio = async (provider: PublicClient, network
1787
1811
  if (!tokens.includes('ETH')) tokens.push('ETH');
1788
1812
  if (!tokens.includes('WBTC')) tokens.push('WBTC');
1789
1813
 
1790
- const tokenPrices = await getTokensPricesForPortfolio(tokens, provider, network);
1814
+ const [tokenPrices, merklCampaigns] = await Promise.all([
1815
+ getTokensPricesForPortfolio(tokens, provider, network),
1816
+ getFluidMerklCampaigns(network),
1817
+ ]);
1791
1818
 
1792
- const parsedMarketData = (await Promise.all(data[1].map(async (vaultData) => parseMarketData(provider, vaultData, network, tokenPrices))));
1819
+ const parsedMarketData = (await Promise.all(data[1].map(async (vaultData) => parseMarketData(provider, vaultData, network, tokenPrices))))
1820
+ .map(marketData => (marketData ? attachFluidMerklIncentives(marketData, merklCampaigns) : marketData));
1793
1821
 
1794
1822
  const userData = data[0].map((position, i) => (parsedMarketData[i] && { ...parseUserData(position, parsedMarketData[i]) }));
1795
1823
 
@@ -0,0 +1,102 @@
1
+ import memoize from 'memoizee';
2
+ import { aprToApy } from '../moneymarket';
3
+ import { fetchAllMerklOpportunities } from '../services/merkl';
4
+ import {
5
+ FluidMarketData,
6
+ FluidMerklRewardMap,
7
+ IncentiveData,
8
+ IncentiveEligibilityId,
9
+ IncentiveKind,
10
+ IncentiveSource,
11
+ MerklOpportunity,
12
+ NetworkNumber,
13
+ OpportunityStatus,
14
+ } from '../types';
15
+
16
+ /**
17
+ * Merkl tags Fluid vault-scoped reward campaigns via the opportunity `type` field:
18
+ * - FLUIDVAULT_COLLATERAL → reward for supplying collateral to the vault
19
+ * - FLUIDVAULT_BORROW → reward for borrowing from the vault
20
+ * (ERC20LOGPROCESSOR campaigns target fToken earn positions rather than vaults, so they don't
21
+ * belong on vault market data.)
22
+ *
23
+ * A campaign identifies its vault via `identifier` — the vault address. Conditional campaigns
24
+ * append a marker to it (e.g. `0x5668…eeaBORROW_BL`, excluding holders who borrow the reward
25
+ * asset elsewhere); those are still attached, with the full identifier passed through as
26
+ * `eligibilityId` so a curated check in EligibilityMapping can gate them in net APY — unknown
27
+ * ids apply unconditionally, mirroring Aave V3. Whitelist-gated campaigns only accrue to
28
+ * whitelisted addresses, so they are skipped rather than advertised to every user.
29
+ */
30
+ export enum FluidMerklOpportunityType {
31
+ Collateral = 'FLUIDVAULT_COLLATERAL',
32
+ Borrow = 'FLUIDVAULT_BORROW',
33
+ }
34
+
35
+ // '0x' + 20-byte vault address; conditional campaigns append a marker after it
36
+ const VAULT_ADDRESS_LENGTH = 42;
37
+
38
+ const buildMerklIncentive = (opportunity: MerklOpportunity): IncentiveData => {
39
+ const token = opportunity.rewardsRecord?.breakdowns?.[0]?.token?.symbol || opportunity.tokens?.[0]?.symbol || '';
40
+ return {
41
+ apy: aprToApy(opportunity.apr),
42
+ token,
43
+ incentiveKind: IncentiveKind.Reward,
44
+ source: IncentiveSource.Merkl,
45
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
46
+ eligibilityId: opportunity.identifier as IncentiveEligibilityId,
47
+ };
48
+ };
49
+
50
+ export const buildFluidMerklRewardMap = (opportunities: MerklOpportunity[], chainId: NetworkNumber): FluidMerklRewardMap => {
51
+ const result: FluidMerklRewardMap = {};
52
+
53
+ opportunities
54
+ .filter((o) => o.chainId === chainId)
55
+ .filter((o) => o.status === OpportunityStatus.LIVE)
56
+ .filter((o) => Object.values(FluidMerklOpportunityType).includes(o.type as FluidMerklOpportunityType))
57
+ .filter((o) => !o.identifier?.includes('WHITELIST'))
58
+ .forEach((o) => {
59
+ const vaultAddress = o.identifier?.slice(0, VAULT_ADDRESS_LENGTH).toLowerCase();
60
+ if (!vaultAddress || vaultAddress.length !== VAULT_ADDRESS_LENGTH) return;
61
+ if (!result[vaultAddress]) result[vaultAddress] = { supply: [], borrow: [] };
62
+ result[vaultAddress][o.type === FluidMerklOpportunityType.Borrow ? 'borrow' : 'supply'].push(buildMerklIncentive(o));
63
+ });
64
+
65
+ return result;
66
+ };
67
+
68
+ /**
69
+ * Fetches live vault-scoped Fluid campaigns for the chain, keyed by vault address. Never throws —
70
+ * on any failure it returns an empty map, so Merkl being down can't break market data.
71
+ */
72
+ export const getFluidMerklCampaigns = memoize(async (chainId: NetworkNumber): Promise<FluidMerklRewardMap> => {
73
+ try {
74
+ const opportunities = await fetchAllMerklOpportunities({
75
+ mainProtocolId: 'fluid',
76
+ type: Object.values(FluidMerklOpportunityType).join(','),
77
+ status: OpportunityStatus.LIVE,
78
+ });
79
+ return buildFluidMerklRewardMap(opportunities, chainId);
80
+ } catch (e) {
81
+ console.error('Failed to fetch Fluid Merkl campaigns', e);
82
+ return {};
83
+ }
84
+ }, { promise: true, maxAge: 60 * 1000 });
85
+
86
+ /**
87
+ * Appends the vault's Merkl campaigns to its assets' incentive arrays — supply rewards on every
88
+ * suppliable asset and borrow rewards on every borrowable one. Smart collateral/debt vaults hold
89
+ * the position across both pair tokens, so the pro-rata reward APY applies to each side's value.
90
+ */
91
+ export const attachFluidMerklIncentives = (marketData: FluidMarketData, campaigns: FluidMerklRewardMap): FluidMarketData => {
92
+ const vaultCampaigns = campaigns[marketData.marketData.marketAddress?.toLowerCase()];
93
+ if (!vaultCampaigns || (!vaultCampaigns.supply.length && !vaultCampaigns.borrow.length)) return marketData;
94
+
95
+ const assetsData = Object.fromEntries(Object.entries(marketData.assetsData).map(([symbol, asset]) => [symbol, {
96
+ ...asset,
97
+ supplyIncentives: asset.canBeSupplied ? [...asset.supplyIncentives, ...vaultCampaigns.supply] : asset.supplyIncentives,
98
+ borrowIncentives: asset.canBeBorrowed ? [...asset.borrowIncentives, ...vaultCampaigns.borrow] : asset.borrowIncentives,
99
+ }]));
100
+
101
+ return { ...marketData, assetsData };
102
+ };
@@ -5,16 +5,56 @@ import {
5
5
  FluidAssetsData, FluidDexBorrowDataStructOutput, FluidDexSupplyDataStructOutput, FluidUsedAsset,
6
6
  FluidUsedAssets,
7
7
  FluidVaultType,
8
+ IncentiveData,
9
+ IncentiveSource,
8
10
  InnerFluidMarketData,
9
11
  } from '../../types';
10
12
  import {
11
13
  calcLeverageLiqPrice, getAssetsTotal, getExposure, isLeveragedPos,
12
14
  } from '../../moneymarket';
13
- import { calculateNetApy } from '../../staking';
14
- import { LeverageType, MMAssetsData } from '../../types/common';
15
+ import { calculateInterestEarned, calculateNetApy, EligibilityMapping } from '../../staking';
16
+ import { IncentiveSide, LeverageType, MMAssetsData } from '../../types/common';
15
17
  import { getEthAmountForDecimals } from '../../services/utils';
16
18
 
17
- const calculateNetApyDex = ({ marketData, suppliedUsd, borrowedUsd }: { marketData: InnerFluidMarketData, suppliedUsd: string, borrowedUsd: string }) => {
19
+ export const getUniqueFluidMerklIncentives = (assetsData: FluidAssetsData, side: IncentiveSide): IncentiveData[] => {
20
+ const field = side === IncentiveSide.Supply ? 'supplyIncentives' : 'borrowIncentives';
21
+ const incentives = Object.values(assetsData)
22
+ .flatMap(asset => asset[field])
23
+ .filter(incentive => incentive.source === IncentiveSource.Merkl);
24
+
25
+ return [...new Map(incentives.map(incentive => [
26
+ [incentive.eligibilityId, incentive.token, incentive.apy, incentive.description].join('|'),
27
+ incentive,
28
+ ])).values()];
29
+ };
30
+
31
+ const getMerklIncentiveInterest = (
32
+ incentives: IncentiveData[],
33
+ principal: string,
34
+ usedAssets: FluidUsedAssets,
35
+ ) => incentives.reduce((total, { apy, eligibilityId }) => {
36
+ const eligibilityCheck = eligibilityId ? EligibilityMapping[eligibilityId] : null;
37
+ const { isEligible, eligibleUSDAmount } = eligibilityCheck
38
+ ? eligibilityCheck(usedAssets, undefined)
39
+ : { isEligible: true, eligibleUSDAmount: principal };
40
+ const incentiveInterest = isEligible ? calculateInterestEarned(eligibleUSDAmount, apy, 'year', true) : 0;
41
+
42
+ return new Dec(total).add(incentiveInterest).toString();
43
+ }, '0');
44
+
45
+ const calculateNetApyDex = ({
46
+ marketData,
47
+ assetsData,
48
+ usedAssets,
49
+ suppliedUsd,
50
+ borrowedUsd,
51
+ }: {
52
+ marketData: InnerFluidMarketData,
53
+ assetsData: FluidAssetsData,
54
+ usedAssets: FluidUsedAssets,
55
+ suppliedUsd: string,
56
+ borrowedUsd: string,
57
+ }) => {
18
58
  const {
19
59
  borrowRate,
20
60
  supplyRate,
@@ -29,7 +69,21 @@ const calculateNetApyDex = ({ marketData, suppliedUsd, borrowedUsd }: { marketDa
29
69
 
30
70
  const borrowIncentive = new Dec(incentiveBorrowRate || '0').mul(borrowedUsd).div(100).toString();
31
71
  const supplyIncentive = new Dec(incentiveSupplyRate || '0').mul(suppliedUsd).div(100).toString();
32
- const incentiveUsd = new Dec(supplyIncentive).minus(borrowIncentive).toString();
72
+ const merklSupplyIncentive = getMerklIncentiveInterest(
73
+ getUniqueFluidMerklIncentives(assetsData, IncentiveSide.Supply),
74
+ suppliedUsd,
75
+ usedAssets,
76
+ );
77
+ const merklBorrowIncentive = getMerklIncentiveInterest(
78
+ getUniqueFluidMerklIncentives(assetsData, IncentiveSide.Borrow),
79
+ borrowedUsd,
80
+ usedAssets,
81
+ );
82
+ const incentiveUsd = new Dec(supplyIncentive)
83
+ .minus(borrowIncentive)
84
+ .add(merklSupplyIncentive)
85
+ .add(merklBorrowIncentive)
86
+ .toString();
33
87
 
34
88
  const borrowInterest = new Dec(totalBorrowRate).mul(borrowedUsd).div(100).toString();
35
89
  const supplyInterest = new Dec(totalSupplyRate).mul(suppliedUsd).div(100).toString();
@@ -66,7 +120,15 @@ borrowShares?: string,
66
120
  : new Dec(marketData.debtSharePrice!).mul(borrowShares!).toString();
67
121
 
68
122
  const isDex = [FluidVaultType.T2, FluidVaultType.T3, FluidVaultType.T4].includes(marketData.vaultType);
69
- const { netApy, incentiveUsd, totalInterestUsd } = isDex ? calculateNetApyDex({ marketData, suppliedUsd: payload.suppliedUsd, borrowedUsd: payload.borrowedUsd }) : calculateNetApy({ usedAssets, assetsData: assetsData as unknown as MMAssetsData });
123
+ payload.merklSupplyIncentives = getUniqueFluidMerklIncentives(assetsData, IncentiveSide.Supply);
124
+ payload.merklBorrowIncentives = getUniqueFluidMerklIncentives(assetsData, IncentiveSide.Borrow);
125
+ const { netApy, incentiveUsd, totalInterestUsd } = isDex ? calculateNetApyDex({
126
+ marketData,
127
+ assetsData,
128
+ usedAssets,
129
+ suppliedUsd: payload.suppliedUsd,
130
+ borrowedUsd: payload.borrowedUsd,
131
+ }) : calculateNetApy({ usedAssets, assetsData: assetsData as unknown as MMAssetsData });
70
132
  payload.netApy = netApy;
71
133
  payload.incentiveUsd = incentiveUsd;
72
134
  payload.totalInterestUsd = totalInterestUsd;
@@ -337,4 +399,4 @@ export const mergeUsedAssets = (existing: Partial<FluidUsedAsset> = {}, addition
337
399
  ...EMPTY_USED_ASSET,
338
400
  ...existing,
339
401
  ...additional,
340
- });
402
+ });
@@ -52,16 +52,19 @@ export const getLiquityV2AggregatedPositionData = ({
52
52
  assetsData,
53
53
  minCollRatio,
54
54
  interestRate,
55
+ liqRatio,
55
56
  }: {
56
57
  usedAssets: LiquityV2UsedAssets
57
58
  assetsData: LiquityV2AssetsData
58
59
  minCollRatio: string
59
60
  interestRate: string
61
+ liqRatio?: string // liquidation threshold (MCR), when different from minCollRatio (MCR + BCR for troves in a batch)
60
62
  }): LiquityV2AggregatedTroveData => {
61
63
  const payload = {} as LiquityV2AggregatedTroveData;
62
64
  payload.suppliedUsd = getAssetsTotal(usedAssets, (usedAsset: LiquityV2UsedAsset) => usedAsset, ({ suppliedUsd }: { suppliedUsd: string }) => suppliedUsd);
63
65
  payload.borrowedUsd = getAssetsTotal(usedAssets, (usedAsset: LiquityV2UsedAsset) => usedAsset, ({ borrowedUsd }: { borrowedUsd: string }) => borrowedUsd);
64
66
  payload.borrowLimitUsd = new Dec(payload.suppliedUsd).div(minCollRatio).mul(100).toString();
67
+ payload.liquidationLimitUsd = new Dec(payload.suppliedUsd).div(liqRatio ?? minCollRatio).mul(100).toString();
65
68
  const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
66
69
  payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
67
70
  payload.ratio = (+payload.suppliedUsd && +payload.borrowedUsd) ? new Dec(payload.borrowLimitUsd).div(payload.borrowedUsd).mul(100).toString() : '0';
@@ -77,7 +80,7 @@ export const getLiquityV2AggregatedPositionData = ({
77
80
  payload.liquidationPrice = '';
78
81
  if (leveragedType !== '') {
79
82
  const assetPrice = assetsData[leveragedAsset].price;
80
- payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.borrowLimitUsd);
83
+ payload.liquidationPrice = calcLeverageLiqPrice(leveragedType, assetPrice, payload.borrowedUsd, payload.liquidationLimitUsd);
81
84
  }
82
85
  payload.exposure = getExposure(payload.borrowedUsd, payload.suppliedUsd);
83
86
 
@@ -0,0 +1,82 @@
1
+ import Dec from 'decimal.js';
2
+
3
+ /**
4
+ * Safety margin every Midnight position is held at. On Midnight the lltv is *both* the borrow cap and the
5
+ * liquidation threshold (`liquidationLimitUsd === borrowLimitUsd` in the aggregate), so a position borrowed
6
+ * to its full limit opens at a health ratio of exactly 1 — immediately liquidatable. This is what holds it
7
+ * off that line, and what absorbs swap price impact on a boost.
8
+ */
9
+ export const MIDNIGHT_MIN_HEALTH_RATIO = 1.025;
10
+
11
+ export interface MidnightBorrowHeadroomParams {
12
+ borrowLimitUsd: Dec.Value;
13
+ borrowedUsd: Dec.Value;
14
+ /** Principal a unit of borrow power is worth (loan-per-unit price, ≤ 1), off a book rate. */
15
+ principalPerUnit?: Dec.Value;
16
+ /** Depth the book can fill, in loan tokens, from the same quote. Omitted leaves the answer uncapped. */
17
+ availableAssets?: Dec.Value;
18
+ loanTokenPrice?: Dec.Value;
19
+ /** Loan token decimals. Omitted skips the quantisation, which only a caller ignoring `leftToBorrow` wants. */
20
+ loanTokenDecimals?: number;
21
+ isMatured?: boolean;
22
+ minHealthRatio?: Dec.Value;
23
+ }
24
+
25
+ export interface MidnightBorrowHeadroom {
26
+ /** Face-value headroom, before the order-book discount. What a *boost* solve scales itself. */
27
+ headroomUsd: string;
28
+ /** The borrowable amount in loan tokens — the Borrow action's Max, quantised exactly as it is typed in. */
29
+ leftToBorrow: string;
30
+ /** `leftToBorrow · price`. Derived FROM the token amount, never computed alongside it — see below. */
31
+ leftToBorrowUsd: string;
32
+ borrowPowerUsed: string;
33
+ }
34
+
35
+ /**
36
+ * The one answer to "how much more can this position borrow". Every surface that sizes a Midnight borrow
37
+ * derives from here — the max-borrow getter, the position overview's headroom rows, and the max-boost
38
+ * solve, which scales `headroomUsd` by its own leverage factors — so a max and the figure shown next to it
39
+ * cannot drift into two different formulas. They did: the overview used to price
40
+ * the whole headroom off the top-of-book offer (often dust) with no rate pad and no depth cap, while the
41
+ * max walked the book for its real size, which is what put the two 1–2% apart.
42
+ *
43
+ * Three corrections separate this from a plain `limit − debt`, and dropping any one overstates the answer:
44
+ * `minHealthRatio` reserves the margin, `principalPerUnit` turns face-value headroom into the principal a
45
+ * borrow actually receives (a correction that grows with the term, past 7% on a one-year market), and
46
+ * `availableAssets` caps it at what the book can currently fill.
47
+ *
48
+ * `leftToBorrowUsd` is deliberately `leftToBorrow · price` rather than the USD figure the token amount was
49
+ * derived from: the two differ by the round-down to token decimals, and a UI showing one next to an input
50
+ * holding the other would be reporting a difference the user cannot spend. Everything quantises once, here.
51
+ */
52
+ export const getMorphoMidnightBorrowHeadroom = ({
53
+ borrowLimitUsd,
54
+ borrowedUsd,
55
+ principalPerUnit = 1,
56
+ availableAssets,
57
+ loanTokenPrice = 0,
58
+ loanTokenDecimals,
59
+ isMatured = false,
60
+ minHealthRatio = MIDNIGHT_MIN_HEALTH_RATIO,
61
+ }: MidnightBorrowHeadroomParams): MidnightBorrowHeadroom => {
62
+ const usableLimitUsd = new Dec(borrowLimitUsd).div(minHealthRatio);
63
+ const headroomUsd = isMatured ? new Dec(0) : Dec.max(0, usableLimitUsd.sub(borrowedUsd));
64
+
65
+ const price = new Dec(loanTokenPrice);
66
+ // Capped in loan tokens rather than in USD: `availableAssets` is quoted in tokens, and converting it to
67
+ // USD only to divide the result back out again would re-round the one number that has to land exactly.
68
+ const payout = price.lte(0) ? new Dec(0) : headroomUsd.mul(principalPerUnit).div(price);
69
+ const capped = availableAssets === undefined ? payout : Dec.min(payout, availableAssets);
70
+ // Round down: rounding the last decimal up would eat into the margin we just reserved.
71
+ const leftToBorrow = loanTokenDecimals === undefined ? capped : capped.toDP(loanTokenDecimals, Dec.ROUND_DOWN);
72
+
73
+ return {
74
+ headroomUsd: headroomUsd.toString(),
75
+ leftToBorrow: leftToBorrow.toString(),
76
+ leftToBorrowUsd: leftToBorrow.mul(price).toString(),
77
+ // Measured against the margined limit rather than the raw one, so it reads 100% at max borrow instead
78
+ // of 97.56%, and can exceed 100% inside the reserved band. Deliberately left uncapped by book depth:
79
+ // how much a position has borrowed is a property of the position, not of what the book can fill today.
80
+ borrowPowerUsed: usableLimitUsd.lte(0) ? '0' : new Dec(borrowedUsd).div(usableLimitUsd).mul(100).toString(),
81
+ };
82
+ };
@@ -35,6 +35,11 @@ export {
35
35
  midnightTimeToMaturityDays,
36
36
  MIDNIGHT_DEFAULT_RATE_SLIPPAGE,
37
37
  } from './rate';
38
+ export {
39
+ getMorphoMidnightBorrowHeadroom,
40
+ MIDNIGHT_MIN_HEALTH_RATIO,
41
+ } from './headroom';
42
+ export type { MidnightBorrowHeadroom, MidnightBorrowHeadroomParams } from './headroom';
38
43
  export {
39
44
  tenorBookKeyFor,
40
45
  tenorBookRateToApyPercent,
@@ -77,9 +82,12 @@ export const getMorphoMidnightAggregatedPositionData = ({
77
82
  // Same subtraction every other money market uses, but it does NOT mean the same thing here. Elsewhere
78
83
  // `borrowedUsd` is debt at present value, so the remainder is what a borrow would pay out. Midnight
79
84
  // records debt at its face value at maturity, so this is face-value headroom: borrowing it would add
80
- // more debt than the number says, by the market's discount. Anything surfacing this as "what you can
81
- // borrow" has to scale it by the loan-per-unit price first (`midnightPriceFromApy` off a book rate) —
82
- // a correction that grows with the term, past 7% on a one-year market.
85
+ // more debt than the number says, by the market's discount. It also reserves no safety margin, and this
86
+ // aggregate is synchronous so it has no book rate to discount by.
87
+ //
88
+ // DO NOT SURFACE THIS AS "what you can borrow" — use `getMorphoMidnightBorrowHeadroom` instead, which
89
+ // applies both corrections (the margin, and the loan-per-unit price off a book rate) and caps on the
90
+ // depth the book can fill. The discount alone grows past 7% on a one-year market.
83
91
  const leftToBorrowUsd = new Dec(payload.borrowLimitUsd).sub(payload.borrowedUsd);
84
92
  payload.leftToBorrowUsd = leftToBorrowUsd.lte('0') ? '0' : leftToBorrowUsd.toString();
85
93
 
@@ -227,10 +235,6 @@ export const midnightSlippageParam = (slippagePercent: Dec.Value): string => Dec
227
235
  MIDNIGHT_SLIPPAGE_MAX,
228
236
  ).toDP(1, Dec.ROUND_DOWN).toString();
229
237
 
230
- export const morphoMidnightMarketReportsBorrowInfo = (market: Pick<MorphoMidnightMarketData, 'curator'> | string): boolean => (
231
- !isTenorMidnightMarket(market)
232
- );
233
-
234
238
  /**
235
239
  * Current borrower rate + debt breakdown from the Midnight positions API. Reconstructing this from the raw
236
240
  * `/transactions` fill history only sums `borrow` fills, so it overstates debt for any position with an
@@ -425,7 +425,7 @@ export const _getLiquityV2TroveData = async (
425
425
  const lastInterestRateAdjTime = data.lastInterestRateAdjTime.toString();
426
426
 
427
427
  const hasInterestBatchManager = !compareAddresses(interestBatchManager, ZERO_ADDRESS);
428
- const liqRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
428
+ const borrowLimitRatio = hasInterestBatchManager ? new Dec(minCollRatio).add(batchCollRatio).toString() : minCollRatio;
429
429
 
430
430
  const payload: LiquityV2TroveData = {
431
431
  usedAssets,
@@ -434,10 +434,11 @@ export const _getLiquityV2TroveData = async (
434
434
  interestBatchManager,
435
435
  debtInFront,
436
436
  lastInterestRateAdjTime,
437
- liqRatio,
437
+ liqRatio: minCollRatio,
438
+ borrowLimitRatio,
438
439
  troveStatus: LIQUITY_V2_TROVE_STATUS_ENUM[parseInt(data.status.toString(), 10)],
439
440
  ...getLiquityV2AggregatedPositionData({
440
- usedAssets, assetsData, minCollRatio: liqRatio, interestRate,
441
+ usedAssets, assetsData, minCollRatio: borrowLimitRatio, interestRate, liqRatio: minCollRatio,
441
442
  }),
442
443
  collRatio,
443
444
  };
@@ -26,6 +26,8 @@ export const STABLE_ASSETS = [
26
26
  'USDtb', 'eUSDe', 'PT USDe July', 'PT eUSDe Aug', 'PT sUSDe Sep', 'PT USDe Sep', 'PT sUSDe Nov', 'PT USDe Nov', 'PT sUSDe Jan', 'PT USDe Jan',
27
27
  'PT sUSDe Feb', 'PT USDe Feb', 'PT sUSDe Apr', 'PT USDe Apr', 'PT sUSDe May', 'PT USDe May', 'PT srUSDe Apr', 'frxUSD', 'PT sUSDe June',
28
28
  'PT USDe June', 'PT srUSDe Jun', 'PT srUSDe Oct', 'PT USDG May', 'PT sUSDS Nov', 'PT sUSDe Oct', 'PT USDG Sep',
29
+ 'USDG', 'mUSD', 'PYUSD', 'USDbC', 'MAI', 'sGHO', 'USD3', 'stUSDS', 'PRIME',
30
+ 'crvUSD', 'syrupUSDC', 'syrupUSDT', 'syrupUSDG', 'PT syrupUSDC Aug',
29
31
  ];
30
32
 
31
33
  export const isLeveragedPos = (usedAssets: MMUsedAssets, dustLimit = 5) => {
@@ -19,6 +19,15 @@ import {
19
19
  import { getChainlinkAssetAddress } from '../services/priceService';
20
20
  import { getViemProvider, setViemBlockNumber } from '../services/viem';
21
21
 
22
+ import { addMorphoBlueMerklOpportunitiesToMarketInfo, getMorphoBlueMerklOpportunities } from './merkl';
23
+
24
+ export {
25
+ MorphoBlueMerklOpportunityType,
26
+ addMorphoBlueMerklOpportunitiesToMarketInfo,
27
+ getMorphoBlueMerklOpportunities,
28
+ addMorphoBlueMerklRewardsToMarketInfo,
29
+ } from './merkl';
30
+
22
31
  const HARDCODED_USD_STABLE_PRICE = '100000000'; // $1 with 8 decimals
23
32
 
24
33
  const getMorphoRewardIncentives = (apy: string) => [{
@@ -151,15 +160,21 @@ async function getMorphoBlueMarketDataInternal(
151
160
  }
152
161
 
153
162
  export async function _getMorphoBlueMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo> {
154
- const marketInfo = await getMorphoBlueMarketDataInternal(provider, network, selectedMarket);
155
-
156
- try {
157
- const rewards = await getRewardsForMarket(selectedMarket.marketId, network);
158
- return addMorphoBlueRewardsToMarketInfo(marketInfo, rewards);
159
- } catch (error) {
160
- console.error(error);
161
- return addMorphoBlueRewardsToMarketInfo(marketInfo, { supplyApy: '0', borrowApy: '0' });
162
- }
163
+ const [marketInfo, rewards, merklOpportunities] = await Promise.all([
164
+ getMorphoBlueMarketDataInternal(provider, network, selectedMarket),
165
+ getRewardsForMarket(selectedMarket.marketId, network).catch((error) => {
166
+ console.error(error);
167
+ return { supplyApy: '0', borrowApy: '0' };
168
+ }),
169
+ getMorphoBlueMerklOpportunities(),
170
+ ]);
171
+
172
+ return addMorphoBlueMerklOpportunitiesToMarketInfo(
173
+ addMorphoBlueRewardsToMarketInfo(marketInfo, rewards),
174
+ selectedMarket,
175
+ network,
176
+ merklOpportunities,
177
+ );
163
178
  }
164
179
 
165
180
  export function _getMorphoBluePortfolioMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo> {