@defisaver/positions-sdk 2.1.127-midnight-dev → 2.1.127-midnight-2-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 (79) hide show
  1. package/cjs/aaveV3/index.js +7 -1
  2. package/cjs/aaveV4/lend.js +3 -3
  3. package/cjs/claiming/index.d.ts +2 -1
  4. package/cjs/claiming/index.js +3 -1
  5. package/cjs/claiming/uniswap.d.ts +5 -0
  6. package/cjs/claiming/uniswap.js +75 -0
  7. package/cjs/config/contracts.d.ts +22 -0
  8. package/cjs/config/contracts.js +9 -1
  9. package/cjs/contracts.d.ts +35 -0
  10. package/cjs/contracts.js +2 -1
  11. package/cjs/curveUsd/index.js +1 -1
  12. package/cjs/helpers/morphoBlueHelpers/index.js +1 -0
  13. package/cjs/helpers/morphoMidnightHelpers/index.d.ts +62 -0
  14. package/cjs/helpers/morphoMidnightHelpers/index.js +156 -1
  15. package/cjs/llamaLend/index.js +1 -1
  16. package/cjs/markets/aaveV4/index.d.ts +2 -0
  17. package/cjs/markets/aaveV4/index.js +14 -1
  18. package/cjs/morphoBlue/index.d.ts +8 -6
  19. package/cjs/morphoBlue/index.js +69 -40
  20. package/cjs/morphoMidnight/index.js +25 -1
  21. package/cjs/portfolio/index.js +31 -2
  22. package/cjs/savings/summerVaults/options.js +10 -10
  23. package/cjs/staking/staking.js +3 -0
  24. package/cjs/types/aaveV4.d.ts +2 -1
  25. package/cjs/types/aaveV4.js +1 -0
  26. package/cjs/types/claiming.d.ts +10 -0
  27. package/cjs/types/claiming.js +2 -0
  28. package/cjs/types/morphoBlue.d.ts +9 -0
  29. package/cjs/types/morphoMidnight.d.ts +3 -0
  30. package/esm/aaveV3/index.js +7 -1
  31. package/esm/aaveV4/lend.js +3 -3
  32. package/esm/claiming/index.d.ts +2 -1
  33. package/esm/claiming/index.js +2 -1
  34. package/esm/claiming/uniswap.d.ts +5 -0
  35. package/esm/claiming/uniswap.js +67 -0
  36. package/esm/config/contracts.d.ts +22 -0
  37. package/esm/config/contracts.js +8 -0
  38. package/esm/contracts.d.ts +35 -0
  39. package/esm/contracts.js +1 -0
  40. package/esm/curveUsd/index.js +1 -1
  41. package/esm/helpers/morphoBlueHelpers/index.js +1 -0
  42. package/esm/helpers/morphoMidnightHelpers/index.d.ts +62 -0
  43. package/esm/helpers/morphoMidnightHelpers/index.js +149 -0
  44. package/esm/llamaLend/index.js +1 -1
  45. package/esm/markets/aaveV4/index.d.ts +2 -0
  46. package/esm/markets/aaveV4/index.js +12 -0
  47. package/esm/morphoBlue/index.d.ts +8 -6
  48. package/esm/morphoBlue/index.js +62 -39
  49. package/esm/morphoMidnight/index.js +26 -2
  50. package/esm/portfolio/index.js +32 -3
  51. package/esm/savings/summerVaults/options.js +10 -10
  52. package/esm/staking/staking.js +3 -0
  53. package/esm/types/aaveV4.d.ts +2 -1
  54. package/esm/types/aaveV4.js +1 -0
  55. package/esm/types/claiming.d.ts +10 -0
  56. package/esm/types/claiming.js +2 -0
  57. package/esm/types/morphoBlue.d.ts +9 -0
  58. package/esm/types/morphoMidnight.d.ts +3 -0
  59. package/package.json +2 -2
  60. package/src/aaveV3/index.ts +13 -1
  61. package/src/aaveV4/lend.ts +3 -3
  62. package/src/claiming/index.ts +2 -0
  63. package/src/claiming/uniswap.ts +70 -0
  64. package/src/config/contracts.ts +9 -0
  65. package/src/contracts.ts +2 -0
  66. package/src/curveUsd/index.ts +1 -1
  67. package/src/helpers/morphoBlueHelpers/index.ts +1 -0
  68. package/src/helpers/morphoMidnightHelpers/index.ts +206 -0
  69. package/src/llamaLend/index.ts +1 -1
  70. package/src/markets/aaveV4/index.ts +13 -0
  71. package/src/morphoBlue/index.ts +101 -44
  72. package/src/morphoMidnight/index.ts +29 -2
  73. package/src/portfolio/index.ts +32 -3
  74. package/src/savings/summerVaults/options.ts +10 -10
  75. package/src/staking/staking.ts +2 -0
  76. package/src/types/aaveV4.ts +1 -0
  77. package/src/types/claiming.ts +11 -0
  78. package/src/types/morphoBlue.ts +11 -0
  79. package/src/types/morphoMidnight.ts +6 -0
@@ -99340,3 +99340,25 @@ export declare const AaveV4View: {
99340
99340
  };
99341
99341
  };
99342
99342
  };
