@defisaver/positions-sdk 2.1.127-midnight-14-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 (100) 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 -0
  20. package/cjs/helpers/morphoMidnightHelpers/index.js +10 -4
  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/portfolio/index.js +5 -5
  28. package/cjs/services/merkl.d.ts +6 -0
  29. package/cjs/services/merkl.js +39 -0
  30. package/cjs/staking/eligibility.d.ts +4 -0
  31. package/cjs/staking/eligibility.js +11 -1
  32. package/cjs/types/claiming.d.ts +12 -1
  33. package/cjs/types/claiming.js +2 -0
  34. package/cjs/types/common.d.ts +6 -1
  35. package/cjs/types/common.js +6 -1
  36. package/cjs/types/fluid.d.ts +2 -0
  37. package/cjs/types/liquityV2.d.ts +3 -0
  38. package/cjs/types/merkl.d.ts +8 -0
  39. package/esm/aaveV3/merkl.js +11 -10
  40. package/esm/aaveV4/merkl.js +5 -6
  41. package/esm/claiming/aaveV3.d.ts +2 -1
  42. package/esm/claiming/aaveV3.js +12 -4
  43. package/esm/compoundV3/index.d.ts +1 -0
  44. package/esm/compoundV3/index.js +5 -1
  45. package/esm/compoundV3/merkl.d.ts +16 -0
  46. package/esm/compoundV3/merkl.js +72 -0
  47. package/esm/fluid/index.d.ts +9 -0
  48. package/esm/fluid/index.js +31 -9
  49. package/esm/fluid/merkl.d.ts +32 -0
  50. package/esm/fluid/merkl.js +95 -0
  51. package/esm/helpers/fluidHelpers/index.d.ts +3 -1
  52. package/esm/helpers/fluidHelpers/index.js +38 -6
  53. package/esm/helpers/liquityV2Helpers/index.d.ts +2 -1
  54. package/esm/helpers/liquityV2Helpers/index.js +3 -2
  55. package/esm/helpers/morphoMidnightHelpers/headroom.d.ts +48 -0
  56. package/esm/helpers/morphoMidnightHelpers/headroom.js +45 -0
  57. package/esm/helpers/morphoMidnightHelpers/index.d.ts +2 -0
  58. package/esm/helpers/morphoMidnightHelpers/index.js +7 -3
  59. package/esm/liquityV2/index.js +3 -4
  60. package/esm/moneymarket/moneymarketCommonService.js +2 -0
  61. package/esm/morphoBlue/index.d.ts +1 -0
  62. package/esm/morphoBlue/index.js +11 -9
  63. package/esm/morphoBlue/merkl.d.ts +35 -0
  64. package/esm/morphoBlue/merkl.js +96 -0
  65. package/esm/portfolio/index.js +6 -6
  66. package/esm/services/merkl.d.ts +6 -0
  67. package/esm/services/merkl.js +35 -0
  68. package/esm/staking/eligibility.d.ts +4 -0
  69. package/esm/staking/eligibility.js +9 -0
  70. package/esm/types/claiming.d.ts +12 -1
  71. package/esm/types/claiming.js +2 -0
  72. package/esm/types/common.d.ts +6 -1
  73. package/esm/types/common.js +5 -0
  74. package/esm/types/fluid.d.ts +2 -0
  75. package/esm/types/liquityV2.d.ts +3 -0
  76. package/esm/types/merkl.d.ts +8 -0
  77. package/package.json +1 -1
  78. package/src/aaveV3/merkl.ts +7 -7
  79. package/src/aaveV4/merkl.ts +5 -5
  80. package/src/claiming/aaveV3.ts +19 -7
  81. package/src/compoundV3/index.ts +6 -1
  82. package/src/compoundV3/merkl.ts +76 -0
  83. package/src/fluid/index.ts +37 -9
  84. package/src/fluid/merkl.ts +102 -0
  85. package/src/helpers/fluidHelpers/index.ts +68 -6
  86. package/src/helpers/liquityV2Helpers/index.ts +4 -1
  87. package/src/helpers/morphoMidnightHelpers/headroom.ts +82 -0
  88. package/src/helpers/morphoMidnightHelpers/index.ts +11 -3
  89. package/src/liquityV2/index.ts +4 -3
  90. package/src/moneymarket/moneymarketCommonService.ts +2 -0
  91. package/src/morphoBlue/index.ts +24 -9
  92. package/src/morphoBlue/merkl.ts +121 -0
  93. package/src/portfolio/index.ts +6 -6
  94. package/src/services/merkl.ts +31 -0
  95. package/src/staking/eligibility.ts +10 -0
  96. package/src/types/claiming.ts +13 -0
  97. package/src/types/common.ts +6 -0
  98. package/src/types/fluid.ts +3 -1
  99. package/src/types/liquityV2.ts +3 -0
  100. package/src/types/merkl.ts +6 -0
