@morpho-org/morpho-sdk 2.1.1 → 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 (188) 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 +1 -1
  17. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  18. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -0
  19. package/lib/cjs/actions/vaultV1/deposit.js +13 -14
  20. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -0
  21. package/lib/cjs/actions/vaultV1/migrateToV2.js +11 -9
  22. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -0
  23. package/lib/cjs/actions/vaultV2/deposit.js +13 -14
  24. package/lib/cjs/addresses.d.ts +2 -0
  25. package/lib/cjs/addresses.js +18 -0
  26. package/lib/cjs/augment/AccrualPosition.d.ts +9 -0
  27. package/lib/cjs/augment/AccrualPosition.js +8 -0
  28. package/lib/cjs/augment/AccrualVault.d.ts +8 -0
  29. package/lib/cjs/augment/AccrualVault.js +7 -0
  30. package/lib/cjs/augment/Holding.d.ts +8 -0
  31. package/lib/cjs/augment/Holding.js +7 -0
  32. package/lib/cjs/augment/Market.d.ts +8 -0
  33. package/lib/cjs/augment/Market.js +7 -0
  34. package/lib/cjs/augment/MarketParams.d.ts +8 -0
  35. package/lib/cjs/augment/MarketParams.js +7 -0
  36. package/lib/cjs/augment/Position.d.ts +8 -0
  37. package/lib/cjs/augment/Position.js +7 -0
  38. package/lib/cjs/augment/Token.d.ts +8 -0
  39. package/lib/cjs/augment/Token.js +7 -0
  40. package/lib/cjs/augment/User.d.ts +8 -0
  41. package/lib/cjs/augment/User.js +7 -0
  42. package/lib/cjs/augment/Vault.d.ts +8 -0
  43. package/lib/cjs/augment/Vault.js +7 -0
  44. package/lib/cjs/augment/VaultConfig.d.ts +8 -0
  45. package/lib/cjs/augment/VaultConfig.js +7 -0
  46. package/lib/cjs/augment/VaultMarketAllocation.d.ts +8 -0
  47. package/lib/cjs/augment/VaultMarketAllocation.js +7 -0
  48. package/lib/cjs/augment/VaultMarketConfig.d.ts +8 -0
  49. package/lib/cjs/augment/VaultMarketConfig.js +7 -0
  50. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  51. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +8 -0
  52. package/lib/cjs/augment/VaultUser.d.ts +8 -0
  53. package/lib/cjs/augment/VaultUser.js +7 -0
  54. package/lib/cjs/augment.d.ts +14 -0
  55. package/lib/cjs/augment.js +16 -0
  56. package/lib/cjs/bundler/actions.d.ts +555 -0
  57. package/lib/cjs/bundler/actions.js +953 -0
  58. package/lib/cjs/bundler/index.d.ts +2 -0
  59. package/lib/cjs/bundler/index.js +18 -0
  60. package/lib/cjs/bundler/types.d.ts +181 -0
  61. package/lib/cjs/bundler/types.js +2 -0
  62. package/lib/cjs/constants.d.ts +3 -0
  63. package/lib/cjs/constants.js +32 -0
  64. package/lib/cjs/entities/index.d.ts +6 -3
  65. package/lib/cjs/entities/index.js +41 -17
  66. package/lib/cjs/entities/marketV1/marketV1.d.ts +45 -11
  67. package/lib/cjs/entities/marketV1/marketV1.js +27 -12
  68. package/lib/cjs/entities/reallocationData.d.ts +193 -0
  69. package/lib/cjs/entities/reallocationData.js +406 -0
  70. package/lib/cjs/errors.d.ts +2 -0
  71. package/lib/cjs/errors.js +18 -0
  72. package/lib/cjs/fetch.d.ts +1 -0
  73. package/lib/cjs/fetch.js +30 -0
  74. package/lib/cjs/format.d.ts +2 -0
  75. package/lib/cjs/format.js +22 -0
  76. package/lib/cjs/helpers/computeReallocations.d.ts +48 -8
  77. package/lib/cjs/helpers/computeReallocations.js +120 -32
  78. package/lib/cjs/helpers/constant.d.ts +17 -0
  79. package/lib/cjs/helpers/constant.js +30 -1
  80. package/lib/cjs/helpers/index.d.ts +1 -0
  81. package/lib/cjs/helpers/index.js +9 -1
  82. package/lib/cjs/helpers/validate.d.ts +2 -0
  83. package/lib/cjs/helpers/validate.js +14 -2
  84. package/lib/cjs/index.d.ts +0 -1
  85. package/lib/cjs/index.js +0 -1
  86. package/lib/cjs/types/client.d.ts +1 -1
  87. package/lib/cjs/types/error.d.ts +87 -1
  88. package/lib/cjs/types/error.js +119 -1
  89. package/lib/cjs/types/sharedLiquidity.d.ts +43 -3
  90. package/lib/cjs/types.d.ts +3 -0
  91. package/lib/cjs/types.js +17 -0
  92. package/lib/cjs/utils.d.ts +9 -0
  93. package/lib/cjs/utils.js +65 -0
  94. package/lib/esm/abis.d.ts +2816 -0
  95. package/lib/esm/abis.js +1922 -0
  96. package/lib/esm/actions/index.d.ts +3 -0
  97. package/lib/esm/actions/marketV1/borrow.js +2 -5
  98. package/lib/esm/actions/marketV1/buildReallocationActions.d.ts +2 -3
  99. package/lib/esm/actions/marketV1/buildReallocationActions.js +1 -2
  100. package/lib/esm/actions/marketV1/repay.d.ts +2 -0
  101. package/lib/esm/actions/marketV1/repay.js +4 -5
  102. package/lib/esm/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  103. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +4 -5
  104. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +2 -0
  105. package/lib/esm/actions/marketV1/supplyCollateral.js +4 -5
  106. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  107. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +4 -5
  108. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +1 -1
  109. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +1 -1
  110. package/lib/esm/actions/requirements/getRequirementsApproval.js +1 -1
  111. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -0
  112. package/lib/esm/actions/vaultV1/deposit.js +3 -4
  113. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -0
  114. package/lib/esm/actions/vaultV1/migrateToV2.js +3 -1
  115. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -0
  116. package/lib/esm/actions/vaultV2/deposit.js +3 -4
  117. package/lib/esm/addresses.d.ts +2 -0
  118. package/lib/esm/addresses.js +1 -0
  119. package/lib/esm/augment/AccrualPosition.d.ts +9 -0
  120. package/lib/esm/augment/AccrualPosition.js +5 -0
  121. package/lib/esm/augment/AccrualVault.d.ts +8 -0
  122. package/lib/esm/augment/AccrualVault.js +4 -0
  123. package/lib/esm/augment/Holding.d.ts +8 -0
  124. package/lib/esm/augment/Holding.js +4 -0
  125. package/lib/esm/augment/Market.d.ts +8 -0
  126. package/lib/esm/augment/Market.js +4 -0
  127. package/lib/esm/augment/MarketParams.d.ts +8 -0
  128. package/lib/esm/augment/MarketParams.js +4 -0
  129. package/lib/esm/augment/Position.d.ts +8 -0
  130. package/lib/esm/augment/Position.js +4 -0
  131. package/lib/esm/augment/Token.d.ts +8 -0
  132. package/lib/esm/augment/Token.js +4 -0
  133. package/lib/esm/augment/User.d.ts +8 -0
  134. package/lib/esm/augment/User.js +4 -0
  135. package/lib/esm/augment/Vault.d.ts +8 -0
  136. package/lib/esm/augment/Vault.js +4 -0
  137. package/lib/esm/augment/VaultConfig.d.ts +8 -0
  138. package/lib/esm/augment/VaultConfig.js +4 -0
  139. package/lib/esm/augment/VaultMarketAllocation.d.ts +8 -0
  140. package/lib/esm/augment/VaultMarketAllocation.js +4 -0
  141. package/lib/esm/augment/VaultMarketConfig.d.ts +8 -0
  142. package/lib/esm/augment/VaultMarketConfig.js +4 -0
  143. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  144. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +5 -0
  145. package/lib/esm/augment/VaultUser.d.ts +8 -0
  146. package/lib/esm/augment/VaultUser.js +4 -0
  147. package/lib/esm/augment.d.ts +14 -0
  148. package/lib/esm/augment.js +14 -0
  149. package/lib/esm/bundler/actions.d.ts +555 -0
  150. package/lib/esm/bundler/actions.js +950 -0
  151. package/lib/esm/bundler/index.d.ts +2 -0
  152. package/lib/esm/bundler/index.js +2 -0
  153. package/lib/esm/bundler/types.d.ts +181 -0
  154. package/lib/esm/bundler/types.js +1 -0
  155. package/lib/esm/constants.d.ts +3 -0
  156. package/lib/esm/constants.js +3 -0
  157. package/lib/esm/entities/index.d.ts +6 -3
  158. package/lib/esm/entities/index.js +5 -3
  159. package/lib/esm/entities/marketV1/marketV1.d.ts +45 -11
  160. package/lib/esm/entities/marketV1/marketV1.js +28 -13
  161. package/lib/esm/entities/reallocationData.d.ts +193 -0
  162. package/lib/esm/entities/reallocationData.js +402 -0
  163. package/lib/esm/errors.d.ts +2 -0
  164. package/lib/esm/errors.js +1 -0
  165. package/lib/esm/fetch.d.ts +1 -0
  166. package/lib/esm/fetch.js +1 -0
  167. package/lib/esm/format.d.ts +2 -0
  168. package/lib/esm/format.js +1 -0
  169. package/lib/esm/helpers/computeReallocations.d.ts +48 -8
  170. package/lib/esm/helpers/computeReallocations.js +119 -31
  171. package/lib/esm/helpers/constant.d.ts +17 -0
  172. package/lib/esm/helpers/constant.js +30 -1
  173. package/lib/esm/helpers/index.d.ts +1 -0
  174. package/lib/esm/helpers/index.js +1 -0
  175. package/lib/esm/helpers/validate.d.ts +2 -0
  176. package/lib/esm/helpers/validate.js +12 -1
  177. package/lib/esm/index.d.ts +0 -1
  178. package/lib/esm/index.js +0 -1
  179. package/lib/esm/types/client.d.ts +1 -1
  180. package/lib/esm/types/error.d.ts +87 -1
  181. package/lib/esm/types/error.js +112 -0
  182. package/lib/esm/types/sharedLiquidity.d.ts +43 -3
  183. package/lib/esm/types.d.ts +3 -0
  184. package/lib/esm/types.js +1 -0
  185. package/lib/esm/utils.d.ts +9 -0
  186. package/lib/esm/utils.js +7 -0
  187. package/package.json +118 -11
  188. package/src/index.ts +0 -1
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ShortFormatter = exports.PercentFormatter = exports.NumberFormatter = exports.HexFormatter = exports.getLocaleSymbols = exports.getEnUSNumberToLocalParts = exports.getEffectiveLocale = exports.formatUnion = exports.formatLongString = exports.formatEnumeration = exports.format = exports.Format = exports.createFormat = exports.convertNumStrToLocal = exports.convertNumStrFromEffectiveTo = exports.CommonFormatter = exports.CommasFormatter = exports.BaseFormatter = void 0;
4
+ var morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ Object.defineProperty(exports, "BaseFormatter", { enumerable: true, get: function () { return morpho_ts_1.BaseFormatter; } });
6
+ Object.defineProperty(exports, "CommasFormatter", { enumerable: true, get: function () { return morpho_ts_1.CommasFormatter; } });
7
+ Object.defineProperty(exports, "CommonFormatter", { enumerable: true, get: function () { return morpho_ts_1.CommonFormatter; } });
8
+ Object.defineProperty(exports, "convertNumStrFromEffectiveTo", { enumerable: true, get: function () { return morpho_ts_1.convertNumStrFromEffectiveTo; } });
9
+ Object.defineProperty(exports, "convertNumStrToLocal", { enumerable: true, get: function () { return morpho_ts_1.convertNumStrToLocal; } });
10
+ Object.defineProperty(exports, "createFormat", { enumerable: true, get: function () { return morpho_ts_1.createFormat; } });
11
+ Object.defineProperty(exports, "Format", { enumerable: true, get: function () { return morpho_ts_1.Format; } });
12
+ Object.defineProperty(exports, "format", { enumerable: true, get: function () { return morpho_ts_1.format; } });
13
+ Object.defineProperty(exports, "formatEnumeration", { enumerable: true, get: function () { return morpho_ts_1.formatEnumeration; } });
14
+ Object.defineProperty(exports, "formatLongString", { enumerable: true, get: function () { return morpho_ts_1.formatLongString; } });
15
+ Object.defineProperty(exports, "formatUnion", { enumerable: true, get: function () { return morpho_ts_1.formatUnion; } });
16
+ Object.defineProperty(exports, "getEffectiveLocale", { enumerable: true, get: function () { return morpho_ts_1.getEffectiveLocale; } });
17
+ Object.defineProperty(exports, "getEnUSNumberToLocalParts", { enumerable: true, get: function () { return morpho_ts_1.getEnUSNumberToLocalParts; } });
18
+ Object.defineProperty(exports, "getLocaleSymbols", { enumerable: true, get: function () { return morpho_ts_1.getLocaleSymbols; } });
19
+ Object.defineProperty(exports, "HexFormatter", { enumerable: true, get: function () { return morpho_ts_1.HexFormatter; } });
20
+ Object.defineProperty(exports, "NumberFormatter", { enumerable: true, get: function () { return morpho_ts_1.NumberFormatter; } });
21
+ Object.defineProperty(exports, "PercentFormatter", { enumerable: true, get: function () { return morpho_ts_1.PercentFormatter; } });
22
+ Object.defineProperty(exports, "ShortFormatter", { enumerable: true, get: function () { return morpho_ts_1.ShortFormatter; } });
@@ -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;
@@ -2,32 +2,126 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.computeReallocations = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
- const bundler_sdk_viem_1 = require("@morpho-org/bundler-sdk-viem");
6
5
  const index_js_1 = require("../types/index.js");