99343
+ export declare const UniswapTokenDistributor: {
99344
+ readonly abi: readonly [{
99345
+ readonly inputs: readonly [{
99346
+ readonly internalType: "uint256";
99347
+ readonly name: "index";
99348
+ readonly type: "uint256";
99349
+ }];
99350
+ readonly name: "isClaimed";
99351
+ readonly outputs: readonly [{
99352
+ readonly internalType: "bool";
99353
+ readonly name: "";
99354
+ readonly type: "bool";
99355
+ }];
99356
+ readonly stateMutability: "view";
99357
+ readonly type: "function";
99358
+ }];
99359
+ readonly networks: {
99360
+ readonly "1": {
99361
+ readonly address: "0x090D4613473dEE047c3f2706764f49E0821D256e";
99362
+ };
99363
+ };
99364
+ };
@@ -1358,3 +1358,11 @@ export const AaveV4View = {
1358
1358
  }
1359
1359
  }
1360
1360
  };
1361
+ export const UniswapTokenDistributor = {
1362
+ "abi": [{ "inputs": [{ "internalType": "uint256", "name": "index", "type": "uint256" }], "name": "isClaimed", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" }],
1363
+ "networks": {
1364
+ "1": {
1365
+ "address": "0x090D4613473dEE047c3f2706764f49E0821D256e",
1366
+ }
1367
+ }
1368
+ };
@@ -619752,3 +619752,38 @@ export declare const AaveV4ViewContractViem: (client: Client, network: NetworkNu
619752
619752
  readonly type: "function";
619753
619753
  }];
619754
619754
  };
619755
+ export declare const UniswapTokenDistributorViem: (client: Client, network: NetworkNumber, block?: Blockish) => {
619756
+ read: {
619757
+ isClaimed: (args: readonly [bigint], options?: import("viem").Prettify<import("viem").UnionOmit<import("viem").ReadContractParameters<readonly [{
619758
+ readonly inputs: readonly [{
619759
+ readonly internalType: "uint256";
619760
+ readonly name: "index";
619761
+ readonly type: "uint256";
619762
+ }];
619763
+ readonly name: "isClaimed";
619764
+ readonly outputs: readonly [{
619765
+ readonly internalType: "bool";
619766
+ readonly name: "";
619767
+ readonly type: "bool";
619768
+ }];
619769
+ readonly stateMutability: "view";
619770
+ readonly type: "function";
619771
+ }], "isClaimed", readonly [bigint]>, "address" | "args" | "abi" | "functionName">> | undefined) => Promise<boolean>;
619772
+ };
619773
+ address: `0x${string}`;
619774
+ abi: readonly [{
619775
+ readonly inputs: readonly [{
619776
+ readonly internalType: "uint256";
619777
+ readonly name: "index";
619778
+ readonly type: "uint256";
619779
+ }];
619780
+ readonly name: "isClaimed";
619781
+ readonly outputs: readonly [{
619782
+ readonly internalType: "bool";
619783
+ readonly name: "";
619784
+ readonly type: "bool";
619785
+ }];
619786
+ readonly stateMutability: "view";
619787
+ readonly type: "function";
619788
+ }];
619789
+ };
package/esm/contracts.js CHANGED
@@ -142,3 +142,4 @@ export const YearnViewContractViem = createViemContractFromConfigFunc('YearnView
142
142
  export const MakerDsrContractViem = createViemContractFromConfigFunc('MakerDsr');
143
143
  export const SkySavingsContractView = createViemContractFromConfigFunc('SkySavings');
144
144
  export const AaveV4ViewContractViem = createViemContractFromConfigFunc('AaveV4View');
145
+ export const UniswapTokenDistributorViem = createViemContractFromConfigFunc('UniswapTokenDistributor');
@@ -24,7 +24,7 @@ const getAndFormatBands = (provider, network, selectedMarket, _minBand, _maxBand
24
24
  // getBandsData uses a lot of gas to get all of the bands at once, so we use pagination and fetch 200 bands at a time
25
25
  let i = minBand;
26
26
  while (i < maxBand) {
27
- i += 200;
27
+ i += 20;
28
28
  if (i > maxBand) {
29
29
  pivots.push(maxBand);
30
30
  }
@@ -348,6 +348,7 @@ export const getRewardsForMarket = (marketId_1, ...args_1) => __awaiter(void 0,
348
348
  query: REWARDS_QUERY,
349
349
  variables: { marketId, chainId: network },
350
350
  }),
351
+ signal: AbortSignal.timeout(LONGER_TIMEOUT),
351
352
  });
352
353
  const data = yield response.json();
353
354
  const marketData = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.marketById;
@@ -1,3 +1,4 @@
1
+ import Dec from 'decimal.js';
1
2
  import { MMUsedAssets } from '../../types/common';
2
3
  import { MorphoMidnightAggregatedPositionData, MorphoMidnightAssetsData, MorphoMidnightMarketInfo } from '../../types';
