@morpho-org/morpho-sdk 2.0.0 → 3.0.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 (202) 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/repay.d.ts +2 -0
  8. package/lib/cjs/actions/marketV1/repay.js +7 -8
  9. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  10. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.js +9 -10
  11. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +2 -0
  12. package/lib/cjs/actions/marketV1/supplyCollateral.js +11 -12
  13. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  14. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +13 -14
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +2 -2
  16. package/lib/cjs/actions/requirements/getRequirementsAction.d.ts +28 -4
  17. package/lib/cjs/actions/requirements/getRequirementsAction.js +28 -4
  18. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  19. package/lib/cjs/actions/requirements/index.d.ts +1 -0
  20. package/lib/cjs/actions/requirements/index.js +1 -0
  21. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -0
  22. package/lib/cjs/actions/vaultV1/deposit.js +13 -14
  23. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -0
  24. package/lib/cjs/actions/vaultV1/migrateToV2.js +11 -9
  25. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -0
  26. package/lib/cjs/actions/vaultV2/deposit.js +13 -14
  27. package/lib/cjs/addresses.d.ts +2 -0
  28. package/lib/cjs/addresses.js +18 -0
  29. package/lib/cjs/augment/AccrualPosition.d.ts +9 -0
  30. package/lib/cjs/augment/AccrualPosition.js +8 -0
  31. package/lib/cjs/augment/AccrualVault.d.ts +8 -0
  32. package/lib/cjs/augment/AccrualVault.js +7 -0
  33. package/lib/cjs/augment/Holding.d.ts +8 -0
  34. package/lib/cjs/augment/Holding.js +7 -0
  35. package/lib/cjs/augment/Market.d.ts +8 -0
  36. package/lib/cjs/augment/Market.js +7 -0
  37. package/lib/cjs/augment/MarketParams.d.ts +8 -0
  38. package/lib/cjs/augment/MarketParams.js +7 -0
  39. package/lib/cjs/augment/Position.d.ts +8 -0
  40. package/lib/cjs/augment/Position.js +7 -0
  41. package/lib/cjs/augment/Token.d.ts +8 -0
  42. package/lib/cjs/augment/Token.js +7 -0
  43. package/lib/cjs/augment/User.d.ts +8 -0
  44. package/lib/cjs/augment/User.js +7 -0
  45. package/lib/cjs/augment/Vault.d.ts +8 -0
  46. package/lib/cjs/augment/Vault.js +7 -0
  47. package/lib/cjs/augment/VaultConfig.d.ts +8 -0
  48. package/lib/cjs/augment/VaultConfig.js +7 -0
  49. package/lib/cjs/augment/VaultMarketAllocation.d.ts +8 -0
  50. package/lib/cjs/augment/VaultMarketAllocation.js +7 -0
  51. package/lib/cjs/augment/VaultMarketConfig.d.ts +8 -0
  52. package/lib/cjs/augment/VaultMarketConfig.js +7 -0
  53. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  54. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +8 -0
  55. package/lib/cjs/augment/VaultUser.d.ts +8 -0
  56. package/lib/cjs/augment/VaultUser.js +7 -0
  57. package/lib/cjs/augment.d.ts +14 -0
  58. package/lib/cjs/augment.js +16 -0
  59. package/lib/cjs/bundler/actions.d.ts +555 -0
  60. package/lib/cjs/bundler/actions.js +953 -0
  61. package/lib/cjs/bundler/index.d.ts +2 -0
  62. package/lib/cjs/bundler/index.js +18 -0
  63. package/lib/cjs/bundler/types.d.ts +181 -0
  64. package/lib/cjs/bundler/types.js +2 -0
  65. package/lib/cjs/constants.d.ts +3 -0
  66. package/lib/cjs/constants.js +32 -0
  67. package/lib/cjs/entities/index.d.ts +6 -3
  68. package/lib/cjs/entities/index.js +41 -17
  69. package/lib/cjs/entities/marketV1/marketV1.d.ts +45 -11
  70. package/lib/cjs/entities/marketV1/marketV1.js +45 -23
  71. package/lib/cjs/entities/reallocationData.d.ts +193 -0
  72. package/lib/cjs/entities/reallocationData.js +406 -0
  73. package/lib/cjs/entities/vaultV1/vaultV1.js +6 -2
  74. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -1
  75. package/lib/cjs/errors.d.ts +2 -0
  76. package/lib/cjs/errors.js +18 -0
  77. package/lib/cjs/fetch.d.ts +1 -0
  78. package/lib/cjs/fetch.js +30 -0
  79. package/lib/cjs/format.d.ts +2 -0
  80. package/lib/cjs/format.js +22 -0
  81. package/lib/cjs/helpers/computeReallocations.d.ts +48 -8
  82. package/lib/cjs/helpers/computeReallocations.js +120 -32
  83. package/lib/cjs/helpers/constant.d.ts +17 -0
  84. package/lib/cjs/helpers/constant.js +30 -1
  85. package/lib/cjs/helpers/index.d.ts +1 -0
  86. package/lib/cjs/helpers/index.js +9 -1
  87. package/lib/cjs/helpers/metadata.d.ts +10 -0
  88. package/lib/cjs/helpers/metadata.js +20 -1
  89. package/lib/cjs/helpers/validate.d.ts +2 -0
  90. package/lib/cjs/helpers/validate.js +14 -2
  91. package/lib/cjs/index.d.ts +0 -1
  92. package/lib/cjs/index.js +0 -1
  93. package/lib/cjs/types/client.d.ts +1 -1
  94. package/lib/cjs/types/error.d.ts +91 -1
  95. package/lib/cjs/types/error.js +126 -1
  96. package/lib/cjs/types/sharedLiquidity.d.ts +43 -3
  97. package/lib/cjs/types.d.ts +3 -0
  98. package/lib/cjs/types.js +17 -0
  99. package/lib/cjs/utils.d.ts +9 -0
  100. package/lib/cjs/utils.js +65 -0
  101. package/lib/esm/abis.d.ts +2816 -0
  102. package/lib/esm/abis.js +1922 -0
  103. package/lib/esm/actions/index.d.ts +3 -0
  104. package/lib/esm/actions/marketV1/borrow.js +2 -5
  105. package/lib/esm/actions/marketV1/buildReallocationActions.d.ts +2 -3
  106. package/lib/esm/actions/marketV1/buildReallocationActions.js +1 -2
  107. package/lib/esm/actions/marketV1/repay.d.ts +2 -0
  108. package/lib/esm/actions/marketV1/repay.js +4 -5
  109. package/lib/esm/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  110. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +4 -5
  111. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +2 -0
  112. package/lib/esm/actions/marketV1/supplyCollateral.js +4 -5
  113. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  114. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +4 -5
  115. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +1 -1
  116. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +28 -4
  117. package/lib/esm/actions/requirements/getRequirementsAction.js +29 -5
  118. package/lib/esm/actions/requirements/getRequirementsApproval.js +1 -1
  119. package/lib/esm/actions/requirements/index.d.ts +1 -0
  120. package/lib/esm/actions/requirements/index.js +1 -0
  121. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -0
  122. package/lib/esm/actions/vaultV1/deposit.js +3 -4
  123. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -0
  124. package/lib/esm/actions/vaultV1/migrateToV2.js +3 -1
  125. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -0
  126. package/lib/esm/actions/vaultV2/deposit.js +3 -4
  127. package/lib/esm/addresses.d.ts +2 -0
  128. package/lib/esm/addresses.js +1 -0
  129. package/lib/esm/augment/AccrualPosition.d.ts +9 -0
  130. package/lib/esm/augment/AccrualPosition.js +5 -0
  131. package/lib/esm/augment/AccrualVault.d.ts +8 -0
  132. package/lib/esm/augment/AccrualVault.js +4 -0
  133. package/lib/esm/augment/Holding.d.ts +8 -0
  134. package/lib/esm/augment/Holding.js +4 -0
  135. package/lib/esm/augment/Market.d.ts +8 -0
  136. package/lib/esm/augment/Market.js +4 -0
  137. package/lib/esm/augment/MarketParams.d.ts +8 -0
  138. package/lib/esm/augment/MarketParams.js +4 -0
  139. package/lib/esm/augment/Position.d.ts +8 -0
  140. package/lib/esm/augment/Position.js +4 -0
  141. package/lib/esm/augment/Token.d.ts +8 -0
  142. package/lib/esm/augment/Token.js +4 -0
  143. package/lib/esm/augment/User.d.ts +8 -0
  144. package/lib/esm/augment/User.js +4 -0
  145. package/lib/esm/augment/Vault.d.ts +8 -0
  146. package/lib/esm/augment/Vault.js +4 -0
  147. package/lib/esm/augment/VaultConfig.d.ts +8 -0
  148. package/lib/esm/augment/VaultConfig.js +4 -0
  149. package/lib/esm/augment/VaultMarketAllocation.d.ts +8 -0
  150. package/lib/esm/augment/VaultMarketAllocation.js +4 -0
  151. package/lib/esm/augment/VaultMarketConfig.d.ts +8 -0
  152. package/lib/esm/augment/VaultMarketConfig.js +4 -0
  153. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  154. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +5 -0
  155. package/lib/esm/augment/VaultUser.d.ts +8 -0
  156. package/lib/esm/augment/VaultUser.js +4 -0
  157. package/lib/esm/augment.d.ts +14 -0
  158. package/lib/esm/augment.js +14 -0
  159. package/lib/esm/bundler/actions.d.ts +555 -0
  160. package/lib/esm/bundler/actions.js +950 -0
  161. package/lib/esm/bundler/index.d.ts +2 -0
  162. package/lib/esm/bundler/index.js +2 -0
  163. package/lib/esm/bundler/types.d.ts +181 -0
  164. package/lib/esm/bundler/types.js +1 -0
  165. package/lib/esm/constants.d.ts +3 -0
  166. package/lib/esm/constants.js +3 -0
  167. package/lib/esm/entities/index.d.ts +6 -3
  168. package/lib/esm/entities/index.js +5 -3
  169. package/lib/esm/entities/marketV1/marketV1.d.ts +45 -11
  170. package/lib/esm/entities/marketV1/marketV1.js +46 -24
  171. package/lib/esm/entities/reallocationData.d.ts +193 -0
  172. package/lib/esm/entities/reallocationData.js +402 -0
  173. package/lib/esm/entities/vaultV1/vaultV1.js +6 -2
  174. package/lib/esm/entities/vaultV2/vaultV2.js +6 -1
  175. package/lib/esm/errors.d.ts +2 -0
  176. package/lib/esm/errors.js +1 -0
  177. package/lib/esm/fetch.d.ts +1 -0
  178. package/lib/esm/fetch.js +1 -0
  179. package/lib/esm/format.d.ts +2 -0
  180. package/lib/esm/format.js +1 -0
  181. package/lib/esm/helpers/computeReallocations.d.ts +48 -8
  182. package/lib/esm/helpers/computeReallocations.js +119 -31
  183. package/lib/esm/helpers/constant.d.ts +17 -0
  184. package/lib/esm/helpers/constant.js +30 -1
  185. package/lib/esm/helpers/index.d.ts +1 -0
  186. package/lib/esm/helpers/index.js +1 -0
  187. package/lib/esm/helpers/metadata.d.ts +10 -0
  188. package/lib/esm/helpers/metadata.js +20 -1
  189. package/lib/esm/helpers/validate.d.ts +2 -0
  190. package/lib/esm/helpers/validate.js +12 -1
  191. package/lib/esm/index.d.ts +0 -1
  192. package/lib/esm/index.js +0 -1
  193. package/lib/esm/types/client.d.ts +1 -1
  194. package/lib/esm/types/error.d.ts +91 -1
  195. package/lib/esm/types/error.js +118 -0
  196. package/lib/esm/types/sharedLiquidity.d.ts +43 -3
  197. package/lib/esm/types.d.ts +3 -0
  198. package/lib/esm/types.js +1 -0
  199. package/lib/esm/utils.d.ts +9 -0
  200. package/lib/esm/utils.js +7 -0
  201. package/package.json +121 -14
  202. package/src/index.ts +0 -1