@@ -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
 
@@ -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> {
@@ -0,0 +1,121 @@
1
+ import { aprToApy } from '../moneymarket';
2
+ import { fetchAllMerklOpportunities } from '../services/merkl';
3
+ import {
4
+ IncentiveData,
5
+ IncentiveKind,
6
+ MerklOpportunity,
7
+ MorphoBlueMarketData,
8
+ MorphoBlueMarketInfo,
9
+ NetworkNumber,
10
+ OpportunityStatus,
11
+ } from '../types';
12
+
13
+ /**
14
+ * Merkl tags Morpho Blue market-level reward campaigns via the opportunity `type` field:
15
+ * - MORPHOSUPPLY → reward for supplying the market's loan asset
16
+ * - MORPHOCOLLATERAL → reward for depositing the market's collateral asset
17
+ * - MORPHOBORROW → reward for borrowing the market's loan asset
18
+ * (MORPHOVAULT/ERC20LOGPROCESSOR are MetaMorpho vault campaigns and MORPHOSUPPLY_SINGLETOKEN is
19
+ * token-wide rather than market-scoped, so none of them belong on per-market data.)
20
+ *
21
+ * A campaign identifies its market via `identifier` — the first 20 bytes of the 32-byte Morpho
22
+ * market id, formatted as a checksummed address. Whitelist-gated campaigns append a marker to that
23
+ * identifier (e.g. `0x54cf…c46WHITELIST_CAMPAIGN`); their rewards only accrue to whitelisted
24
+ * addresses, so they are skipped rather than advertised to every user.
25
+ */
26
+ export enum MorphoBlueMerklOpportunityType {
27
+ Supply = 'MORPHOSUPPLY',
28
+ Collateral = 'MORPHOCOLLATERAL',
29
+ Borrow = 'MORPHOBORROW',
30
+ }
31
+
32
+ const MERKL_DESCRIPTION_MARKER = 'through Merkl';
33
+
34
+ // '0x' + first 20 bytes of the market id
35
+ const MARKET_ID_PREFIX_LENGTH = 42;
36
+
37
+ const buildMerklIncentive = (opportunity: MerklOpportunity): IncentiveData => {
38
+ const token = opportunity.rewardsRecord?.breakdowns?.[0]?.token?.symbol || opportunity.tokens?.[0]?.symbol || '';
39
+ return {
40
+ apy: aprToApy(opportunity.apr),
41
+ token,
42
+ incentiveKind: IncentiveKind.Reward,
43
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
44
+ };
45
+ };
46
+
47
+ const withoutMerklIncentives = (incentives: IncentiveData[] = []) => incentives
48
+ .filter(({ description }) => !description?.includes(MERKL_DESCRIPTION_MARKER));
49
+
50
+ /**
51
+ * Appends the given live Merkl campaigns for the market to its `assetsData` incentive arrays
52
+ * (collateral supply / loan supply / loan borrow). Existing Merkl incentives are replaced rather
53
+ * than duplicated, so re-applying on refreshed data is safe.
54
+ */
55
+ export const addMorphoBlueMerklOpportunitiesToMarketInfo = (
56
+ marketInfo: MorphoBlueMarketInfo,
57
+ selectedMarket: MorphoBlueMarketData,
58
+ chainId: NetworkNumber,
59
+ opportunities: MerklOpportunity[],
60
+ ): MorphoBlueMarketInfo => {
61
+ const marketIdPrefix = (selectedMarket.marketId || '').slice(0, MARKET_ID_PREFIX_LENGTH).toLowerCase();
62
+ const collateralAsset = marketInfo.assetsData[marketInfo.collateralToken];
63
+ const loanAsset = marketInfo.assetsData[marketInfo.loanToken];
64
+ if (marketIdPrefix.length !== MARKET_ID_PREFIX_LENGTH || !collateralAsset || !loanAsset) return marketInfo;
65
+
66
+ const relevant = opportunities.filter((o) => o.chainId === chainId
67
+ && o.status === OpportunityStatus.LIVE
68
+ && Object.values(MorphoBlueMerklOpportunityType).includes(o.type as MorphoBlueMerklOpportunityType)
69
+ // a suffixed identifier marks a whitelist-gated campaign — skip those
70
+ && o.identifier?.length === MARKET_ID_PREFIX_LENGTH
71
+ && o.identifier.toLowerCase() === marketIdPrefix);
72
+ if (!relevant.length) return marketInfo;
73
+
74
+ const incentivesByType = (type: MorphoBlueMerklOpportunityType) => relevant.filter((o) => o.type === type).map(buildMerklIncentive);
75
+ const collateralSupply = incentivesByType(MorphoBlueMerklOpportunityType.Collateral);
76
+ const loanSupply = incentivesByType(MorphoBlueMerklOpportunityType.Supply);
77
+ const loanBorrow = incentivesByType(MorphoBlueMerklOpportunityType.Borrow);
78
+
79
+ return {
80
+ ...marketInfo,
81
+ assetsData: {
82
+ ...marketInfo.assetsData,
83
+ [marketInfo.collateralToken]: {
84
+ ...collateralAsset,
85
+ supplyIncentives: [...withoutMerklIncentives(collateralAsset.supplyIncentives), ...collateralSupply],
86
+ },
87
+ [marketInfo.loanToken]: {
88
+ ...loanAsset,
89
+ supplyIncentives: [...withoutMerklIncentives(loanAsset.supplyIncentives), ...loanSupply],
90
+ borrowIncentives: [...withoutMerklIncentives(loanAsset.borrowIncentives), ...loanBorrow],
91
+ },
92
+ },
93
+ };
94
+ };
95
+
96
+ /**
97
+ * Fetches live market-scoped Morpho Blue campaigns for all chains. Never throws — on any failure
98
+ * it returns an empty list, so Merkl being down can't break market data.
99
+ */
100
+ export const getMorphoBlueMerklOpportunities = async (): Promise<MerklOpportunity[]> => {
101
+ try {
102
+ return await fetchAllMerklOpportunities({
103
+ mainProtocolId: 'morpho',
104
+ type: Object.values(MorphoBlueMerklOpportunityType).join(','),
105
+ status: OpportunityStatus.LIVE,
106
+ });
107
+ } catch (e) {
108
+ console.error('Failed to fetch Morpho Blue Merkl campaigns', e);
109
+ return [];
110
+ }
111
+ };
112
+
113
+ /**
114
+ * Fetches live Merkl campaigns and appends the ones for the market to its `assetsData` incentive
115
+ * arrays. Never throws — on any failure the market info is returned unchanged.
116
+ */
117
+ export const addMorphoBlueMerklRewardsToMarketInfo = async (
118
+ marketInfo: MorphoBlueMarketInfo,
119
+ selectedMarket: MorphoBlueMarketData,
120
+ network: NetworkNumber,
121
+ ): Promise<MorphoBlueMarketInfo> => addMorphoBlueMerklOpportunitiesToMarketInfo(marketInfo, selectedMarket, network, await getMorphoBlueMerklOpportunities());
@@ -44,7 +44,7 @@ import { _getLiquityTroveInfo, getLiquityStakingData } from '../liquity';
44
44
  import { _getLiquityV2MarketData, getLiquitySAndYBold, getLiquityV2Staking } from '../liquityV2';
45
45
  import { _getAllUserEarnPositionsWithFTokens, _getUserPositionsPortfolio } from '../fluid';
46
46
  import { getUmbrellaData } from '../umbrella';
47
- import { getMeritUnclaimedRewards, getUnclaimedRewardsForAllMarkets } from '../claiming/aaveV3';
47
+ import { getMerklUnclaimedRewards, getUnclaimedRewardsForAllMarkets } from '../claiming/aaveV3';
48
48
  import { getCompoundV3Rewards } from '../claiming/compV3';
49
49
  import { fetchSparkAirdropRewards, fetchSparkRewards } from '../claiming/spark';
50
50
  import { getKingRewards } from '../claiming/king';
@@ -151,7 +151,7 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
151
151
  };