3
4
  /**
@@ -14,3 +15,64 @@ export declare const getMorphoMidnightAggregatedPositionData: ({ usedAssets, ass
14
15
  assetsData: MorphoMidnightAssetsData;
15
16
  marketInfo: MorphoMidnightMarketInfo;
16
17
  }) => MorphoMidnightAggregatedPositionData;
18
+ export interface MorphoMidnightBorrowInfo {
19
+ borrowRate: string;
20
+ debtBase: string;
21
+ debtInterest: string;
22
+ debtTotal: string;
23
+ }
24
+ export interface MorphoMidnightBorrowQuote {
25
+ bestPrice: string;
26
+ worstPrice: string;
27
+ estBorrowRate: string;
28
+ maxRate: string;
29
+ newUnits: string;
30
+ maxUnits: string;
31
+ availableAssets: string;
32
+ availableUnits: string;
33
+ takeableOffers: any[];
34
+ }
35
+ export declare const midnightTimeToMaturityDays: (maturity: number, atSeconds?: number) => number;
36
+ export declare const midnightApyFromPrice: (price: Dec.Value, ttmDays: Dec.Value) => string;
37
+ /**
38
+ * Inverse of `midnightApyFromPrice`: the loan-per-unit price a borrow APY implies,
39
+ * price = (1 + rate)^(−ttmDays / 365).
40
+ *
41
+ * This is what turns an absolute rate ceiling into an on-chain `maxUnits` cap (units = assets / price),
42
+ * and equally the principal a unit of borrow power is worth — Midnight debt is recorded at its maturity
43
+ * face value, so borrowing the full limit as principal would overshoot it by the interest.
44
+ */
45
+ export declare const midnightPriceFromApy: (ratePercent: Dec.Value, ttmDays: Dec.Value) => string;
46
+ /**
47
+ * Coerce a slippage into what the quote endpoint accepts: 0.1–100 with at most one decimal place. The
48
+ * validation is lexical, so a computed value (`4.15066671050631467`) is rejected outright — without this
49
+ * the request 400s and the quote looks unavailable.
50
+ *
51
+ * Rounded **down**, since a wider slippage is a looser cap than the caller asked for.
52
+ */
53
+ export declare const midnightSlippageParam: (slippagePercent: Dec.Value) => string;
54
+ /**
55
+ * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
56
+ * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
57
+ * fill history. Per fill the rate is (units / seller_assets)^(365 / ttmAtFill) − 1, weighted by base amount.
58
+ * The caller swallows errors — a missing rate must never block position rendering.
59
+ */
60
+ export declare const getMorphoMidnightUserBorrowInfo: (account: string, marketId: string, maturity: number, loanTokenSymbol: string) => Promise<MorphoMidnightBorrowInfo>;
61
+ /**
62
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
63
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
64
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
65
+ * amounts. Throws if the book can't fill the amount (caller handles).
66
+ *
67
+ * Two ways to set the cap:
68
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
69
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
70
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
71
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
72
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
73
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
74
+ *
75
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
76
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
77
+ */
78
+ export declare const getMorphoMidnightBorrowQuote: (marketId: string, assetsRaw: string, slippagePercent: Dec.Value, maturity: number, maxBorrowRate?: Dec.Value) => Promise<MorphoMidnightBorrowQuote>;
@@ -1,7 +1,19 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
1
10
  import Dec from 'decimal.js';
11
+ import { assetAmountInEth } from '@defisaver/tokens';
2
12
  import { calcLeverageLiqPrice, getAssetsTotal, getExposure, isLeveragedPos, } from '../../moneymarket';
3
13
  import { calculateNetApy } from '../../staking';
4
14
  import { LeverageType, } from '../../types/common';