@@ -1,23 +1,63 @@
1
1
  import { type MarketId } from "@morpho-org/blue-sdk";
2
- import type { SimulationState } from "@morpho-org/simulation-sdk";
2
+ import type { ReallocationData } from "../entities/reallocationData.js";
3
3
  import { type ReallocationComputeOptions, type VaultReallocation } from "../types/index.js";
4
4
  /**
5
5
  * Computes vault reallocations for a borrow operation on a target market.
6
6
  *
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.
7
+ * First attempts "friendly" reallocations respecting withdrawal utilization
8
+ * targets, then falls back to aggressive reallocations (100% withdrawal
9
+ * utilization) if liquidity is still insufficient.
11
10
  *
12
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
11
+ * @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.
12
+ * @param params.reallocationData - The local state containing market, vault, and position data.
13
13
  * @param params.marketId - The target market to reallocate liquidity into.
14
14
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
15
  * @param params.options - Optional reallocation computation options.
16
16
  * @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.
17
+ * @throws {InsufficientSharedLiquidityError} when 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.
18
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
19
+ * @example
20
+ * ```ts
21
+ * import { createPublicClient, http, parseUnits } from "viem";
22
+ * import { mainnet } from "viem/chains";
23
+ * import { markets, vaults } from "@morpho-org/morpho-test";
24
+ * import {
25
+ * computeReallocations,
26
+ * morphoViemExtension,
27
+ * } from "@morpho-org/morpho-sdk";
28
+ *
29
+ * const client = createPublicClient({
30
+ * chain: mainnet,
31
+ * transport: http(),
32
+ * }).extend(morphoViemExtension());
33
+ *
34
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
35
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
36
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
37
+ * const block = await client.getBlock();
38
+ * const reallocationData = await market.getReallocationData({
39
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
40
+ * block: { number: block.number, timestamp: block.timestamp },
41
+ * });
42
+ * const borrowAmount = parseUnits("1000", 6);
43
+ * const reallocations = computeReallocations({
44
+ * reallocationData,
45
+ * marketId: marketParams.id,
46
+ * borrowAmount,
47
+ * options: { timestamp: block.timestamp },
48
+ * });
49
+ * const positionData = await market.getPositionData(userAddress);
50
+ * const borrow = market.borrow({
51
+ * userAddress,
52
+ * amount: borrowAmount,
53
+ * positionData,
54
+ * reallocations,
55
+ * });
56
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
57
+ * ```
18
58
  */