152
152
 
153
153
  rewardsData[address.toLowerCase() as EthAddress] = {
154
- aaveV3merit: {},
154
+ merkl: {},
155
155
  aaveV3: {},
156
156
  compV3: {},
157
157
  spark: {},
@@ -364,11 +364,11 @@ export async function getPortfolioData(provider: EthereumProvider, network: Netw
364
364
  })).flat(),
365
365
  ...addresses.map(async (address) => {
366
366
  try {
367
- const aaveMeritData = await getMeritUnclaimedRewards(address, network);
368
- rewardsData[address.toLowerCase() as EthAddress].aaveV3merit = { error: '', data: aaveMeritData };
367
+ const merklData = await getMerklUnclaimedRewards(address, network);
368
+ rewardsData[address.toLowerCase() as EthAddress].merkl = { error: '', data: merklData };
369
369
  } catch (error) {
370
- console.error(`Error fetching Aave V3 Merit rewards data for address ${address}:`, error);
371
- rewardsData[address.toLowerCase() as EthAddress].aaveV3merit = { error: `Error fetching Aave V3 Merit rewards data for address ${address}`, data: null };
370
+ console.error(`Error fetching Merkl rewards data for address ${address}:`, error);
371
+ rewardsData[address.toLowerCase() as EthAddress].merkl = { error: `Error fetching Merkl rewards data for address ${address}`, data: null };
372
372
  }
373
373
  }),