15
+ import { SECONDS_PER_DAY, WAD } from '../../constants';
16
+ import { LONGER_TIMEOUT } from '../../services/utils';
5
17
  /**
6
18
  * Aggregate a Morpho Midnight position. Midnight markets are multi-collateral, so the borrow limit is
7
19
  * the sum of each collateral's USD value times its own lltv (Aave-v4 style), rather than a single pair.
@@ -59,3 +71,140 @@ export const getMorphoMidnightAggregatedPositionData = ({ usedAssets, assetsData
59
71
  payload.exposure = getExposure(payload.borrowedUsd, payload.suppliedUsd);
60
72
  return payload;
61
73
  };
74
+ // ── Off-chain order-book rate helpers ──────────────────────────────────────────────────────────────
75
+ // notion: https://app.notion.com/p/defisaver/Estimate-borrow-rate-and-slippage-before-execution-3a70be682adc80c783c8c11fdb761dd2
76
+ // the borrow rate is not exposed on-chain (MidnightView only stores total debt at maturity in `units`).
77
+ // derive the rate + interest from Morpho's public keyless Midnight API
78
+ // Quote prices are WAD-scaled
79
+ // loan-per-unit ratios (< 1 for a discounted fixed-term borrow); annualizing them yields the borrow APY.
80
+ const MIDNIGHT_API_BASE = 'https://api.morpho.org/v0/midnight';
81
+ const nowInSeconds = () => Math.floor(Date.now() / 1000);
82
+ // The quote endpoint's `slippage` query param is validated as a string: 0.1–100, at most one decimal
83
+ // place (`0.50` is rejected even though `0.5` passes). See `midnightSlippageParam`.
84
+ const MIDNIGHT_SLIPPAGE_MIN = 0.1;
85
+ const MIDNIGHT_SLIPPAGE_MAX = 100;
86
+ // Days remaining until maturity, optionally measured at a past timestamp (for historical fills).
87
+ export const midnightTimeToMaturityDays = (maturity, atSeconds = nowInSeconds()) => new Dec(maturity).sub(atSeconds).div(SECONDS_PER_DAY).toNumber();
88
+ // Annualize a fixed-term discount price into an APY percent: (1 / price)^(365 / ttmDays) − 1.
89
+ // `price` is loan-per-unit (assets received / units owed), so 1/price ≥ 1.
90
+ export const midnightApyFromPrice = (price, ttmDays) => {
91
+ const p = new Dec(price);
92
+ const ttm = new Dec(ttmDays);
93
+ if (p.lte(0) || ttm.lte(0))
94
+ return '0';
95
+ return new Dec(1).div(p).pow(new Dec(365).div(ttm)).sub(1)
96
+ .mul(100)
97
+ .toString();
98
+ };
99
+ /**
100
+ * Inverse of `midnightApyFromPrice`: the loan-per-unit price a borrow APY implies,
101
+ * price = (1 + rate)^(−ttmDays / 365).
102
+ *
103
+ * This is what turns an absolute rate ceiling into an on-chain `maxUnits` cap (units = assets / price),
104
+ * and equally the principal a unit of borrow power is worth — Midnight debt is recorded at its maturity
105
+ * face value, so borrowing the full limit as principal would overshoot it by the interest.
106
+ */
107
+ export const midnightPriceFromApy = (ratePercent, ttmDays) => {
108
+ const rate = new Dec(ratePercent);
109
+ const ttm = new Dec(ttmDays);
110
+ if (rate.lte(0) || ttm.lte(0))
111
+ return '1';
112
+ return new Dec(1).div(new Dec(1).add(rate.div(100)).pow(ttm.div(365))).toString();
113
+ };
114
+ /**
115
+ * Coerce a slippage into what the quote endpoint accepts: 0.1–100 with at most one decimal place. The
116
+ * validation is lexical, so a computed value (`4.15066671050631467`) is rejected outright — without this
117
+ * the request 400s and the quote looks unavailable.
118
+ *
119
+ * Rounded **down**, since a wider slippage is a looser cap than the caller asked for.
120
+ */
121
+ export const midnightSlippageParam = (slippagePercent) => Dec.min(Dec.max(new Dec(slippagePercent), MIDNIGHT_SLIPPAGE_MIN), MIDNIGHT_SLIPPAGE_MAX).toDP(1, Dec.ROUND_DOWN).toString();
122
+ /**
123
+ * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
124
+ * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
125
+ * fill history. Per fill the rate is (units / seller_assets)^(365 / ttmAtFill) − 1, weighted by base amount.
126
+ * The caller swallows errors — a missing rate must never block position rendering.
127
+ */
128
+ export const getMorphoMidnightUserBorrowInfo = (account, marketId, maturity, loanTokenSymbol) => __awaiter(void 0, void 0, void 0, function* () {
129
+ const res = yield fetch(`${MIDNIGHT_API_BASE}/users/${account}/transactions`, { signal: AbortSignal.timeout(LONGER_TIMEOUT) });
130
+ const json = yield res.json();
131
+ const borrows = ((json === null || json === void 0 ? void 0 : json.data) || []).filter((t) => { var _a; return t.event_type === 'borrow' && ((_a = t.market_id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === marketId.toLowerCase(); });
132
+ let sumSeller = new Dec(0); // Σ seller_assets (base), raw
133
+ let sumUnits = new Dec(0); // Σ units (debt at maturity), raw
134
+ let weightedApy = new Dec(0); // Σ seller_assets × APYᵢ
135
+ borrows.forEach((t) => {
136
+ var _a, _b;
137
+ const sellerAssets = new Dec(((_a = t.data) === null || _a === void 0 ? void 0 : _a.seller_assets) || 0);
138
+ const units = new Dec(((_b = t.data) === null || _b === void 0 ? void 0 : _b.units) || 0);
139
+ if (sellerAssets.lte(0) || units.lte(0))
140
+ return;
141
+ const ttmDays = midnightTimeToMaturityDays(maturity, t.created_at);
142
+ const apy = midnightApyFromPrice(sellerAssets.div(units), ttmDays); // price = seller_assets / units
143
+ sumSeller = sumSeller.add(sellerAssets);
144
+ sumUnits = sumUnits.add(units);
145
+ weightedApy = weightedApy.add(sellerAssets.mul(apy));
146
+ });
147
+ const borrowRate = sumSeller.lte(0) ? '0' : weightedApy.div(sumSeller).toString();
148
+ const debtBase = assetAmountInEth(sumSeller.toFixed(0), loanTokenSymbol);
149
+ const debtTotal = assetAmountInEth(sumUnits.toFixed(0), loanTokenSymbol);
150
+ const debtInterest = Dec.max(new Dec(debtTotal).sub(debtBase), 0).toString();
151
+ return {
152
+ borrowRate, debtBase, debtInterest, debtTotal,
153
+ };
154
+ });
155
+ // The API says why a quote failed — NOT_FOUND (market matured or not open yet), INSUFFICIENT_LIQUIDITY
156
+ // (book can't fill the size), VALIDATION_ERROR (bad param, with the offending field in `details`).
157
+ // Callers surface this to the user, so keep the reason rather than collapsing everything into one string.
158
+ const midnightQuoteError = (error) => {
159
+ const detail = ((error === null || error === void 0 ? void 0 : error.details) || []).map(({ issue }) => issue).filter(Boolean).join('; ');
160
+ const reason = detail || (error === null || error === void 0 ? void 0 : error.message) || (error === null || error === void 0 ? void 0 : error.code);
161
+ return reason ? `Morpho Midnight quote unavailable: ${reason}` : 'Morpho Midnight quote unavailable';
162
+ };
163
+ /**
164
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
165
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
166
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
167
+ * amounts. Throws if the book can't fill the amount (caller handles).
168
+ *
169
+ * Two ways to set the cap:
170
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
171
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
172
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
173
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
174
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
175
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
176
+ *
177
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
178
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
179
+ */
180
+ export const getMorphoMidnightBorrowQuote = (marketId, assetsRaw, slippagePercent, maturity, maxBorrowRate) => __awaiter(void 0, void 0, void 0, function* () {
181
+ const url = `${MIDNIGHT_API_BASE}/books/${marketId}/bids/quote?assets=${assetsRaw}&slippage=${midnightSlippageParam(slippagePercent)}`;
182
+ const res = yield fetch(url, { signal: AbortSignal.timeout(LONGER_TIMEOUT) });
183
+ const json = yield res.json();
184
+ const d = json === null || json === void 0 ? void 0 : json.data;
185
+ if (!(d === null || d === void 0 ? void 0 : d.average_best_price))
186
+ throw new Error(midnightQuoteError(json === null || json === void 0 ? void 0 : json.error));
187
+ const bestPrice = new Dec(d.average_best_price).div(WAD).toString();
188
+ const worstPrice = new Dec(d.average_worst_price || 0).div(WAD).toString();
189
+ const ttmDays = midnightTimeToMaturityDays(maturity);
190
+ const estBorrowRate = midnightApyFromPrice(bestPrice, ttmDays);
191
+ // Price the cap sits at, and the rate that price represents — one derivation, so `maxRate` and
192
+ // `maxUnits` can never disagree about what the user is protected at.
193
+ const capPrice = maxBorrowRate !== undefined && new Dec(maxBorrowRate).gt(0)
194
+ ? midnightPriceFromApy(maxBorrowRate, ttmDays)
195
+ : worstPrice;
196
+ const maxRate = midnightApyFromPrice(capPrice, ttmDays);
197
+ const newUnits = new Dec(bestPrice).lte(0) ? '0' : new Dec(assetsRaw).div(bestPrice).toFixed(0);
198
+ const maxUnits = new Dec(capPrice).lte(0) ? '0' : new Dec(assetsRaw).div(capPrice).toFixed(0);
199
+ return {
200
+ bestPrice,
201
+ worstPrice,
202
+ estBorrowRate,
203
+ maxRate,
204
+ newUnits,
205
+ maxUnits,
206
+ availableAssets: d.available_assets || '0',
207
+ availableUnits: d.available_units || '0',
208
+ takeableOffers: d.takeable_offers || [],
209
+ };
210
+ });
@@ -25,7 +25,7 @@ const getAndFormatBands = (provider, network, selectedMarket, _minBand, _maxBand
25
25
  // getBandsData uses a lot of gas to get all of the bands at once, so we use pagination and fetch 200 bands at a time
26
26
  let i = minBand;
27
27
  while (i < maxBand) {
28
- i += 200;
28
+ i += 20;
29
29
  if (i > maxBand) {
30
30
  pivots.push(maxBand);
31
31
  }
@@ -22,6 +22,7 @@ export declare const AAVE_V4_LIDO_SPOKE: (networkId: NetworkNumber) => AaveV4Spo
22
22
  export declare const AAVE_V4_LOMBARD_BTC_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
23
23
  export declare const AAVE_V4_MAIN_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
24
24
  export declare const AAVE_V4_USDG_PENDLE_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
25
+ export declare const AAVE_V4_USDG_MAPLE_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
25
26
  export declare const AaveV4Spokes: (networkId: NetworkNumber) => {
26
27
  readonly aave_v4_bluechip_spoke: AaveV4SpokeInfo;
27
28
  readonly aave_v4_ethena_correlated_spoke: AaveV4SpokeInfo;
@@ -34,6 +35,7 @@ export declare const AaveV4Spokes: (networkId: NetworkNumber) => {
34
35
  readonly aave_v4_lombard_btc_spoke: AaveV4SpokeInfo;
35
36
  readonly aave_v4_main_spoke: AaveV4SpokeInfo;
36
37
  readonly aave_v4_usdg_pendle_spoke: AaveV4SpokeInfo;
38
+ readonly aave_v4_usdg_maple_spoke: AaveV4SpokeInfo;
37
39
  };
38
40
  export declare const getAaveV4SpokeTypeInfo: (type: AaveV4SpokesType, network?: NetworkNumber) => AaveV4SpokeInfo;
39
41
  export declare const findAaveV4SpokeByAddress: (networkId: NetworkNumber, address: string) => AaveV4SpokeInfo | undefined;
@@ -164,6 +164,17 @@ export const AAVE_V4_USDG_PENDLE_SPOKE = (networkId) => ({
164
164
  AAVE_V4_CORE_HUB(NetworkNumber.Eth).address,
165
165
  ],
166
166
  });
167
+ export const AAVE_V4_USDG_MAPLE_SPOKE = (networkId) => ({
168
+ chainIds: [NetworkNumber.Eth],
169
+ label: 'USDG Maple',
170
+ value: AaveV4SpokesType.AaveV4USDGMapleSpoke,
171
+ url: 'usdg-maple',
172
+ address: '0x774b9655413c34809c1f1b16b654465A89EBE989',
173
+ hubs: [
174
+ AAVE_V4_PAXOS_HUB(NetworkNumber.Eth).address,
175
+ AAVE_V4_CORE_HUB(NetworkNumber.Eth).address,
176
+ ],
177
+ });
167
178
  export const AaveV4Spokes = (networkId) => ({
168
179
  [AaveV4SpokesType.AaveV4BluechipSpoke]: AAVE_V4_BLUECHIP_SPOKE(networkId),
169
180
  [AaveV4SpokesType.AaveV4EthenaCorrelatedSpoke]: AAVE_V4_ETHENA_CORRELATED_SPOKE(networkId),
@@ -176,6 +187,7 @@ export const AaveV4Spokes = (networkId) => ({
176
187
  [AaveV4SpokesType.AaveV4LombardBtcSpoke]: AAVE_V4_LOMBARD_BTC_SPOKE(networkId),
177
188
  [AaveV4SpokesType.AaveV4MainSpoke]: AAVE_V4_MAIN_SPOKE(networkId),
178
189
  [AaveV4SpokesType.AaveV4USDGPendleSpoke]: AAVE_V4_USDG_PENDLE_SPOKE(networkId),
190
+ [AaveV4SpokesType.AaveV4USDGMapleSpoke]: AAVE_V4_USDG_MAPLE_SPOKE(networkId),
179
191
  });
180
192
  export const getAaveV4SpokeTypeInfo = (type, network) => (Object.assign({}, AaveV4Spokes(network !== null && network !== void 0 ? network : NetworkNumber.Eth))[type]);
181
193
  export const findAaveV4SpokeByAddress = (networkId, address) => Object.values(AaveV4Spokes(networkId)).find(spoke => spoke.address.toLowerCase() === address.toLowerCase());
@@ -1,14 +1,16 @@
1
1
  import { Client } from 'viem';
2
2
  import { Blockish, EthAddress, EthereumProvider, NetworkNumber, PositionBalances } from '../types/common';
3
- import { MorphoBlueMarketData, MorphoBlueMarketInfo, MorphoBluePositionData } from '../types';
3
+ import { MorphoBlueEarnData, MorphoBlueMarketData, MorphoBlueMarketInfo, MorphoBlueMarketRewards, MorphoBluePositionData } from '../types';
4
+ export declare const addMorphoBlueRewardsToMarketInfo: (marketInfo: MorphoBlueMarketInfo, rewards: MorphoBlueMarketRewards) => MorphoBlueMarketInfo;
4
5
  export declare function _getMorphoBlueMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
6
+ export declare function _getMorphoBluePortfolioMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
5
7
  export declare function getMorphoBlueMarketData(provider: EthereumProvider, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
8
+ export declare function getMorphoBluePortfolioMarketData(provider: EthereumProvider, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
9
+ export declare const getMorphoBluePositionDataWithMarketInfo: (data: MorphoBluePositionData, marketInfo: MorphoBlueMarketInfo) => MorphoBluePositionData;
10
+ export declare const getMorphoEarnDataWithMarketInfo: (data: MorphoBlueEarnData, marketInfo: MorphoBlueMarketInfo) => MorphoBlueEarnData;
11
+ export declare function getMorphoBlueMarketRewards(network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketRewards>;
6
12
  export declare const _getMorphoBlueAccountBalances: (provider: Client, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress, selectedMarket: MorphoBlueMarketData) => Promise<PositionBalances>;
7
13
  export declare const getMorphoBlueAccountBalances: (provider: EthereumProvider, network: NetworkNumber, block: Blockish, addressMapping: boolean, address: EthAddress, selectedMarket: MorphoBlueMarketData) => Promise<PositionBalances>;
8
14
  export declare function _getMorphoBlueAccountData(provider: Client, network: NetworkNumber, account: EthAddress, selectedMarket: MorphoBlueMarketData, marketInfo: MorphoBlueMarketInfo): Promise<MorphoBluePositionData>;
9
15
  export declare function getMorphoBlueAccountData(provider: EthereumProvider, network: NetworkNumber, account: EthAddress, selectedMarket: MorphoBlueMarketData, marketInfo: MorphoBlueMarketInfo): Promise<MorphoBluePositionData>;
10
- export declare function getMorphoEarn(provider: Client, network: NetworkNumber, account: EthAddress, selectedMarket: MorphoBlueMarketData, marketInfo: MorphoBlueMarketInfo): Promise<{
11
- apy: string;
12
- amount: string;
13
- amountUsd: string;
14
- }>;
16
+ export declare function getMorphoEarn(provider: Client, network: NetworkNumber, account: EthAddress, selectedMarket: MorphoBlueMarketData, marketInfo: MorphoBlueMarketInfo): Promise<MorphoBlueEarnData>;
@@ -18,7 +18,20 @@ import { getBorrowRate, getMorphoBlueAggregatedPositionData, getRewardsForMarket
18
18
  import { getChainlinkAssetAddress } from '../services/priceService';
19
19
  import { getViemProvider, setViemBlockNumber } from '../services/viem';
20
20
  const HARDCODED_USD_STABLE_PRICE = '100000000'; // $1 with 8 decimals
21
- export function _getMorphoBlueMarketData(provider, network, selectedMarket) {
21
+ const getMorphoRewardIncentives = (apy) => [{
22
+ token: 'MORPHO',
23
+ apy,
24
+ incentiveKind: IncentiveKind.Reward,
25
+ description: 'Eligible for protocol-level MORPHO incentives.',
26
+ }];
27
+ export const addMorphoBlueRewardsToMarketInfo = (marketInfo, rewards) => (Object.assign(Object.assign({}, marketInfo), { assetsData: Object.assign(Object.assign({}, marketInfo.assetsData), { [marketInfo.loanToken]: Object.assign(Object.assign({}, marketInfo.assetsData[marketInfo.loanToken]), { supplyIncentives: [
28
+ ...marketInfo.assetsData[marketInfo.loanToken].supplyIncentives.filter(({ token }) => token !== 'MORPHO'),
29
+ ...getMorphoRewardIncentives(rewards.supplyApy),
30
+ ], borrowIncentives: [
31
+ ...marketInfo.assetsData[marketInfo.loanToken].borrowIncentives.filter(({ token }) => token !== 'MORPHO'),
32
+ ...getMorphoRewardIncentives(rewards.borrowApy),
33
+ ] }) }) }));
34
+ function getMorphoBlueMarketDataInternal(provider, network, selectedMarket) {
22
35
  return __awaiter(this, void 0, void 0, function* () {
23
36
  const { loanToken, collateralToken, oracle, irm, lltv, oracleType, } = selectedMarket;
24
37
  const lltvInWei = new Dec(lltv).mul(WAD).toString();
@@ -50,16 +63,6 @@ export function _getMorphoBlueMarketData(provider, network, selectedMarket) {
50
63
  marketInfo = _marketInfo;
51
64
  loanTokenPrice = loanTokenPriceRound[1].toString();
52
65
  }
53
- let morphoSupplyApy = '0';
54
- let morphoBorrowApy = '0';
55
- try {
56
- const { supplyApy: _morphoSupplyApy, borrowApy: _morphoBorrowApy } = yield getRewardsForMarket(selectedMarket.marketId, network);
57
- morphoSupplyApy = _morphoSupplyApy;
58
- morphoBorrowApy = _morphoBorrowApy;
59
- }
60
- catch (e) {
61
- console.error(e);
62
- }
63
66
  const supplyRate = getSupplyRate(marketInfo.totalSupplyAssets.toString(), marketInfo.totalBorrowAssets.toString(), marketInfo.borrowRate.toString(), marketInfo.fee.toString());
64
67
  const compoundedBorrowRate = getBorrowRate(marketInfo.borrowRate.toString(), marketInfo.totalBorrowShares.toString());
65
68
  const utillization = new Dec(marketInfo.totalBorrowAssets.toString()).div(marketInfo.totalSupplyAssets.toString()).mul(100).toString();
@@ -78,18 +81,8 @@ export function _getMorphoBlueMarketData(provider, network, selectedMarket) {
78
81
  totalBorrow: new Dec(marketInfo.totalBorrowAssets.toString()).div(scale).toString(),
79
82
  canBeSupplied: true,
80
83
  canBeBorrowed: true,
81
- supplyIncentives: [{
82
- token: 'MORPHO',
83
- apy: morphoSupplyApy,
84
- incentiveKind: IncentiveKind.Reward,
85
- description: 'Eligible for protocol-level MORPHO incentives.',
86
- }],
87
- borrowIncentives: [{
88
- token: 'MORPHO',
89
- apy: morphoBorrowApy,
90
- incentiveKind: IncentiveKind.Reward,
91
- description: 'Eligible for protocol-level MORPHO incentives.',
92
- }],
84
+ supplyIncentives: [],
85
+ borrowIncentives: [],
93
86
  };
94
87
  assetsData[wethToEth(collateralTokenInfo.symbol)] = {
95
88
  symbol: wethToEth(collateralTokenInfo.symbol),
@@ -124,11 +117,54 @@ export function _getMorphoBlueMarketData(provider, network, selectedMarket) {
124
117
  };
125
118
  });
126
119
  }
120
+ export function _getMorphoBlueMarketData(provider, network, selectedMarket) {
121
+ return __awaiter(this, void 0, void 0, function* () {
122
+ const marketInfo = yield getMorphoBlueMarketDataInternal(provider, network, selectedMarket);
123
+ try {
124
+ const rewards = yield getRewardsForMarket(selectedMarket.marketId, network);
125
+ return addMorphoBlueRewardsToMarketInfo(marketInfo, rewards);
126
+ }
127
+ catch (error) {
128
+ console.error(error);
129
+ return addMorphoBlueRewardsToMarketInfo(marketInfo, { supplyApy: '0', borrowApy: '0' });
130
+ }
131
+ });
132
+ }
133
+ export function _getMorphoBluePortfolioMarketData(provider, network, selectedMarket) {
134
+ return getMorphoBlueMarketDataInternal(provider, network, selectedMarket);
135
+ }
127
136
  export function getMorphoBlueMarketData(provider, network, selectedMarket) {
128
137
  return __awaiter(this, void 0, void 0, function* () {
129
138
  return _getMorphoBlueMarketData(getViemProvider(provider, network), network, selectedMarket);
130
139
  });
131
140
  }
141
+ export function getMorphoBluePortfolioMarketData(provider, network, selectedMarket) {
142
+ return _getMorphoBluePortfolioMarketData(getViemProvider(provider, network), network, selectedMarket);
143
+ }
144
+ export const getMorphoBluePositionDataWithMarketInfo = (data, marketInfo) => (Object.assign(Object.assign({}, data), getMorphoBlueAggregatedPositionData({
145
+ usedAssets: data.usedAssets,
146
+ assetsData: marketInfo.assetsData,
147
+ marketInfo,
148
+ })));
149
+ export const getMorphoEarnDataWithMarketInfo = (data, marketInfo) => {
150
+ const loanTokenInfo = marketInfo.assetsData[marketInfo.loanToken];
151
+ const usedAssets = {
152
+ [marketInfo.loanToken]: {
153
+ symbol: loanTokenInfo.symbol,
154
+ supplied: data.amount,
155
+ borrowed: '0',
156
+ isSupplied: new Dec(data.amount).gt(0),
157
+ isBorrowed: false,
158
+ collateral: false,
159
+ suppliedUsd: data.amountUsd,
160
+ borrowedUsd: '0',
161
+ },
162
+ };
163
+ return Object.assign(Object.assign({}, data), { apy: calculateNetApy({ usedAssets, assetsData: marketInfo.assetsData }).netApy });
164
+ };
165
+ export function getMorphoBlueMarketRewards(network, selectedMarket) {
166
+ return getRewardsForMarket(selectedMarket.marketId, network);
167
+ }
132
168
  export const _getMorphoBlueAccountBalances = (provider, network, block, addressMapping, address, selectedMarket) => __awaiter(void 0, void 0, void 0, function* () {
133
169
  let balances = {
134
170
  collateral: {},
@@ -216,23 +252,10 @@ export function getMorphoEarn(provider, network, account, selectedMarket, market
216
252
  const loanTokenInfo = marketInfo.assetsData[marketInfo.loanToken];
217
253
  const loanTokenSupplied = assetAmountInEth(loanInfo.suppliedInAssets.toString(), marketInfo.loanToken);
218
254
  const loanTokenSuppliedUsd = new Dec(loanTokenSupplied).mul(loanTokenInfo.price).toString();
219
- const usedAssets = {
220
- [marketInfo.loanToken]: {
221
- symbol: loanTokenInfo.symbol,
222
- supplied: loanTokenSupplied,
223
- borrowed: '0',
224
- isSupplied: new Dec(loanInfo.suppliedInAssets.toString()).gt(0),
225
- isBorrowed: false,
226
- collateral: false,
227
- suppliedUsd: loanTokenSuppliedUsd,
228
- borrowedUsd: '0',
229
- },
230
- };
231
- const { netApy } = calculateNetApy({ usedAssets, assetsData: marketInfo.assetsData });
232
- return {
233
- apy: netApy,
255
+ return getMorphoEarnDataWithMarketInfo({
256
+ apy: '0',
234
257
  amount: loanTokenSupplied,
235
258
  amountUsd: loanTokenSuppliedUsd,
236
- };
259
+ }, marketInfo);
237
260
  });
238
261
  }
@@ -14,7 +14,7 @@ import { DFSFeedRegistryContractViem, FeedRegistryContractViem, MorphoMidnightVi
14
14
  import { USD_QUOTE } from '../constants';
15
15
  import { calculateNetApy } from '../staking';
16
16
  import { isMainnetNetwork, wethToEth } from '../services/utils';
17
- import { getMorphoMidnightAggregatedPositionData } from '../helpers/morphoMidnightHelpers';
17
+ import { getMorphoMidnightAggregatedPositionData, getMorphoMidnightUserBorrowInfo } from '../helpers/morphoMidnightHelpers';
18
18
  import { getChainlinkAssetAddress } from '../services/priceService';
19
19
  import { getViemProvider, setViemBlockNumber } from '../services/viem';
20
20
  const HARDCODED_USD_STABLE_PRICE = '100000000'; // $1 with 8 decimals
@@ -148,9 +148,33 @@ export function _getMorphoMidnightAccountData(provider, network, account, select
148
148
  borrowedUsd: '0',
149
149
  };
150
150
  });
151
+ // Enrich borrower positions with the orderbook-derived rate + principal/interest split (off-chain).
152
+ // MidnightView only stores `debt` (= face value at maturity), so we default to full-debt-as-principal and
153
+ // override from the transactions API when available. Never throw here — the position must still render.
154
+ let borrowRate = '0';
155
+ let debtBase = debt; // fallback: treat the full on-chain debt as principal until fill history is known
156
+ let debtInterest = '0';
157
+ let assetsDataForApy = marketInfo.assetsData;
158
+ if (new Dec(positionInfo.debt.toString()).gt(0)) {
159
+ try {
160
+ const borrowInfo = yield getMorphoMidnightUserBorrowInfo(account, marketId, marketInfo.maturity, marketInfo.loanToken);
161
+ borrowRate = borrowInfo.borrowRate;
162
+ debtBase = borrowInfo.debtBase;
163
+ debtInterest = borrowInfo.debtInterest;
164
+ usedAssets[marketInfo.loanToken].borrowRate = borrowRate;
165
+ // Reflect the real borrow cost in netApy without mutating the shared marketInfo.assetsData.
166
+ assetsDataForApy = Object.assign(Object.assign({}, marketInfo.assetsData), { [marketInfo.loanToken]: Object.assign(Object.assign({}, loanTokenData), { borrowRate }) });
167
+ }
168
+ catch (err) {
169
+ // Orderbook API unavailable — keep the on-chain-only fallback above.
170
+ }
171
+ }
151
172
  return Object.assign({ usedAssets,
152
173
  credit,
153
- debt, maturity: marketInfo.maturity, isMatured: marketInfo.isMatured }, getMorphoMidnightAggregatedPositionData({ usedAssets, assetsData: marketInfo.assetsData, marketInfo }));
174
+ debt,
175
+ borrowRate,
176
+ debtBase,
177
+ debtInterest, maturity: marketInfo.maturity, isMatured: marketInfo.isMatured }, getMorphoMidnightAggregatedPositionData({ usedAssets, assetsData: assetsDataForApy, marketInfo }));
154
178
  });
155
179
  }
156
180
  export function getMorphoMidnightAccountData(provider, network, account, selectedMarket, marketInfo) {