6
+ const constant_js_1 = require("./constant.js");
7
+ const validate_js_1 = require("./validate.js");
8
+ const groupWithdrawalsByVault = (withdrawals) => {
9
+ const groups = [];
10
+ const groupsByVault = new Map();
11
+ for (const [index, { vault, id, assets }] of withdrawals.entries()) {
12
+ if (assets <= 0n)
13
+ continue;
14
+ let group = groupsByVault.get(vault);
15
+ if (group == null) {
16
+ group = {
17
+ vault,
18
+ firstIndex: index,
19
+ totalAssets: 0n,
20
+ withdrawals: [],
21
+ };
22
+ groupsByVault.set(vault, group);
23
+ groups.push(group);
24
+ }
25
+ group.totalAssets += assets;
26
+ group.withdrawals.push({ id, assets });
27
+ }
28
+ return groups.sort((a, b) => {
29
+ if (a.totalAssets > b.totalAssets)
30
+ return -1;
31
+ if (a.totalAssets < b.totalAssets)
32
+ return 1;
33
+ return a.firstIndex - b.firstIndex;
34
+ });
35
+ };
36
+ const capVaultWithdrawals = (withdrawals, assets) => {
37
+ const cappedWithdrawals = [];
38
+ let remainingAssets = assets;
39
+ for (const withdrawal of withdrawals) {
40
+ const cappedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, remainingAssets);
41
+ if (cappedAssets <= 0n)
42
+ continue;
43
+ const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
44
+ if (existing != null) {
45
+ existing.assets += cappedAssets;
46
+ }
47
+ else {
48
+ cappedWithdrawals.push({
49
+ id: withdrawal.id,
50
+ assets: cappedAssets,
51
+ });
52
+ }
53
+ remainingAssets -= cappedAssets;
54
+ if (remainingAssets === 0n)
55
+ break;
56
+ }
57
+ return cappedWithdrawals;
58
+ };
7
59
  /**
8
60
  * Computes vault reallocations for a borrow operation on a target market.
9
61
  *
10
- * Replicates the shared liquidity algorithm from `populateSubBundle` in
11
- * `@morpho-org/bundler-sdk-viem`. First attempts "friendly" reallocations
12
- * respecting withdrawal utilization targets, then falls back to aggressive
13
- * reallocations (100% withdrawal utilization) if liquidity is still insufficient.
62
+ * First attempts "friendly" reallocations respecting withdrawal utilization
63
+ * targets, then falls back to aggressive reallocations (100% withdrawal
64
+ * utilization) if liquidity is still insufficient.
14
65
  *
15
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
66
+ * @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.
67
+ * @param params.reallocationData - The local state containing market, vault, and position data.
16
68
  * @param params.marketId - The target market to reallocate liquidity into.
17
69
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
18
70
  * @param params.options - Optional reallocation computation options.
19
71
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
20
- * @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.
72
+ * @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.
73
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
74
+ * @example
75
+ * ```ts
76
+ * import { createPublicClient, http, parseUnits } from "viem";
77
+ * import { mainnet } from "viem/chains";
78
+ * import { markets, vaults } from "@morpho-org/morpho-test";
79
+ * import {
80
+ * computeReallocations,
81
+ * morphoViemExtension,
82
+ * } from "@morpho-org/morpho-sdk";
83
+ *
84
+ * const client = createPublicClient({
85
+ * chain: mainnet,
86
+ * transport: http(),
87
+ * }).extend(morphoViemExtension());
88
+ *
89
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
90
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
91
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
92
+ * const block = await client.getBlock();
93
+ * const reallocationData = await market.getReallocationData({
94
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
95
+ * block: { number: block.number, timestamp: block.timestamp },
96
+ * });
97
+ * const borrowAmount = parseUnits("1000", 6);
98
+ * const reallocations = computeReallocations({
99
+ * reallocationData,
100
+ * marketId: marketParams.id,
101
+ * borrowAmount,
102
+ * options: { timestamp: block.timestamp },
103
+ * });
104
+ * const positionData = await market.getPositionData(userAddress);
105
+ * const borrow = market.borrow({
106
+ * userAddress,
107
+ * amount: borrowAmount,
108
+ * positionData,
109
+ * reallocations,
110
+ * });
111
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
112
+ * ```
21
113
  */
