@morpho-org/morpho-sdk 2.1.1 → 3.1.0

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 (206) hide show
  1. package/lib/cjs/abis.d.ts +2816 -0
  2. package/lib/cjs/abis.js +1951 -0
  3. package/lib/cjs/actions/index.d.ts +3 -0
  4. package/lib/cjs/actions/marketV1/borrow.js +7 -10
  5. package/lib/cjs/actions/marketV1/buildReallocationActions.d.ts +2 -3
  6. package/lib/cjs/actions/marketV1/buildReallocationActions.js +1 -2
  7. package/lib/cjs/actions/marketV1/index.d.ts +2 -0
  8. package/lib/cjs/actions/marketV1/index.js +2 -0
  9. package/lib/cjs/actions/marketV1/repay.d.ts +2 -0
  10. package/lib/cjs/actions/marketV1/repay.js +7 -8
  11. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  12. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.js +9 -10
  13. package/lib/cjs/actions/marketV1/supply.d.ts +69 -0
  14. package/lib/cjs/actions/marketV1/supply.js +128 -0
  15. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +3 -1
  16. package/lib/cjs/actions/marketV1/supplyCollateral.js +12 -13
  17. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +3 -1
  18. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +14 -15
  19. package/lib/cjs/actions/marketV1/withdraw.d.ts +83 -0
  20. package/lib/cjs/actions/marketV1/withdraw.js +110 -0
  21. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +2 -2
  22. package/lib/cjs/actions/requirements/getRequirementsAction.d.ts +1 -1
  23. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  24. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -0
  25. package/lib/cjs/actions/vaultV1/deposit.js +13 -14
  26. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -0
  27. package/lib/cjs/actions/vaultV1/migrateToV2.js +11 -9
  28. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -0
  29. package/lib/cjs/actions/vaultV2/deposit.js +13 -14
  30. package/lib/cjs/addresses.d.ts +2 -0
  31. package/lib/cjs/addresses.js +18 -0
  32. package/lib/cjs/augment/AccrualPosition.d.ts +9 -0
  33. package/lib/cjs/augment/AccrualPosition.js +8 -0
  34. package/lib/cjs/augment/AccrualVault.d.ts +8 -0
  35. package/lib/cjs/augment/AccrualVault.js +7 -0
  36. package/lib/cjs/augment/Holding.d.ts +8 -0
  37. package/lib/cjs/augment/Holding.js +7 -0
  38. package/lib/cjs/augment/Market.d.ts +8 -0
  39. package/lib/cjs/augment/Market.js +7 -0
  40. package/lib/cjs/augment/MarketParams.d.ts +8 -0
  41. package/lib/cjs/augment/MarketParams.js +7 -0
  42. package/lib/cjs/augment/Position.d.ts +8 -0
  43. package/lib/cjs/augment/Position.js +7 -0
  44. package/lib/cjs/augment/Token.d.ts +8 -0
  45. package/lib/cjs/augment/Token.js +7 -0
  46. package/lib/cjs/augment/User.d.ts +8 -0
  47. package/lib/cjs/augment/User.js +7 -0
  48. package/lib/cjs/augment/Vault.d.ts +8 -0
  49. package/lib/cjs/augment/Vault.js +7 -0
  50. package/lib/cjs/augment/VaultConfig.d.ts +8 -0
  51. package/lib/cjs/augment/VaultConfig.js +7 -0
  52. package/lib/cjs/augment/VaultMarketAllocation.d.ts +8 -0
  53. package/lib/cjs/augment/VaultMarketAllocation.js +7 -0
  54. package/lib/cjs/augment/VaultMarketConfig.d.ts +8 -0
  55. package/lib/cjs/augment/VaultMarketConfig.js +7 -0
  56. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  57. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +8 -0
  58. package/lib/cjs/augment/VaultUser.d.ts +8 -0
  59. package/lib/cjs/augment/VaultUser.js +7 -0
  60. package/lib/cjs/augment.d.ts +14 -0
  61. package/lib/cjs/augment.js +16 -0
  62. package/lib/cjs/bundler/actions.d.ts +637 -0
  63. package/lib/cjs/bundler/actions.js +1088 -0
  64. package/lib/cjs/bundler/index.d.ts +2 -0
  65. package/lib/cjs/bundler/index.js +18 -0
  66. package/lib/cjs/bundler/types.d.ts +200 -0
  67. package/lib/cjs/bundler/types.js +2 -0
  68. package/lib/cjs/constants.d.ts +3 -0
  69. package/lib/cjs/constants.js +32 -0
  70. package/lib/cjs/entities/index.d.ts +6 -3
  71. package/lib/cjs/entities/index.js +41 -17
  72. package/lib/cjs/entities/marketV1/marketV1.d.ts +161 -24
  73. package/lib/cjs/entities/marketV1/marketV1.js +166 -19
  74. package/lib/cjs/entities/reallocationData.d.ts +193 -0
  75. package/lib/cjs/entities/reallocationData.js +406 -0
  76. package/lib/cjs/errors.d.ts +2 -0
  77. package/lib/cjs/errors.js +18 -0
  78. package/lib/cjs/fetch.d.ts +1 -0
  79. package/lib/cjs/fetch.js +30 -0
  80. package/lib/cjs/format.d.ts +2 -0
  81. package/lib/cjs/format.js +22 -0
  82. package/lib/cjs/helpers/computeReallocations.d.ts +63 -12
  83. package/lib/cjs/helpers/computeReallocations.js +160 -41
  84. package/lib/cjs/helpers/constant.d.ts +17 -0
  85. package/lib/cjs/helpers/constant.js +30 -1
  86. package/lib/cjs/helpers/index.d.ts +3 -2
  87. package/lib/cjs/helpers/index.js +14 -2
  88. package/lib/cjs/helpers/slippage.d.ts +57 -0
  89. package/lib/cjs/helpers/slippage.js +82 -0
  90. package/lib/cjs/helpers/validate.d.ts +40 -7
  91. package/lib/cjs/helpers/validate.js +67 -12
  92. package/lib/cjs/index.d.ts +0 -1
  93. package/lib/cjs/index.js +0 -1
  94. package/lib/cjs/types/action.d.ts +27 -6
  95. package/lib/cjs/types/client.d.ts +1 -1
  96. package/lib/cjs/types/error.d.ts +155 -7
  97. package/lib/cjs/types/error.js +202 -11
  98. package/lib/cjs/types/sharedLiquidity.d.ts +43 -3
  99. package/lib/cjs/types.d.ts +3 -0
  100. package/lib/cjs/types.js +17 -0
  101. package/lib/cjs/utils.d.ts +9 -0
  102. package/lib/cjs/utils.js +65 -0
  103. package/lib/esm/abis.d.ts +2816 -0
  104. package/lib/esm/abis.js +1922 -0
  105. package/lib/esm/actions/index.d.ts +3 -0
  106. package/lib/esm/actions/marketV1/borrow.js +2 -5
  107. package/lib/esm/actions/marketV1/buildReallocationActions.d.ts +2 -3
  108. package/lib/esm/actions/marketV1/buildReallocationActions.js +1 -2
  109. package/lib/esm/actions/marketV1/index.d.ts +2 -0
  110. package/lib/esm/actions/marketV1/index.js +2 -0
  111. package/lib/esm/actions/marketV1/repay.d.ts +2 -0
  112. package/lib/esm/actions/marketV1/repay.js +4 -5
  113. package/lib/esm/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  114. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +4 -5
  115. package/lib/esm/actions/marketV1/supply.d.ts +69 -0
  116. package/lib/esm/actions/marketV1/supply.js +124 -0
  117. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +3 -1
  118. package/lib/esm/actions/marketV1/supplyCollateral.js +7 -8
  119. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +3 -1
  120. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +7 -8
  121. package/lib/esm/actions/marketV1/withdraw.d.ts +83 -0
  122. package/lib/esm/actions/marketV1/withdraw.js +106 -0
  123. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +1 -1
  124. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +1 -1
  125. package/lib/esm/actions/requirements/getRequirementsApproval.js +1 -1
  126. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -0
  127. package/lib/esm/actions/vaultV1/deposit.js +3 -4
  128. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -0
  129. package/lib/esm/actions/vaultV1/migrateToV2.js +3 -1
  130. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -0
  131. package/lib/esm/actions/vaultV2/deposit.js +3 -4
  132. package/lib/esm/addresses.d.ts +2 -0
  133. package/lib/esm/addresses.js +1 -0
  134. package/lib/esm/augment/AccrualPosition.d.ts +9 -0
  135. package/lib/esm/augment/AccrualPosition.js +5 -0
  136. package/lib/esm/augment/AccrualVault.d.ts +8 -0
  137. package/lib/esm/augment/AccrualVault.js +4 -0
  138. package/lib/esm/augment/Holding.d.ts +8 -0
  139. package/lib/esm/augment/Holding.js +4 -0
  140. package/lib/esm/augment/Market.d.ts +8 -0
  141. package/lib/esm/augment/Market.js +4 -0
  142. package/lib/esm/augment/MarketParams.d.ts +8 -0
  143. package/lib/esm/augment/MarketParams.js +4 -0
  144. package/lib/esm/augment/Position.d.ts +8 -0
  145. package/lib/esm/augment/Position.js +4 -0
  146. package/lib/esm/augment/Token.d.ts +8 -0
  147. package/lib/esm/augment/Token.js +4 -0
  148. package/lib/esm/augment/User.d.ts +8 -0
  149. package/lib/esm/augment/User.js +4 -0
  150. package/lib/esm/augment/Vault.d.ts +8 -0
  151. package/lib/esm/augment/Vault.js +4 -0
  152. package/lib/esm/augment/VaultConfig.d.ts +8 -0
  153. package/lib/esm/augment/VaultConfig.js +4 -0
  154. package/lib/esm/augment/VaultMarketAllocation.d.ts +8 -0
  155. package/lib/esm/augment/VaultMarketAllocation.js +4 -0
  156. package/lib/esm/augment/VaultMarketConfig.d.ts +8 -0
  157. package/lib/esm/augment/VaultMarketConfig.js +4 -0
  158. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  159. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +5 -0
  160. package/lib/esm/augment/VaultUser.d.ts +8 -0
  161. package/lib/esm/augment/VaultUser.js +4 -0
  162. package/lib/esm/augment.d.ts +14 -0
  163. package/lib/esm/augment.js +14 -0
  164. package/lib/esm/bundler/actions.d.ts +637 -0
  165. package/lib/esm/bundler/actions.js +1085 -0
  166. package/lib/esm/bundler/index.d.ts +2 -0
  167. package/lib/esm/bundler/index.js +2 -0
  168. package/lib/esm/bundler/types.d.ts +200 -0
  169. package/lib/esm/bundler/types.js +1 -0
  170. package/lib/esm/constants.d.ts +3 -0
  171. package/lib/esm/constants.js +3 -0
  172. package/lib/esm/entities/index.d.ts +6 -3
  173. package/lib/esm/entities/index.js +5 -3
  174. package/lib/esm/entities/marketV1/marketV1.d.ts +161 -24
  175. package/lib/esm/entities/marketV1/marketV1.js +170 -23
  176. package/lib/esm/entities/reallocationData.d.ts +193 -0
  177. package/lib/esm/entities/reallocationData.js +402 -0
  178. package/lib/esm/errors.d.ts +2 -0
  179. package/lib/esm/errors.js +1 -0
  180. package/lib/esm/fetch.d.ts +1 -0
  181. package/lib/esm/fetch.js +1 -0
  182. package/lib/esm/format.d.ts +2 -0
  183. package/lib/esm/format.js +1 -0
  184. package/lib/esm/helpers/computeReallocations.d.ts +63 -12
  185. package/lib/esm/helpers/computeReallocations.js +160 -41
  186. package/lib/esm/helpers/constant.d.ts +17 -0
  187. package/lib/esm/helpers/constant.js +30 -1
  188. package/lib/esm/helpers/index.d.ts +3 -2
  189. package/lib/esm/helpers/index.js +3 -2
  190. package/lib/esm/helpers/slippage.d.ts +57 -0
  191. package/lib/esm/helpers/slippage.js +80 -0
  192. package/lib/esm/helpers/validate.d.ts +40 -7
  193. package/lib/esm/helpers/validate.js +63 -11
  194. package/lib/esm/index.d.ts +0 -1
  195. package/lib/esm/index.js +0 -1
  196. package/lib/esm/types/action.d.ts +27 -6
  197. package/lib/esm/types/client.d.ts +1 -1
  198. package/lib/esm/types/error.d.ts +155 -7
  199. package/lib/esm/types/error.js +185 -9
  200. package/lib/esm/types/sharedLiquidity.d.ts +43 -3
  201. package/lib/esm/types.d.ts +3 -0
  202. package/lib/esm/types.js +1 -0
  203. package/lib/esm/utils.d.ts +9 -0
  204. package/lib/esm/utils.js +7 -0
  205. package/package.json +128 -17
  206. package/src/index.ts +0 -1