374
374
  ...aaveV3Markets.map(market => addresses.map(async (address) => {
@@ -0,0 +1,31 @@
1
+ import { MerklOpportunity } from '../types';
2
+ import { LONGER_TIMEOUT } from './utils';
3
+
4
+ const MERKL_OPPORTUNITIES_URL = 'https://fe.defisaver.com/api/merkl/opportunities';
5
+
6
+ /**
7
+ * Fetches every page matching the query. Merkl returns 20 opportunities by default, so omitting
8
+ * `items` and advancing `page` avoids imposing a client-side maximum on the result set.
9
+ */
10
+ export const fetchAllMerklOpportunities = async (query: Record<string, string>): Promise<MerklOpportunity[]> => {
11
+ const opportunities: MerklOpportunity[] = [];
12
+ let page = 0;
13
+ let pageOpportunities: MerklOpportunity[];
14
+
15
+ do {
16
+ const searchParams = new URLSearchParams({ ...query, page: page.toString() });
17
+ const res = await fetch(`${MERKL_OPPORTUNITIES_URL}?${searchParams}`, { // eslint-disable-line no-await-in-loop
18
+ signal: AbortSignal.timeout(LONGER_TIMEOUT),
19
+ });
20
+ if (!res.ok) throw new Error(`Failed to fetch Merkl opportunities page ${page}`);
21
+
22
+ const data = await res.json(); // eslint-disable-line no-await-in-loop
23
+ if (!Array.isArray(data)) throw new Error(`Invalid Merkl opportunities response on page ${page}`);
24
+
25
+ pageOpportunities = data as MerklOpportunity[];
26
+ opportunities.push(...pageOpportunities);
27
+ page += 1;
28
+ } while (pageOpportunities.length > 0);
29
+
30
+ return opportunities;
31
+ };
@@ -97,10 +97,20 @@ export const isEligibleForAaveV3ArbitrumETHLSBorrow = (usedAssets: MMUsedAssets)
97
97
  return { isEligible: true, eligibleUSDAmount: ETHAmountBorrowed };
98
98
  };
99
99
 
100
+ // "Borrow WETH with pufETH collateral" — rewards are calculated as min(collateral * 80% LTV, borrow amount)
101
+ export const isEligibleForCompoundV3PufEthWethBorrow = (usedAssets: MMUsedAssets) => {
102
+ const collateralUsd = usedAssets.pufETH?.suppliedUsd || '0';
103
+ const borrowedUsd = usedAssets.ETH?.borrowedUsd || '0';
104
+ const eligibleUSDAmount = Dec.min(new Dec(collateralUsd).mul('0.8'), borrowedUsd).toString();
105
+
106
+ return { isEligible: new Dec(eligibleUSDAmount).gt(0), eligibleUSDAmount };
107
+ };
108
+
100
109
  export const EligibilityMapping: { [key in IncentiveEligibilityId]: (usedAssets: MMUsedAssets, optionalData: any) => { isEligible: boolean; eligibleUSDAmount: string } } = {
101
110
  [IncentiveEligibilityId.AaveV3EthenaLiquidLeverage]: isEligibleForEthenaUSDeRewards,
102
111
  [IncentiveEligibilityId.AaveV3ArbitrumEthSupply]: isEligibleForAaveV3ArbitrumEthSupply,
103
112
  [IncentiveEligibilityId.AaveV3ArbitrumETHLSBorrow]: isEligibleForAaveV3ArbitrumETHLSBorrow,
104
113
  [IncentiveEligibilityId.AaveV3EthenaLiquidLeveragePlasma]: isEligibleForEthenaUSDeRewards,
105
114
  [IncentiveEligibilityId.AaveV3EthenaLiquidLeveragePlasmaGHO]: isEligibleForEthenaGHORewards,
115
+ [IncentiveEligibilityId.CompoundV3PufEthWethBorrow]: isEligibleForCompoundV3PufEthWethBorrow,
106
116
  };
@@ -5,6 +5,8 @@ export enum ClaimType {
5
5
  AAVE_REWARDS = 'AAVE_REWARDS',
6
6
  /** Merit rewards from AAVE (various tokens) */
7
7
  AAVE_MERIT_REWARDS = 'AAVE_MERIT_REWARDS',
8
+ /** Rewards distributed through Merkl across supported protocols */
9
+ MERKL_REWARDS = 'MERKL_REWARDS',
8
10
  /** Rewards from Compound V3 (only in COMP) */
9
11
  COMPOUND_V3_COMP = 'COMPOUND_V3_COMP',
10
12
  /** Rewards from Spark (wstETH only for now) */
@@ -47,6 +49,16 @@ export type AaveMeritRewardsClaimableToken = _ClaimableTokenPartial & {
47
49
  };
48
50
  };
49
51
 
52
+ export type MerklRewardsClaimableToken = _ClaimableTokenPartial & {
53
+ claimType: ClaimType.MERKL_REWARDS;
54
+ additionalClaimFields: {
55
+ accumulated: string;
56
+ proof: string[];
57
+ decimals: string;
58
+ unclaimed: string;
59
+ };
60
+ };
61
+
50
62
  export type SparkRewardsClaimableToken = _ClaimableTokenPartial & {
51
63
  claimType: ClaimType.SPARK_REWARDS;
52
64
  additionalClaimFields: {
@@ -102,6 +114,7 @@ export type UniswapAirdropClaimableToken = _ClaimableTokenPartial & {
102
114
  export type ClaimableToken =
103
115
  AaveRewardsClaimableToken
104
116
  | AaveMeritRewardsClaimableToken
117
+ | MerklRewardsClaimableToken
105
118
  | CompoundV3CompClaimableToken
106
119
  | SparkRewardsClaimableToken
107
120
  | KingRewardsClaimableToken
@@ -8,12 +8,17 @@ export enum IncentiveSide {
8
8
  Borrow = 'borrow',
9
9
  }
10
10
 
11
+ export enum IncentiveSource {
12
+ Merkl = 'merkl',
13
+ }
14
+
11
15
  export enum IncentiveEligibilityId {
12
16
  AaveV3EthenaLiquidLeverage = '0x0dC599DBB180E64E42b87332FDeC3a551445ea44BORROW_BL',
13
17
  AaveV3ArbitrumEthSupply = '0x5d16261c6715a653248269861bbacf68a9774cde',
14
18
  AaveV3ArbitrumETHLSBorrow = '0x0c84331e39d6658Cd6e6b9ba04736cC4c4734351',
15
19
  AaveV3EthenaLiquidLeveragePlasma = '0x2E8f1FA9c73F9d975B46BDFe40C92b6dDEFA3f31BORROW_BL',
16
20
  AaveV3EthenaLiquidLeveragePlasmaGHO = '2b2f6fefcd3df634',
21
+ CompoundV3PufEthWethBorrow = 'e6e49b79e83041f9',
17
22
  }
18
23
 
19
24
  export enum LeverageType {
@@ -28,6 +33,7 @@ export interface IncentiveData {
28
33
  token: string,
29
34
  apy: string,
30
35
  incentiveKind?: IncentiveKind;
36
+ source?: IncentiveSource;
31
37
  description?: string;
32
38
  eligibilityId?: IncentiveEligibilityId;
33
39
  }
@@ -340,6 +340,8 @@ export interface FluidAggregatedVaultData {
340
340
  leftToBorrowUsd: string,
341
341
  netApy: string,
342
342
  incentiveUsd: string,
343
+ merklSupplyIncentives: IncentiveData[],
344
+ merklBorrowIncentives: IncentiveData[],
343
345
  ratio: string,
344
346
  collRatio: string,
345
347
  minRatio: string,
@@ -484,4 +486,4 @@ export interface FluidFTokenDataStructOutput {
484
486
  supplyRate: bigint;
485
487
  rewardsRate: bigint;
486
488
  withdrawable: bigint;
487
- }
489
+ }
@@ -94,6 +94,7 @@ export interface LiquityV2AggregatedTroveData {
94
94
  suppliedUsd: string,
95
95
  borrowedUsd: string,
96
96
  borrowLimitUsd: string,
97
+ liquidationLimitUsd: string,
97
98
  leftToBorrowUsd: string,
98
99
  netApy: string,
99
100
  incentiveUsd: string,
@@ -112,9 +113,11 @@ export interface LiquityV2TroveData {
112
113
  ratio: string,
113
114
  collRatio: string,
114
115
  liqRatio: string,
116
+ borrowLimitRatio: string,
115
117
  interestRate: string,
116
118
  leftToBorrowUsd: string,
117
119
  borrowLimitUsd: string,
120
+ liquidationLimitUsd: string,
118
121
  suppliedUsd: string,
119
122
  borrowedUsd: string,
120
123
  netApy: string,
@@ -72,6 +72,12 @@ export type MerkleRewardMap = Record<EthAddress, { supply?: MerkleRewardInfo; bo
72
72
 
73
73
  export type AaveV4MerklScopedReward = { [side in IncentiveSide]?: IncentiveData };
74
74
 
75
+ /**
76
+ * Fluid vault-scoped Merkl campaigns keyed by lowercase vault address — `supply` rewards apply to
77
+ * the vault's collateral side, `borrow` rewards to its debt side.
78
+ */
79
+ export type FluidMerklRewardMap = Record<string, { supply: IncentiveData[], borrow: IncentiveData[] }>;
80
+
75
81
  /**
76
82
  * Aave V4 Merkl reward campaigns split by scope:
77
83
  * - `hub`: keyed by `${hubAddress}_${underlyingAddress}` (both lowercase) — rewards for supplying/borrowing via a hub