22
114
  const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
23
115
  if (options?.enabled === false)
24
116
  return [];
25
- const market = data.getMarket(marketId).accrueInterest(data.block.timestamp);
117
+ // ReallocationData does not retain the fetch block; pass that block timestamp
118
+ // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
119
+ const market = data.getMarket(marketId).accrueInterest(options?.timestamp);
26
120
  const newTotalBorrowAssets = market.totalBorrowAssets + borrowAmount;
27
121
  const newTotalSupplyAssets = market.totalSupplyAssets;
28
122
  const supplyTargetUtilization = options?.supplyTargetUtilization?.[market.params.id] ??
29
123
  options?.defaultSupplyTargetUtilization ??
30
- bundler_sdk_viem_1.DEFAULT_SUPPLY_TARGET_UTILIZATION;
124
+ constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION;
31
125
  if (blue_sdk_1.MarketUtils.getUtilization({
32
126
  totalSupplyAssets: newTotalSupplyAssets,
33
127
  totalBorrowAssets: newTotalBorrowAssets,
@@ -58,27 +152,20 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
58
152
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
59
153
  ? newTotalBorrowAssets - newTotalSupplyAssets
60
154
  : 0n;
61
- // Group withdrawals by vault, capping total at requiredAssets.
62
- const reallocationsMap = {};
155
+ const reallocations = [];
63
156
  let totalReallocated = 0n;
64
- for (const { vault, ...withdrawal } of withdrawals) {
65
- const vaultReallocations = (reallocationsMap[vault] ??= []);
66
- const existing = vaultReallocations.find((item) => item.id === withdrawal.id);
67
- const reallocatedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, requiredAssets);
157
+ let remainingRequiredAssets = requiredAssets;
158
+ for (const group of groupWithdrawalsByVault(withdrawals)) {
159
+ const reallocatedAssets = blue_sdk_1.MathLib.min(group.totalAssets, remainingRequiredAssets);
68
160
  if (reallocatedAssets <= 0n)
69
161
  continue;
70
- if (existing != null) {
71
- existing.assets += reallocatedAssets;
72
- }
73
- else {
74
- vaultReallocations.push({
75
- ...withdrawal,
76
- assets: reallocatedAssets,
77
- });
78
- }
79
- requiredAssets -= reallocatedAssets;
162
+ reallocations.push({
163
+ vault: group.vault,
164
+ withdrawals: capVaultWithdrawals(group.withdrawals, reallocatedAssets),
165
+ });
166
+ remainingRequiredAssets -= reallocatedAssets;
80
167
  totalReallocated += reallocatedAssets;
81
- if (requiredAssets === 0n)
168
+ if (remainingRequiredAssets === 0n)
82
169
  break;
83
170
  }
84
171
  // Refuse fee-bearing partial plans for an unreachable borrow.
@@ -90,10 +177,10 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
90
177
  });
91
178
  }