@@ -1,27 +1,146 @@
1
1
  import { MarketUtils, MathLib } from "@morpho-org/blue-sdk";
2
- import { DEFAULT_SUPPLY_TARGET_UTILIZATION } from "@morpho-org/bundler-sdk-viem";
3
- import { InsufficientSharedLiquidityError, MissingPublicAllocatorConfigError, } from "../types/index.js";
2
+ import { InsufficientSharedLiquidityError, MissingPublicAllocatorConfigError, ReallocationWithdrawExceedsMarketSupplyError, } from "../types/index.js";
3
+ import { DEFAULT_SUPPLY_TARGET_UTILIZATION } from "./constant.js";
4
+ import { compareMarketIds } from "./validate.js";
5
+ const groupWithdrawalsByVault = (withdrawals) => {
6
+ const groups = [];
7
+ const groupsByVault = new Map();
8
+ for (const [index, { vault, id, assets }] of withdrawals.entries()) {
9
+ if (assets <= 0n)
10
+ continue;
11
+ let group = groupsByVault.get(vault);
12
+ if (group == null) {
13
+ group = {
14
+ vault,
15
+ firstIndex: index,
16
+ totalAssets: 0n,
17
+ withdrawals: [],
18
+ };
19
+ groupsByVault.set(vault, group);
20
+ groups.push(group);
21
+ }
22
+ group.totalAssets += assets;
23
+ group.withdrawals.push({ id, assets });
24
+ }
25
+ return groups.sort((a, b) => {
26
+ if (a.totalAssets > b.totalAssets)
27
+ return -1;
28
+ if (a.totalAssets < b.totalAssets)
29
+ return 1;
30
+ return a.firstIndex - b.firstIndex;
31
+ });
32
+ };
33
+ const capVaultWithdrawals = (withdrawals, assets) => {
34
+ const cappedWithdrawals = [];
35
+ let remainingAssets = assets;
36
+ for (const withdrawal of withdrawals) {
37
+ const cappedAssets = MathLib.min(withdrawal.assets, remainingAssets);
38
+ if (cappedAssets <= 0n)
39
+ continue;
40
+ const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
41
+ if (existing != null) {
42
+ existing.assets += cappedAssets;
43
+ }
44
+ else {
45
+ cappedWithdrawals.push({
46
+ id: withdrawal.id,
47
+ assets: cappedAssets,
48
+ });
49
+ }
50
+ remainingAssets -= cappedAssets;
51
+ if (remainingAssets === 0n)
52
+ break;
53
+ }
54
+ return cappedWithdrawals;
55
+ };
4
56
  /**
5
- * Computes vault reallocations for a borrow operation on a target market.
57
+ * Computes vault reallocations for a `borrow` or `withdraw` on a target market.
6
58
  *
7
- * Replicates the shared liquidity algorithm from `populateSubBundle` in
8
- * `@morpho-org/bundler-sdk-viem`. First attempts "friendly" reallocations
9
- * respecting withdrawal utilization targets, then falls back to aggressive
10
- * reallocations (100% withdrawal utilization) if liquidity is still insufficient.
59
+ * First attempts "friendly" reallocations respecting withdrawal utilization
60
+ * targets, then falls back to aggressive reallocations (100% withdrawal
61
+ * utilization) if liquidity is still insufficient.
11
62
  *
12
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
63
+ * Algebra branches on `operation`:
64
+ * - `"borrow"`: `S' = S`, `B' = B + amount` (additional borrow demand).
65
+ * - `"withdraw"`: `S' = S − amount`, `B' = B` (supply-side shrinkage).
66
+ *
67
+ * In both cases reallocated assets are added on the supply side; `requiredAssets`
68
+ * and `absoluteShortfall` are derived from the operation-specific post-state.
69
+ *
70
+ * @remarks Pass `options.timestamp` from the same block used to fetch `reallocationData`; when omitted, market accrual falls back to the target market's `lastUpdate`, which can diverge from the source rows' fetch block. Per-market `maxWithdrawalUtilization` overrides apply only to phase 1; phase 2 forces 100% utilization on every source market.
71
+ * @param params.reallocationData - The local state containing market, vault, and position data.
13
72
  * @param params.marketId - The target market to reallocate liquidity into.
14
- * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
73
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
74
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
15
75
  * @param params.options - Optional reallocation computation options.
16
76
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
17
- * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
77
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market — preventing fee-bearing reallocations from being attached to a call that would still revert onchain.
78
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
79
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
80
+ * @example
81
+ * ```ts
82
+ * import { createPublicClient, http, parseUnits } from "viem";
83
+ * import { mainnet } from "viem/chains";
84
+ * import { markets, vaults } from "@morpho-org/morpho-test";
85
+ * import {
86
+ * computeReallocations,
87
+ * morphoViemExtension,
88
+ * } from "@morpho-org/morpho-sdk";
89
+ *
90
+ * const client = createPublicClient({
91
+ * chain: mainnet,
92
+ * transport: http(),
93
+ * }).extend(morphoViemExtension());
94
+ *
95
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
96
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
97
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
98
+ * const block = await client.getBlock();
99
+ * const reallocationData = await market.getReallocationData({
100
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
101
+ * block: { number: block.number, timestamp: block.timestamp },
102
+ * });
103
+ * const borrowAmount = parseUnits("1000", 6);
104
+ * const reallocations = computeReallocations({
105
+ * reallocationData,
106
+ * marketId: marketParams.id,
107
+ * operation: "borrow",
108
+ * amount: borrowAmount,
109
+ * options: { timestamp: block.timestamp },
110
+ * });
111
+ * const positionData = await market.getPositionData(userAddress);
112
+ * const borrow = market.borrow({
113
+ * userAddress,
114
+ * amount: borrowAmount,
115
+ * positionData,
116
+ * reallocations,
117
+ * });
118
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
119
+ * ```
18
120
  */