19
59
  export declare const computeReallocations: ({ reallocationData: data, marketId, borrowAmount, options, }: {
20
- readonly reallocationData: SimulationState;
60
+ readonly reallocationData: ReallocationData;
21
61
  readonly marketId: MarketId;
22
62
  readonly borrowAmount: bigint;
23
63
  readonly options?: ReallocationComputeOptions;
@@ -1,25 +1,119 @@
1
1
  import { MarketUtils, MathLib } from "@morpho-org/blue-sdk";
2
- import { DEFAULT_SUPPLY_TARGET_UTILIZATION } from "@morpho-org/bundler-sdk-viem";
3
2
  import { InsufficientSharedLiquidityError, MissingPublicAllocatorConfigError, } 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
57
  * Computes vault reallocations for a borrow operation 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
+ * @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.
64
+ * @param params.reallocationData - The local state containing market, vault, and position data.
13
65
  * @param params.marketId - The target market to reallocate liquidity into.
14
66
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
67
  * @param params.options - Optional reallocation computation options.
16
68
  * @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.
69
+ * @throws {InsufficientSharedLiquidityError} when 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.
70
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
71
+ * @example
72
+ * ```ts
73
+ * import { createPublicClient, http, parseUnits } from "viem";
74
+ * import { mainnet } from "viem/chains";
75
+ * import { markets, vaults } from "@morpho-org/morpho-test";
76
+ * import {
77
+ * computeReallocations,
78
+ * morphoViemExtension,
79
+ * } from "@morpho-org/morpho-sdk";
80
+ *
81
+ * const client = createPublicClient({
82
+ * chain: mainnet,
83
+ * transport: http(),
84
+ * }).extend(morphoViemExtension());
85
+ *
86
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
87
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
88
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
89
+ * const block = await client.getBlock();
90
+ * const reallocationData = await market.getReallocationData({
91
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
92
+ * block: { number: block.number, timestamp: block.timestamp },
93
+ * });
94
+ * const borrowAmount = parseUnits("1000", 6);
95
+ * const reallocations = computeReallocations({
96
+ * reallocationData,
97
+ * marketId: marketParams.id,
98
+ * borrowAmount,
99
+ * options: { timestamp: block.timestamp },
100
+ * });
101
+ * const positionData = await market.getPositionData(userAddress);
102
+ * const borrow = market.borrow({
103
+ * userAddress,
104
+ * amount: borrowAmount,
105
+ * positionData,
106
+ * reallocations,
107
+ * });
108
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
109
+ * ```
18
110
  */
19
111
  export const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
20
112
  if (options?.enabled === false)
21
113
  return [];
22
- const market = data.getMarket(marketId).accrueInterest(data.block.timestamp);
114
+ // ReallocationData does not retain the fetch block; pass that block timestamp
115
+ // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
116
+ const market = data.getMarket(marketId).accrueInterest(options?.timestamp);
23
117
  const newTotalBorrowAssets = market.totalBorrowAssets + borrowAmount;
24
118
  const newTotalSupplyAssets = market.totalSupplyAssets;
25
119
  const supplyTargetUtilization = options?.supplyTargetUtilization?.[market.params.id] ??
@@ -55,27 +149,20 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
55
149
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
56
150
  ? newTotalBorrowAssets - newTotalSupplyAssets
57
151
  : 0n;
58
- // Group withdrawals by vault, capping total at requiredAssets.
59
- const reallocationsMap = {};
152
+ const reallocations = [];
60
153
  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);
154
+ let remainingRequiredAssets = requiredAssets;
155
+ for (const group of groupWithdrawalsByVault(withdrawals)) {
156
+ const reallocatedAssets = MathLib.min(group.totalAssets, remainingRequiredAssets);
65
157
  if (reallocatedAssets <= 0n)
66
158
  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;
159
+ reallocations.push({
160
+ vault: group.vault,
161
+ withdrawals: capVaultWithdrawals(group.withdrawals, reallocatedAssets),
162
+ });
163
+ remainingRequiredAssets -= reallocatedAssets;
77
164
  totalReallocated += reallocatedAssets;
78
- if (requiredAssets === 0n)
165
+ if (remainingRequiredAssets === 0n)
79
166
  break;
80
167
  }
81
168
  // Refuse fee-bearing partial plans for an unreachable borrow.
@@ -87,10 +174,10 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
87
174
  });