92
179
  // Transform into VaultReallocation[] format.
93
- return Object.entries(reallocationsMap)
94
- .filter(([, vaultWithdrawals]) => vaultWithdrawals.length > 0)
95
- .map(([vault, vaultWithdrawals]) => ({
96
- vault: vault,
180
+ return reallocations
181
+ .filter(({ withdrawals: vaultWithdrawals }) => vaultWithdrawals.length > 0)
182
+ .map(({ vault, withdrawals: vaultWithdrawals }) => ({
183
+ vault,
97
184
  fee: (() => {
98
185
  const config = data.getVault(vault).publicAllocatorConfig;
99
186
  if (config == null) {
@@ -102,8 +189,9 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
102
189
  return config.fee;
103
190
  })(),
104
191
  withdrawals: vaultWithdrawals
105
- // Reallocation withdrawals must be sorted by market id in ascending order.
106
- .sort(({ id: idA }, { id: idB }) => idA > idB ? 1 : idA < idB ? -1 : 0)
192
+ // Reallocation withdrawals must be sorted by market id in ascending
193
+ // order. Normalize first because `MarketId` can be mixed-case hex.
194
+ .sort(({ id: idA }, { id: idB }) => (0, validate_js_1.compareMarketIds)(idA, idB))
107
195
  .map(({ id, assets }) => ({
108
196
  marketParams: data.getMarket(id).params,
109
197
  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,10 +1,39 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_LLTV_BUFFER = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
3
+ exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_LLTV_BUFFER = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const viem_1 = require("viem");
5
6
  /** Maximum slippage tolerance: 10% */
6
7
  exports.MAX_SLIPPAGE_TOLERANCE = blue_sdk_1.MathLib.WAD / 10n;
7
8
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
8
9
  exports.DEFAULT_LLTV_BUFFER = blue_sdk_1.MathLib.WAD / 200n;
9
10
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
10
11
  exports.MAX_ABSOLUTE_SHARE_PRICE = 100n * blue_sdk_1.MathLib.RAY;
12
+ /**
13
+ * The default maximum utilization allowed to reach when withdrawing shared liquidity.
14
+ */
15
+ exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
16
+ /**
17
+ * The default target utilization above which shared liquidity reallocations are triggered.
18
+ */
19
+ exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
20
+ /**
21
+ * Tokens that require setting allowance from zero before changing approval.
22
+ */
23
+ exports.APPROVE_ONLY_ONCE_TOKENS = {
24
+ [blue_sdk_1.ChainId.EthMainnet]: [
25
+ "0xdAC17F958D2ee523a2206206994597C13D831ec7", // USDT
26
+ "0xD533a949740bb3306d119CC777fa900bA034cd52", // CRV
27
+ ],
28
+ };
29
+ /**
30
+ * Token-specific maximum approval amounts for tokens that cannot use uint256 max.
31
+ */
32
+ exports.MAX_TOKEN_APPROVALS = {
33
+ [blue_sdk_1.ChainId.EthMainnet]: {
34
+ "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984": viem_1.maxUint96, // UNI
35
+ "0xfAbA6f8e4a5E8Ab82F62fe7C39859FA577269BE3": viem_1.maxUint96, // ONDO
36
+ "0xc00e94Cb662C3520282E6f5717214004A7f26888": viem_1.maxUint96, // COMP
37
+ "0x6f40d4A6237C257fff2dB00FA0510DeEECd303eb": viem_1.maxUint96, // FLUID
38
+ },
39
+ };
@@ -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,8 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeCollateral = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = void 0;
3
+ exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeCollateral = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_LLTV_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = exports.computeReallocations = void 0;
4
4
  var computeReallocations_js_1 = require("./computeReallocations.js");
5
5
  Object.defineProperty(exports, "computeReallocations", { enumerable: true, get: function () { return computeReallocations_js_1.computeReallocations; } });
6
+ var constant_js_1 = require("./constant.js");
7
+ Object.defineProperty(exports, "APPROVE_ONLY_ONCE_TOKENS", { enumerable: true, get: function () { return constant_js_1.APPROVE_ONLY_ONCE_TOKENS; } });
8
+ Object.defineProperty(exports, "DEFAULT_LLTV_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_LLTV_BUFFER; } });
9
+ Object.defineProperty(exports, "DEFAULT_SUPPLY_TARGET_UTILIZATION", { enumerable: true, get: function () { return constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION; } });
10
+ Object.defineProperty(exports, "DEFAULT_WITHDRAWAL_TARGET_UTILIZATION", { enumerable: true, get: function () { return constant_js_1.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION; } });
11
+ Object.defineProperty(exports, "MAX_ABSOLUTE_SHARE_PRICE", { enumerable: true, get: function () { return constant_js_1.MAX_ABSOLUTE_SHARE_PRICE; } });
12
+ Object.defineProperty(exports, "MAX_SLIPPAGE_TOLERANCE", { enumerable: true, get: function () { return constant_js_1.MAX_SLIPPAGE_TOLERANCE; } });
13
+ Object.defineProperty(exports, "MAX_TOKEN_APPROVALS", { enumerable: true, get: function () { return constant_js_1.MAX_TOKEN_APPROVALS; } });
6
14
  var metadata_js_1 = require("./metadata.js");
7
15
  Object.defineProperty(exports, "addTransactionMetadata", { enumerable: true, get: function () { return metadata_js_1.addTransactionMetadata; } });
8
16
  var slippage_js_1 = require("./slippage.js");
@@ -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.
@@ -1,12 +1,23 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = void 0;
3
+ exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = exports.compareMarketIds = void 0;
4
4
  exports.validateUserAddress = validateUserAddress;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
7
  const viem_1 = require("viem");
8
8
  const index_js_1 = require("../types/index.js");
9
9
  const constant_js_1 = require("./constant.js");
10
+ /** @internal */
11
+ const compareMarketIds = (idA, idB) => {
12
+ const normalizedIdA = idA.toLowerCase();
13
+ const normalizedIdB = idB.toLowerCase();
14
+ if (normalizedIdA > normalizedIdB)
15
+ return 1;
16
+ if (normalizedIdA < normalizedIdB)
17
+ return -1;
18
+ return 0;
19
+ };
20
+ exports.compareMarketIds = compareMarketIds;
10
21
  /**
11
22
  * Asserts that the client has a connected account AND that it matches
12
23
  * the provided user address.
@@ -264,7 +275,8 @@ const validateReallocations = (reallocations, targetMarketId) => {
264
275
  if (w.marketParams.id === targetMarketId) {
265
276
  throw new index_js_1.ReallocationWithdrawalOnTargetMarketError(r.vault, w.marketParams.id);
266
277
  }
267
- if (prevId !== undefined && w.marketParams.id <= prevId) {
278
+ if (prevId !== undefined &&
279
+ (0, exports.compareMarketIds)(w.marketParams.id, prevId) <= 0) {
268
280
  throw new index_js_1.UnsortedReallocationWithdrawalsError(r.vault, w.marketParams.id);
269
281
  }
270
282
  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/cjs/index.js CHANGED
@@ -16,6 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./actions/index.js"), exports);
18
18
  __exportStar(require("./client/index.js"), exports);
19
- __exportStar(require("./entities/index.js"), exports);
20
19
  __exportStar(require("./helpers/index.js"), exports);
21
20
  __exportStar(require("./types/index.js"), exports);
@@ -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);
@@ -196,6 +240,12 @@ export declare class RepaySharesExceedDebtError extends Error {
196
240
  export declare class MissingPublicAllocatorConfigError extends Error {
197
241
  constructor(vault: string);
198
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
+ }
199
249
  /**
200
250
  * Thrown when shared liquidity selected by `computeReallocations` cannot cover
201
251
  * the absolute borrow shortfall on the target market — the resulting
@@ -215,6 +265,42 @@ export declare class InsufficientSharedLiquidityError extends Error {
215
265
  readonly available: bigint;
216
266
  });
217
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
+ }
218
304
  /** Thrown when a market borrow's `minSharePrice` slippage bound is negative. */
219
305
  export declare class NonPositiveMinBorrowSharePriceError extends Error {
220
306
  constructor(market: string);