19
- export const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
121
+ export const computeReallocations = ({ reallocationData: data, marketId, operation, amount, options, }) => {
20
122
  if (options?.enabled === false)
21
123
  return [];
22
- const market = data.getMarket(marketId).accrueInterest(data.block.timestamp);
23
- const newTotalBorrowAssets = market.totalBorrowAssets + borrowAmount;
24
- const newTotalSupplyAssets = market.totalSupplyAssets;
124
+ // ReallocationData does not retain the fetch block; pass that block timestamp
125
+ // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
126
+ const market = data.getMarket(marketId).accrueInterest(options?.timestamp);
127
+ // Reject unreachable withdraws before any utilization math: a negative
128
+ // post-supply yields a negative utilization that short-circuits the
129
+ // utilization gate below and silently returns `[]` — masking a sure revert.
130
+ if (operation === "withdraw" && amount > market.totalSupplyAssets) {
131
+ throw new ReallocationWithdrawExceedsMarketSupplyError({
132
+ marketId,
133
+ withdrawAmount: amount,
134
+ totalSupplyAssets: market.totalSupplyAssets,
135
+ });
136
+ }
137
+ // Post-state utilization is operation-dependent.
138
+ const newTotalBorrowAssets = operation === "borrow"
139
+ ? market.totalBorrowAssets + amount
140
+ : market.totalBorrowAssets;
141
+ const newTotalSupplyAssets = operation === "withdraw"
142
+ ? market.totalSupplyAssets - amount
143
+ : market.totalSupplyAssets;
25
144
  const supplyTargetUtilization = options?.supplyTargetUtilization?.[market.params.id] ??
26
145
  options?.defaultSupplyTargetUtilization ??
27
146
  DEFAULT_SUPPLY_TARGET_UTILIZATION;
@@ -39,8 +158,14 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
39
158
  const { withdrawals: friendlyWithdrawals, data: friendlyReallocationData } = data.getMarketPublicReallocations(market.id, options);
40
159
  const withdrawals = [...friendlyWithdrawals];
41
160
  const friendlyReallocationMarket = friendlyReallocationData.getMarket(market.id);
42
- if (friendlyReallocationMarket.totalBorrowAssets + borrowAmount >
43
- friendlyReallocationMarket.totalSupplyAssets) {
161
+ // Operation-specific post-friendly check: would the on-chain call still revert?
162
+ const friendlyBorrow = operation === "borrow"
163
+ ? friendlyReallocationMarket.totalBorrowAssets + amount
164
+ : friendlyReallocationMarket.totalBorrowAssets;
165
+ const friendlySupply = operation === "withdraw"
166
+ ? friendlyReallocationMarket.totalSupplyAssets - amount
167
+ : friendlyReallocationMarket.totalSupplyAssets;
168
+ if (friendlyBorrow > friendlySupply) {
44
169
  // Phase 2: "aggressive" — fully withdraw from every market (100% utilization).
45
170
  requiredAssets = newTotalBorrowAssets - newTotalSupplyAssets;
46
171
  withdrawals.push(...friendlyReallocationData.getMarketPublicReallocations(market.id, {
@@ -51,34 +176,27 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
51
176
  }
52
177
  if (requiredAssets <= 0n)
53
178
  return [];
54
- // Liquidity strictly required for `morphoBorrow` to succeed onchain.
179
+ // Liquidity strictly required for the on-chain call to succeed.
55
180
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
56
181
  ? newTotalBorrowAssets - newTotalSupplyAssets
57
182
  : 0n;
58
- // Group withdrawals by vault, capping total at requiredAssets.
59
- const reallocationsMap = {};
183
+ const reallocations = [];
60
184
  let totalReallocated = 0n;
61
- for (const { vault, ...withdrawal } of withdrawals) {
62
- const vaultReallocations = (reallocationsMap[vault] ??= []);
63
- const existing = vaultReallocations.find((item) => item.id === withdrawal.id);
64
- const reallocatedAssets = MathLib.min(withdrawal.assets, requiredAssets);
185
+ let remainingRequiredAssets = requiredAssets;
186
+ for (const group of groupWithdrawalsByVault(withdrawals)) {
187
+ const reallocatedAssets = MathLib.min(group.totalAssets, remainingRequiredAssets);
65
188
  if (reallocatedAssets <= 0n)
66
189
  continue;
67
- if (existing != null) {
68
- existing.assets += reallocatedAssets;
69
- }
70
- else {
71
- vaultReallocations.push({
72
- ...withdrawal,
73
- assets: reallocatedAssets,
74
- });
75
- }
76
- requiredAssets -= reallocatedAssets;
190
+ reallocations.push({
191
+ vault: group.vault,
192
+ withdrawals: capVaultWithdrawals(group.withdrawals, reallocatedAssets),
193
+ });
194
+ remainingRequiredAssets -= reallocatedAssets;
77
195
  totalReallocated += reallocatedAssets;
78
- if (requiredAssets === 0n)
196
+ if (remainingRequiredAssets === 0n)
79
197
  break;
80
198
  }
81
- // Refuse fee-bearing partial plans for an unreachable borrow.
199
+ // Refuse fee-bearing partial plans for an unreachable operation.
82
200
  if (totalReallocated < absoluteShortfall) {
83
201
  throw new InsufficientSharedLiquidityError({
84
202
  marketId,
@@ -87,10 +205,10 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
87
205
  });
88
206
  }
89
207
  // Transform into VaultReallocation[] format.
90
- return Object.entries(reallocationsMap)
91
- .filter(([, vaultWithdrawals]) => vaultWithdrawals.length > 0)
92
- .map(([vault, vaultWithdrawals]) => ({
93
- vault: vault,
208
+ return reallocations
209
+ .filter(({ withdrawals: vaultWithdrawals }) => vaultWithdrawals.length > 0)
210
+ .map(({ vault, withdrawals: vaultWithdrawals }) => ({
211
+ vault,
94
212
  fee: (() => {
95
213
  const config = data.getVault(vault).publicAllocatorConfig;
96
214
  if (config == null) {
@@ -99,8 +217,9 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
99
217
  return config.fee;
100
218
  })(),
101
219
  withdrawals: vaultWithdrawals
102
- // Reallocation withdrawals must be sorted by market id in ascending order.
103
- .sort(({ id: idA }, { id: idB }) => idA > idB ? 1 : idA < idB ? -1 : 0)
220
+ // Reallocation withdrawals must be sorted by market id in ascending
221
+ // order. Normalize first because `MarketId` can be mixed-case hex.
222
+ .sort(({ id: idA }, { id: idB }) => compareMarketIds(idA, idB))
104
223
  .map(({ id, assets }) => ({
105
224
  marketParams: data.getMarket(id).params,
106
225
  amount: assets,
@@ -1,6 +1,23 @@
1
+ import { type Address } from "viem";
1
2
  /** Maximum slippage tolerance: 10% */
2
3
  export declare const MAX_SLIPPAGE_TOLERANCE: bigint;
3
4
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
4
5
  export declare const DEFAULT_LLTV_BUFFER: bigint;
5
6
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
6
7
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
8
+ /**
9
+ * The default maximum utilization allowed to reach when withdrawing shared liquidity.
10
+ */
11
+ export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
12
+ /**
13
+ * The default target utilization above which shared liquidity reallocations are triggered.
14
+ */
15
+ export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
16
+ /**
17
+ * Tokens that require setting allowance from zero before changing approval.
18
+ */
19
+ export declare const APPROVE_ONLY_ONCE_TOKENS: Partial<Record<number, Address[]>>;
20
+ /**
21
+ * Token-specific maximum approval amounts for tokens that cannot use uint256 max.
22
+ */
23
+ export declare const MAX_TOKEN_APPROVALS: Partial<Record<number, Record<Address, bigint>>>;
@@ -1,7 +1,36 @@
1
- import { MathLib } from "@morpho-org/blue-sdk";
1
+ import { ChainId, MathLib } from "@morpho-org/blue-sdk";
2
+ import { maxUint96 } from "viem";
2
3
  /** Maximum slippage tolerance: 10% */
3
4
  export const MAX_SLIPPAGE_TOLERANCE = MathLib.WAD / 10n;
4
5
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
5
6
  export const DEFAULT_LLTV_BUFFER = MathLib.WAD / 200n;
6
7
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
7
8
  export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
9
+ /**
10
+ * The default maximum utilization allowed to reach when withdrawing shared liquidity.
11
+ */
12
+ export const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
13
+ /**
14
+ * The default target utilization above which shared liquidity reallocations are triggered.
15
+ */
16
+ export const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
17
+ /**
18
+ * Tokens that require setting allowance from zero before changing approval.
19
+ */
20
+ export const APPROVE_ONLY_ONCE_TOKENS = {
21
+ [ChainId.EthMainnet]: [
22
+ "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT
23
+ "0xD533a949740bb3306d119CC777fa900bA034cd52", // CRV
24
+ ],
25
+ };
26
+ /**
27
+ * Token-specific maximum approval amounts for tokens that cannot use uint256 max.
28
+ */
29
+ export const MAX_TOKEN_APPROVALS = {
30
+ [ChainId.EthMainnet]: {
31
+ "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984": maxUint96, // UNI
32
+ "0xfAbA6f8e4a5E8Ab82F62fe7C39859FA577269BE3": maxUint96, // ONDO
33
+ "0xc00e94Cb662C3520282E6f5717214004A7f26888": maxUint96, // COMP
34
+ "0x6f40d4A6237C257fff2dB00FA0510DeEECd303eb": maxUint96, // FLUID
35
+ },
36
+ };
@@ -1,4 +1,5 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
3
  export { addTransactionMetadata } from "./metadata.js";
3
- export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
4
- export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./validate.js";
4
+ export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
5
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -1,4 +1,5 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
3
  export { addTransactionMetadata } from "./metadata.js";
3
- export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
4
- export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./validate.js";
4
+ export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
5
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -44,3 +44,60 @@ export declare function computeMaxRepaySharePrice(params: {
44
44
  market: Market;
45
45
  slippageTolerance: bigint;
46
46
  }): bigint;
47
+ /**
48
+ * Computes the maximum supply share price (in RAY, 1e27) for slippage protection.
49
+ *
50
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoSupply`:
51
+ * ```solidity
52
+ * require(suppliedAssets.rDivUp(suppliedShares) <= maxSharePriceE27)
53
+ * ```
54
+ *
55
+ * Caps at {@link MAX_ABSOLUTE_SHARE_PRICE} to prevent absurd values on extreme markets.
56
+ *
57
+ * @param params - Computation parameters.
58
+ * @param params.supplyAssets - The amount of loan assets to supply.
59
+ * @param params.market - The market to compute the maximum supply share price for.
60
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
61
+ * @returns `maxSharePriceE27` in RAY scale (1e27).
62
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
63
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
64
+ */
65
+ export declare function computeMaxSupplySharePrice(params: {
66
+ supplyAssets: bigint;
67
+ market: Market;
68
+ slippageTolerance: bigint;
69
+ }): bigint;
70
+ /**
71
+ * Computes the minimum withdraw share price (in RAY, 1e27) for slippage protection.
72
+ *
73
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoWithdraw`:
74
+ * ```solidity
75
+ * require(withdrawnAssets.rDivDown(withdrawnShares) >= minSharePriceE27)
76
+ * ```
77
+ *
78
+ * Supports both assets and shares modes:
79
+ * - By assets: derives expected shares via `toSupplyShares("Up")` (upper bound, protects the
80
+ * withdrawer against over-burning shares).
81
+ * - By shares: derives expected assets via `toSupplyAssets("Down")` (lower bound, the on-chain
82
+ * amount paid out).
83
+ *
84
+ * Direction is opposite of supply's `maxSharePrice`:
85
+ * - Supply uses `(WAD + slippage)` → upper bound (anti-inflation).
86
+ * - Withdraw uses `(WAD − slippage)` → lower bound (protects withdrawer from receiving too few
87
+ * assets per share burned).
88
+ *
89
+ * @param params - Computation parameters.
90
+ * @param params.withdrawAssets - The amount of assets to withdraw (`0n` when withdrawing by shares).
91
+ * @param params.withdrawShares - The amount of shares to withdraw (`0n` when withdrawing by assets).
92
+ * @param params.market - The market to compute the minimum withdraw share price for.
93
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
94
+ * @returns `minSharePriceE27` in RAY scale (1e27).
95
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
96
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
97
+ */
98
+ export declare function computeMinWithdrawSharePrice(params: {
99
+ withdrawAssets: bigint;
100
+ withdrawShares: bigint;
101
+ market: Market;
102
+ slippageTolerance: bigint;
103
+ }): bigint;
@@ -67,3 +67,83 @@ export function computeMaxRepaySharePrice(params) {
67
67
  const maxSharePrice = MathLib.mulDivUp(assets, MathLib.wToRay(MathLib.WAD + slippageTolerance), shares);
68
68
  return MathLib.min(maxSharePrice, MAX_ABSOLUTE_SHARE_PRICE);
69
69
  }
70
+ /**
71
+ * Computes the maximum supply share price (in RAY, 1e27) for slippage protection.
72
+ *
73
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoSupply`:
74
+ * ```solidity
75
+ * require(suppliedAssets.rDivUp(suppliedShares) <= maxSharePriceE27)
76
+ * ```
77
+ *
78
+ * Caps at {@link MAX_ABSOLUTE_SHARE_PRICE} to prevent absurd values on extreme markets.
79
+ *
80
+ * @param params - Computation parameters.
81
+ * @param params.supplyAssets - The amount of loan assets to supply.
82
+ * @param params.market - The market to compute the maximum supply share price for.
83
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
84
+ * @returns `maxSharePriceE27` in RAY scale (1e27).
85
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
86
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
87
+ */
88
+ export function computeMaxSupplySharePrice(params) {
89
+ const { supplyAssets, market, slippageTolerance } = params;
90
+ if (slippageTolerance >= MathLib.WAD) {
91
+ throw new ExcessiveSlippageToleranceError(slippageTolerance);
92
+ }
93
+ const expectedShares = market.toSupplyShares(supplyAssets, "Down");
94
+ if (expectedShares === 0n) {
95
+ throw new ShareDivideByZeroError(market.params.id);
96
+ }
97
+ const maxSharePrice = MathLib.mulDivUp(supplyAssets, MathLib.wToRay(MathLib.WAD + slippageTolerance), expectedShares);
98
+ return MathLib.min(maxSharePrice, MAX_ABSOLUTE_SHARE_PRICE);
99
+ }
100
+ /**
101
+ * Computes the minimum withdraw share price (in RAY, 1e27) for slippage protection.
102
+ *
103
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoWithdraw`:
104
+ * ```solidity
105
+ * require(withdrawnAssets.rDivDown(withdrawnShares) >= minSharePriceE27)
106
+ * ```
107
+ *
108
+ * Supports both assets and shares modes:
109
+ * - By assets: derives expected shares via `toSupplyShares("Up")` (upper bound, protects the
110
+ * withdrawer against over-burning shares).
111
+ * - By shares: derives expected assets via `toSupplyAssets("Down")` (lower bound, the on-chain
112
+ * amount paid out).
113
+ *
114
+ * Direction is opposite of supply's `maxSharePrice`:
115
+ * - Supply uses `(WAD + slippage)` → upper bound (anti-inflation).
116
+ * - Withdraw uses `(WAD − slippage)` → lower bound (protects withdrawer from receiving too few
117
+ * assets per share burned).
118
+ *
119
+ * @param params - Computation parameters.
120
+ * @param params.withdrawAssets - The amount of assets to withdraw (`0n` when withdrawing by shares).
121
+ * @param params.withdrawShares - The amount of shares to withdraw (`0n` when withdrawing by assets).
122
+ * @param params.market - The market to compute the minimum withdraw share price for.
123
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
124
+ * @returns `minSharePriceE27` in RAY scale (1e27).
125
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
126
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
127
+ */
128
+ export function computeMinWithdrawSharePrice(params) {
129
+ const { withdrawAssets, withdrawShares, market, slippageTolerance } = params;
130
+ if (slippageTolerance >= MathLib.WAD) {
131
+ throw new ExcessiveSlippageToleranceError(slippageTolerance);
132
+ }
133
+ let assets;
134
+ let shares;
135
+ if (withdrawShares > 0n) {
136
+ assets = market.toSupplyAssets(withdrawShares, "Down");
137
+ shares = withdrawShares;
138
+ }
139
+ else {
140
+ assets = withdrawAssets;
141
+ shares = market.toSupplyShares(withdrawAssets, "Up");
142
+ }
143
+ // Dust shares can round to `assets === 0n` here, which would make
144
+ // `minSharePriceE27 = 0` and silently nullify the on-chain slippage cap.
145
+ if (shares === 0n || assets === 0n) {
146
+ throw new ShareDivideByZeroError(market.params.id);
147
+ }
148
+ return MathLib.mulDivDown(assets, MathLib.wToRay(MathLib.WAD - slippageTolerance), shares);
149
+ }
@@ -1,6 +1,8 @@
1
1
  import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
3
  import { type VaultReallocation } from "../types/index.js";
4
+ /** @internal */
5
+ export declare const compareMarketIds: (idA: MarketId, idB: MarketId) => 0 | 1 | -1;
4
6
  /**
5
7
  * Asserts that the client has a connected account AND that it matches
6
8
  * the provided user address.
@@ -67,14 +69,16 @@ export declare const validatePositionHealth: (params: {
67
69
  */
68
70
  export declare const validateChainId: (clientChainId: number | undefined, expectedChainId: number) => void;
69
71
  /**
70
- * Validates that the given collateral token is the chain's wrapped native token.
71
- * Throws {@link ChainWNativeMissingError} if wNative is not configured for the chain.
72
- * Throws {@link NativeAmountOnNonWNativeCollateralError} if collateral is not wNative.
72
+ * Validates that the given asset is the chain's wrapped native token.
73
+ * Used by any action that may receive `nativeAmount` — the SDK wraps native
74
+ * into wNative, so the target asset must be wNative for the action to succeed.
73
75
  *
74
76
  * @param chainId - The chain to look up wNative on.
75
- * @param collateralToken - The market's collateral token address.
77
+ * @param asset - The asset address to check (collateral, loan, vault asset…).
78
+ * @throws {ChainWNativeMissingError} if wNative is not configured for the chain.
79
+ * @throws {NativeAmountOnNonWNativeAssetError} if the asset is not wNative.
76
80
  */
77
- export declare const validateNativeCollateral: (chainId: number, collateralToken: Address) => void;
81
+ export declare const validateNativeAsset: (chainId: number, asset: Address) => void;
78
82
  /**
79
83
  * Validates that the resulting position stays within the safe LTV threshold
80
84
  * (LLTV minus buffer) after withdrawing collateral.
@@ -142,11 +146,12 @@ export declare const validateRepayParams: (params: {
142
146
  * - `fee` must be non-negative.
143
147
  * - `withdrawals` must be non-empty.
144
148
  * - Every withdrawal `amount` must be strictly positive.
145
- * - No withdrawal may target `targetMarketId` (the borrow market).
149
+ * - No withdrawal may target `targetMarketId` (the operation's target market — the market being
150
+ * borrowed from for `borrow`, or being withdrawn from for `withdraw`).
146
151
  * - Withdrawal market IDs must be strictly ascending (required by `PublicAllocator.reallocateTo`).
147
152
  *
148
153
  * @param reallocations - The reallocations to validate.
149
- * @param targetMarketId - The ID of the market being borrowed from. No withdrawal may reference this market.
154
+ * @param targetMarketId - The ID of the operation's target market. No withdrawal may reference this market.
150
155
  */
151
156
  export declare const validateReallocations: (reallocations: readonly VaultReallocation[], targetMarketId: MarketId) => void;
152
157
  /**
@@ -158,3 +163,31 @@ export declare const validateReallocations: (reallocations: readonly VaultReallo
158
163
  * @param slippageTolerance - The slippage tolerance in WAD.
159
164
  */
160
165
  export declare const validateSlippageTolerance: (slippageTolerance: bigint) => void;
166
+ /**
167
+ * Validates that the withdraw assets do not exceed the user's supplied assets in the market.
168
+ *
169
+ * @param params - Validation parameters.
170
+ * @param params.positionData - The current accrual position.
171
+ * @param params.withdrawAssets - The amount of assets to withdraw.
172
+ * @param params.marketId - The market identifier (for error messages).
173
+ * @throws {WithdrawExceedsSupplyError} when `withdrawAssets > positionData.supplyAssets`.
174
+ */
175
+ export declare const validateWithdrawAmount: (params: {
176
+ positionData: AccrualPosition;
177
+ withdrawAssets: bigint;
178
+ marketId: MarketId;
179
+ }) => void;
180
+ /**
181
+ * Validates that the withdraw shares do not exceed the user's owned supply shares in the market.
182
+ *
183
+ * @param params - Validation parameters.
184
+ * @param params.positionData - The current accrual position.
185
+ * @param params.withdrawShares - The amount of shares to withdraw.
186
+ * @param params.marketId - The market identifier (for error messages).
187
+ * @throws {WithdrawSharesExceedSupplyError} when `withdrawShares > positionData.supplyShares`.
188
+ */
189
+ export declare const validateWithdrawShares: (params: {
190
+ positionData: AccrualPosition;
191
+ withdrawShares: bigint;
192
+ marketId: MarketId;
193
+ }) => void;