88
175
  }
89
176
  // Transform into VaultReallocation[] format.
90
- return Object.entries(reallocationsMap)
91
- .filter(([, vaultWithdrawals]) => vaultWithdrawals.length > 0)
92
- .map(([vault, vaultWithdrawals]) => ({
93
- vault: vault,
177
+ return reallocations
178
+ .filter(({ withdrawals: vaultWithdrawals }) => vaultWithdrawals.length > 0)
179
+ .map(({ vault, withdrawals: vaultWithdrawals }) => ({
180
+ vault,
94
181
  fee: (() => {
95
182
  const config = data.getVault(vault).publicAllocatorConfig;
96
183
  if (config == null) {
@@ -99,8 +186,9 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
99
186
  return config.fee;
100
187
  })(),
101
188
  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)
189
+ // Reallocation withdrawals must be sorted by market id in ascending
190
+ // order. Normalize first because `MarketId` can be mixed-case hex.
191
+ .sort(({ id: idA }, { id: idB }) => compareMarketIds(idA, idB))
104
192
  .map(({ id, assets }) => ({
105
193
  marketParams: data.getMarket(id).params,
106
194
  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
4
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
4
5
  export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } 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
4
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
4
5
  export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./validate.js";
@@ -9,6 +9,16 @@ import type { Metadata } from "../types/index.js";
9
9
  * The function ensures that the transaction data is correctly formatted
10
10
  * and includes optional metadata elements if provided.
11
11
  *
12
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
13
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
14
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
15
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
16
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
17
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
18
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
19
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
20
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
21
+ *
12
22
  * @param {Object} tx - The original transaction object.
13
23
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
14
24
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -9,6 +9,16 @@ import { concatHex, isHex, numberToHex } from "viem";
9
9
  * The function ensures that the transaction data is correctly formatted
10
10
  * and includes optional metadata elements if provided.
11
11
  *
12
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
13
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
14
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
15
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
16
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
17
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
18
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
19
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
20
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
21
+ *
12
22
  * @param {Object} tx - The original transaction object.
13
23
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
14
24
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -31,11 +41,20 @@ export function addTransactionMetadata(tx, metadata) {
31
41
  concatItems.push(numberToHex(Time.timestamp(), { size: 4 }));
32
42
  }
33
43
  try {
34
- const origin = metadata.origin.replace(/^(?!0x)/, "");
44
+ // Strip a leading "0x" / "0X" case-insensitively so callers can pass
45
+ // "cafe", "0xcafe", or "0Xcafe" — all produce the same 4-byte appended
46
+ // origin. The case-insensitive form prevents "0Xcafe" from falling
47
+ // through to `isHex("0x0Xcafe")` and being silently dropped.
48
+ const origin = metadata.origin.replace(/^0x/i, "");
35
49
  if (!isHex(`0x${origin}`))
36
50
  throw Error("Calldata origin must consists of only hex characters");
37
51
  if (origin.length > 8)
38
52
  throw Error("Calldata origin must be at most 8 characters long");
53
+ // Reject odd-length raw fragments. viem's `concatHex` would pad the
54
+ // stray nibble to a whole byte at broadcast, corrupting the trailing
55
+ // analytics byte on-chain.
56
+ if (origin.length % 2 !== 0)
57
+ throw Error("Calldata origin must have an even number of hex characters");
39
58
  concatItems.push(`0x${origin}`);
40
59
  }
41
60
  catch (error) {
@@ -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.
@@ -3,6 +3,16 @@ import { isDefined } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
4
  import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, EmptyReallocationWithdrawalsError, ExcessiveSlippageToleranceError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, MutuallyExclusiveRepayAmountsError, NativeAmountOnNonWNativeCollateralError, NegativeReallocationFeeError, NegativeSlippageToleranceError, NonPositiveReallocationAmountError, NonPositiveRepayAmountError, NonPositiveRepayMaxSharePriceError, NonPositiveTransferAmountError, ReallocationWithdrawalOnTargetMarketError, RepayExceedsDebtError, RepaySharesExceedDebtError, TransferAmountNotEqualToAssetsError, UnsortedReallocationWithdrawalsError, WithdrawExceedsCollateralError, WithdrawMakesPositionUnhealthyError, } from "../types/index.js";
5
5
  import { DEFAULT_LLTV_BUFFER, MAX_SLIPPAGE_TOLERANCE } from "./constant.js";
6
+ /** @internal */
7
+ export const compareMarketIds = (idA, idB) => {
8
+ const normalizedIdA = idA.toLowerCase();
9
+ const normalizedIdB = idB.toLowerCase();
10
+ if (normalizedIdA > normalizedIdB)
11
+ return 1;
12
+ if (normalizedIdA < normalizedIdB)
13
+ return -1;
14
+ return 0;
15
+ };
6
16
  /**
7
17
  * Asserts that the client has a connected account AND that it matches
8
18
  * the provided user address.
@@ -252,7 +262,8 @@ export const validateReallocations = (reallocations, targetMarketId) => {
252
262
  if (w.marketParams.id === targetMarketId) {
253
263
  throw new ReallocationWithdrawalOnTargetMarketError(r.vault, w.marketParams.id);
254
264
  }
255
- if (prevId !== undefined && w.marketParams.id <= prevId) {
265
+ if (prevId !== undefined &&
266
+ compareMarketIds(w.marketParams.id, prevId) <= 0) {
256
267
  throw new UnsortedReallocationWithdrawalsError(r.vault, w.marketParams.id);
257
268
  }
258
269
  prevId = w.marketParams.id;
@@ -1,5 +1,4 @@
1
1
  export * from "./actions/index.js";
2
2
  export * from "./client/index.js";
3
- export * from "./entities/index.js";
4
3
  export * from "./helpers/index.js";
5
4
  export * from "./types/index.js";
package/lib/esm/index.js CHANGED
@@ -1,5 +1,4 @@
1
1
  export * from "./actions/index.js";
2
2
  export * from "./client/index.js";
3
- export * from "./entities/index.js";
4
3
  export * from "./helpers/index.js";
5
4
  export * from "./types/index.js";
@@ -1,6 +1,6 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address, Client } from "viem";
3
- import type { MarketV1Actions, VaultV1Actions, VaultV2Actions } from "../entities/index.js";
3
+ import type { MarketV1Actions, VaultV1Actions, VaultV2Actions } from "../actions/index.js";
4
4
  import type { Metadata } from "./index.js";
5
5
  /**
6
6
  * Structural contract every concrete `MorphoClient` implementation satisfies. Carries the viem
@@ -1,5 +1,49 @@
1
- import type { MarketId } from "@morpho-org/blue-sdk";
1
+ import { type MarketId, UnknownDataError } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
+ /**
4
+ * Typed errors thrown while encoding supported Bundler3 actions.
5
+ *
6
+ * @remarks
7
+ * Import these classes through `@morpho-org/morpho-sdk` when handling
8
+ * failures from `BundlerAction`.
9
+ */
10
+ export declare namespace BundlerErrors {
11
+ /**
12
+ * Thrown when an action that requires an offchain signature is encoded before
13
+ * the signature has been attached.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { BundlerErrors } from "@morpho-org/morpho-sdk";
18
+ *
19
+ * if (error instanceof BundlerErrors.MissingSignature) {
20
+ * // Attach the missing permit or Permit2 signature, then encode again.
21
+ * }
22
+ * ```
23
+ */
24
+ class MissingSignature extends Error {
25
+ constructor();
26
+ }
27
+ /**
28
+ * Thrown when an action is unsupported on the requested chain.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { BundlerErrors } from "@morpho-org/morpho-sdk";
33
+ *
34
+ * if (error instanceof BundlerErrors.UnexpectedAction) {
35
+ * // Remove or replace the action for the selected chain.
36
+ * }
37
+ * ```
38
+ */
39
+ class UnexpectedAction extends Error {
40
+ /**
41
+ * @param type - Unsupported Bundler3 action discriminator or name.
42
+ * @param chainId - Chain where the action was requested.
43
+ */
44
+ constructor(type: string, chainId: number);
45
+ }
46
+ }
3
47
  /** Thrown when an asset amount is required to be positive but is zero or negative. */
4
48
  export declare class NonPositiveAssetAmountError extends Error {
5
49
  constructor(origin: Address);
@@ -52,6 +96,10 @@ export declare class DepositAmountMismatchError extends Error {
52
96
  export declare class DepositAssetMismatchError extends Error {
53
97
  constructor(depositAsset: Address, signatureAsset: Address);
54
98
  }
99
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
100
+ export declare class Permit2ExpirationMissingError extends Error {
101
+ constructor();
102
+ }
55
103
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
56
104
  export declare class NativeAmountOnNonWNativeVaultError extends Error {
57
105
  constructor(vaultAsset: Address, wNative: Address);
@@ -192,6 +240,12 @@ export declare class RepaySharesExceedDebtError extends Error {
192
240
  export declare class MissingPublicAllocatorConfigError extends Error {
193
241
  constructor(vault: string);
194
242
  }
243
+ /** Thrown when a reallocation attempts to use a disabled vault market. */
244
+ export declare class DisabledReallocationMarketError extends Error {
245
+ readonly vault: Address;
246
+ readonly marketId: MarketId;
247
+ constructor(vault: Address, marketId: MarketId);
248
+ }
195
249
  /**
196
250
  * Thrown when shared liquidity selected by `computeReallocations` cannot cover
197
251
  * the absolute borrow shortfall on the target market — the resulting
@@ -211,6 +265,42 @@ export declare class InsufficientSharedLiquidityError extends Error {
211
265
  readonly available: bigint;
212
266
  });
213
267
  }
268
+ /** Thrown when reallocation state does not contain a requested market. */
269
+ export declare class UnknownReallocationMarketError extends UnknownDataError {
270
+ readonly marketId: MarketId;
271
+ /**
272
+ * @param marketId - Missing market id.
273
+ */
274
+ constructor(marketId: MarketId);
275
+ }
276
+ /** Thrown when reallocation state does not contain a requested vault. */
277
+ export declare class UnknownReallocationVaultError extends UnknownDataError {
278
+ readonly vault: Address;
279
+ /**
280
+ * @param vault - Missing vault address.
281
+ */
282
+ constructor(vault: Address);
283
+ }
284
+ /** Thrown when reallocation state does not contain a requested vault-market config. */
285
+ export declare class UnknownReallocationVaultMarketConfigError extends UnknownDataError {
286
+ readonly vault: Address;
287
+ readonly marketId: MarketId;
288
+ /**
289
+ * @param vault - Vault address for the missing config.
290
+ * @param marketId - Market id for the missing config.
291
+ */
292
+ constructor(vault: Address, marketId: MarketId);
293
+ }
294
+ /** Thrown when reallocation state does not contain a requested market position. */
295
+ export declare class UnknownReallocationPositionError extends UnknownDataError {
296
+ readonly user: Address;
297
+ readonly marketId: MarketId;
298
+ /**
299
+ * @param user - Position owner address.
300
+ * @param marketId - Market id for the missing position.
301
+ */
302
+ constructor(user: Address, marketId: MarketId);
303
+ }
214
304
  /** Thrown when a market borrow's `minSharePrice` slippage bound is negative. */
215
305
  export declare class NonPositiveMinBorrowSharePriceError extends Error {
216
306
  constructor(market: string);