@morpho-org/morpho-sdk 3.0.0 → 3.1.1

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 (60) hide show
  1. package/README.md +69 -3
  2. package/lib/cjs/actions/marketV1/index.d.ts +2 -0
  3. package/lib/cjs/actions/marketV1/index.js +2 -0
  4. package/lib/cjs/actions/marketV1/supply.d.ts +69 -0
  5. package/lib/cjs/actions/marketV1/supply.js +128 -0
  6. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +1 -1
  7. package/lib/cjs/actions/marketV1/supplyCollateral.js +2 -2
  8. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  9. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +2 -2
  10. package/lib/cjs/actions/marketV1/withdraw.d.ts +83 -0
  11. package/lib/cjs/actions/marketV1/withdraw.js +110 -0
  12. package/lib/cjs/bundler/actions.d.ts +86 -4
  13. package/lib/cjs/bundler/actions.js +143 -8
  14. package/lib/cjs/bundler/types.d.ts +23 -4
  15. package/lib/cjs/entities/marketV1/marketV1.d.ts +121 -18
  16. package/lib/cjs/entities/marketV1/marketV1.js +144 -12
  17. package/lib/cjs/entities/reallocationData.js +3 -0
  18. package/lib/cjs/helpers/computeReallocations.d.ts +17 -6
  19. package/lib/cjs/helpers/computeReallocations.js +44 -11
  20. package/lib/cjs/helpers/index.d.ts +2 -2
  21. package/lib/cjs/helpers/index.js +6 -2
  22. package/lib/cjs/helpers/slippage.d.ts +57 -0
  23. package/lib/cjs/helpers/slippage.js +82 -0
  24. package/lib/cjs/helpers/validate.d.ts +38 -7
  25. package/lib/cjs/helpers/validate.js +54 -11
  26. package/lib/cjs/types/action.d.ts +27 -6
  27. package/lib/cjs/types/error.d.ts +68 -6
  28. package/lib/cjs/types/error.js +85 -12
  29. package/lib/cjs/utils.d.ts +1 -1
  30. package/lib/cjs/utils.js +2 -2
  31. package/lib/esm/actions/marketV1/index.d.ts +2 -0
  32. package/lib/esm/actions/marketV1/index.js +2 -0
  33. package/lib/esm/actions/marketV1/supply.d.ts +69 -0
  34. package/lib/esm/actions/marketV1/supply.js +124 -0
  35. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +1 -1
  36. package/lib/esm/actions/marketV1/supplyCollateral.js +3 -3
  37. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  38. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +3 -3
  39. package/lib/esm/actions/marketV1/withdraw.d.ts +83 -0
  40. package/lib/esm/actions/marketV1/withdraw.js +106 -0
  41. package/lib/esm/bundler/actions.d.ts +86 -4
  42. package/lib/esm/bundler/actions.js +143 -8
  43. package/lib/esm/bundler/types.d.ts +23 -4
  44. package/lib/esm/entities/marketV1/marketV1.d.ts +121 -18
  45. package/lib/esm/entities/marketV1/marketV1.js +147 -15
  46. package/lib/esm/entities/reallocationData.js +3 -0
  47. package/lib/esm/helpers/computeReallocations.d.ts +17 -6
  48. package/lib/esm/helpers/computeReallocations.js +45 -12
  49. package/lib/esm/helpers/index.d.ts +2 -2
  50. package/lib/esm/helpers/index.js +2 -2
  51. package/lib/esm/helpers/slippage.d.ts +57 -0
  52. package/lib/esm/helpers/slippage.js +80 -0
  53. package/lib/esm/helpers/validate.d.ts +38 -7
  54. package/lib/esm/helpers/validate.js +51 -10
  55. package/lib/esm/types/action.d.ts +27 -6
  56. package/lib/esm/types/error.d.ts +68 -6
  57. package/lib/esm/types/error.js +73 -9
  58. package/lib/esm/utils.d.ts +1 -1
  59. package/lib/esm/utils.js +1 -1
  60. package/package.json +14 -10
@@ -34,6 +34,120 @@ class MorphoMarketV1 {
34
34
  chainId: this.chainId,
35
35
  });
36
36
  }
37
+ supply({ amount = 0n, userAddress, nativeAmount, marketData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, }) {
38
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
39
+ if (amount < 0n) {
40
+ throw new index_js_3.NegativeSupplyAmountError(this.marketParams.id);
41
+ }
42
+ if (nativeAmount !== undefined && nativeAmount < 0n) {
43
+ throw new index_js_3.NegativeNativeAmountError(nativeAmount);
44
+ }
45
+ const totalAssets = amount + (nativeAmount ?? 0n);
46
+ if (totalAssets === 0n) {
47
+ throw new index_js_3.ZeroSupplyAmountError(this.marketParams.id);
48
+ }
49
+ if (marketData.id !== this.marketParams.id) {
50
+ throw new index_js_3.MarketIdMismatchError(marketData.id, this.marketParams.id);
51
+ }
52
+ (0, index_js_2.validateSlippageTolerance)(slippageTolerance);
53
+ if (nativeAmount !== undefined && nativeAmount > 0n) {
54
+ (0, index_js_2.validateNativeAsset)(this.chainId, this.marketParams.loanToken);
55
+ }
56
+ const maxSharePrice = (0, index_js_2.computeMaxSupplySharePrice)({
57
+ supplyAssets: totalAssets,
58
+ market: marketData,
59
+ slippageTolerance,
60
+ });
61
+ return {
62
+ getRequirements: (params) => (0, index_js_1.getRequirements)(this.client.viemClient, {
63
+ address: this.marketParams.loanToken,
64
+ chainId: this.chainId,
65
+ supportSignature: this.client.options.supportSignature,
66
+ supportDeployless: this.client.options.supportDeployless,
67
+ useSimplePermit: params?.useSimplePermit,
68
+ args: { amount, from: userAddress },
69
+ }),
70
+ buildTx: (requirementSignature) => (0, index_js_1.marketV1Supply)({
71
+ market: { chainId: this.chainId, marketParams: this.marketParams },
72
+ args: {
73
+ amount,
74
+ nativeAmount,
75
+ onBehalf: userAddress,
76
+ maxSharePrice,
77
+ requirementSignature,
78
+ },
79
+ metadata: this.client.options.metadata,
80
+ }),
81
+ };
82
+ }
83
+ withdraw(params) {
84
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
85
+ const { userAddress, receiver = userAddress, positionData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, reallocations, } = params;
86
+ // Mode normalization: a missing or undefined `assets`/`shares` key collapses to `0n`
87
+ // so the mutual-exclusion and positivity checks below are pure value comparisons.
88
+ const assets = ("assets" in params ? params.assets : undefined) ?? 0n;
89
+ const shares = ("shares" in params ? params.shares : undefined) ?? 0n;
90
+ // Mode conflict comes first: detect "both values present" (either non-zero)
91
+ // before positivity, so `{ assets: -1n, shares: 5n }` reports the actual
92
+ // mode conflict instead of being misclassified as a positivity error.
93
+ // Mirrors action layer.
94
+ if (assets !== 0n && shares !== 0n) {
95
+ throw new index_js_3.MutuallyExclusiveWithdrawAmountsError(this.marketParams.id);
96
+ }
97
+ if (assets < 0n || shares < 0n || (assets === 0n && shares === 0n)) {
98
+ throw new index_js_3.NonPositiveWithdrawAmountError(this.marketParams.id);
99
+ }
100
+ (0, index_js_2.validateSlippageTolerance)(slippageTolerance);
101
+ if (!positionData) {
102
+ throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
103
+ }
104
+ (0, index_js_2.validateAccrualPosition)({
105
+ positionData,
106
+ expectedMarketId: this.marketParams.id,
107
+ expectedUser: userAddress,
108
+ });
109
+ if (shares > 0n) {
110
+ (0, index_js_2.validateWithdrawShares)({
111
+ positionData,
112
+ withdrawShares: shares,
113
+ marketId: this.marketParams.id,
114
+ });
115
+ }
116
+ else {
117
+ (0, index_js_2.validateWithdrawAmount)({
118
+ positionData,
119
+ withdrawAssets: assets,
120
+ marketId: this.marketParams.id,
121
+ });
122
+ }
123
+ const minSharePrice = (0, index_js_2.computeMinWithdrawSharePrice)({
124
+ withdrawAssets: assets,
125
+ withdrawShares: shares,
126
+ market: positionData.market,
127
+ slippageTolerance,
128
+ });
129
+ return {
130
+ getRequirements: async () => {
131
+ const authTx = await (0, index_js_1.getMorphoAuthorizationRequirement)({
132
+ viemClient: this.client.viemClient,
133
+ chainId: this.chainId,
134
+ userAddress,
135
+ });
136
+ return authTx ? [authTx] : [];
137
+ },
138
+ buildTx: () => (0, index_js_1.marketV1Withdraw)({
139
+ market: { chainId: this.chainId, marketParams: this.marketParams },
140
+ args: {
141
+ assets,
142
+ shares,
143
+ receiver,
144
+ minSharePrice,
145
+ reallocations,
146
+ },
147
+ metadata: this.client.options.metadata,
148
+ }),
149
+ };
150
+ }
37
151
  supplyCollateral({ amount = 0n, userAddress, nativeAmount, }) {
38
152
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
39
153
  if (amount < 0n) {
@@ -47,7 +161,7 @@ class MorphoMarketV1 {
47
161
  throw new index_js_3.ZeroCollateralAmountError(this.marketParams.id);
48
162
  }
49
163
  if (nativeAmount !== undefined && nativeAmount > 0n) {
50
- (0, index_js_2.validateNativeCollateral)(this.chainId, this.marketParams.collateralToken);
164
+ (0, index_js_2.validateNativeAsset)(this.chainId, this.marketParams.collateralToken);
51
165
  }
52
166
  return {
53
167
  getRequirements: (params) => (0, index_js_1.getRequirements)(this.client.viemClient, {
@@ -395,7 +509,7 @@ class MorphoMarketV1 {
395
509
  }
396
510
  (0, index_js_2.validateSlippageTolerance)(slippageTolerance);
397
511
  if (nativeAmount !== undefined && nativeAmount > 0n) {
398
- (0, index_js_2.validateNativeCollateral)(this.chainId, this.marketParams.collateralToken);
512
+ (0, index_js_2.validateNativeAsset)(this.chainId, this.marketParams.collateralToken);
399
513
  }
400
514
  (0, index_js_2.validatePositionHealth)({
401
515
  positionData,
@@ -524,25 +638,43 @@ class MorphoMarketV1 {
524
638
  });
525
639
  }
526
640
  /**
527
- * Computes public allocator reallocations for a borrow on this market.
641
+ * Computes public allocator reallocations for a borrow or withdraw on this market.
642
+ *
643
+ * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow", amount }`)
644
+ * or `{ operation, amount }` for a borrow or loan-asset withdraw.
528
645
  *
529
646
  * @param params - Reallocation computation parameters.
530
647
  * @param params.reallocationData - State returned by {@link getReallocationData}.
531
- * @param params.borrowAmount - Borrow amount to test against post-borrow utilization.
648
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
649
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
650
+ * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.}
532
651
  * @param params.options - Optional allocator and utilization options.
533
- * @returns Vault reallocations ready to pass to `borrow` or `supplyCollateralBorrow`.
652
+ * @returns Vault reallocations ready to pass to `borrow`, `supplyCollateralBorrow`, or `withdraw`.
534
653
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market.
535
- * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market.
654
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market.
655
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`.
536
656
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
537
657
  * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data.
538
658
  */
539
- getReallocations({ reallocationData, borrowAmount, options, }) {
540
- (0, index_js_2.validateChainId)(reallocationData.chainId, this.chainId);
659
+ getReallocations(params) {
660
+ (0, index_js_2.validateChainId)(params.reallocationData.chainId, this.chainId);
661
+ const marketId = this.marketParams.id;
662
+ const options = { enabled: true, ...params.options };
663
+ if (params.borrowAmount !== undefined) {
664
+ return (0, index_js_2.computeReallocations)({
665
+ reallocationData: params.reallocationData,
666
+ marketId,
667
+ operation: "borrow",
668
+ amount: params.borrowAmount,
669
+ options,
670
+ });
671
+ }
541
672
  return (0, index_js_2.computeReallocations)({
542
- reallocationData,
543
- marketId: this.marketParams.id,
544
- borrowAmount,
545
- options: { enabled: true, ...options },
673
+ reallocationData: params.reallocationData,
674
+ marketId,
675
+ operation: params.operation,
676
+ amount: params.amount,
677
+ options,
546
678
  });
547
679
  }
548
680
  }
@@ -285,6 +285,7 @@ class ReallocationData {
285
285
  if (count <= 1)
286
286
  continue;
287
287
  const vaultPublicAllocatorConfig = data.getVault(vault).publicAllocatorConfig;
288
+ /* v8 ignore next: repeated withdrawals require a configured public allocator earlier in the flow. */
288
289
  if (vaultPublicAllocatorConfig == null)
289
290
  throw new index_js_1.MissingPublicAllocatorConfigError(vault);
290
291
  vaultPublicAllocatorConfig.accruedFee -=
@@ -357,7 +358,9 @@ class ReallocationData {
357
358
  applyPublicReallocation({ vault, supplyMarketId, withdrawal, timestamp, }) {
358
359
  const data = this.forkAliasedState();
359
360
  data.vaults[vault] = cloneVault(this.getVault(vault));
361
+ /* v8 ignore next: forkAliasedState keeps vault position buckets initialized for known vaults. */
360
362
  data.positions[vault] = { ...(this.positions[vault] ?? {}) };
363
+ /* v8 ignore next: forkAliasedState keeps vault market config buckets initialized for known vaults. */
361
364
  data.vaultMarketConfigs[vault] = {
362
365
  ...(this.vaultMarketConfigs[vault] ?? {}),
363
366
  };
@@ -2,19 +2,28 @@ import { type MarketId } from "@morpho-org/blue-sdk";
2
2
  import type { ReallocationData } from "../entities/reallocationData.js";
3
3
  import { type ReallocationComputeOptions, type VaultReallocation } from "../types/index.js";
4
4
  /**
5
- * Computes vault reallocations for a borrow operation on a target market.
5
+ * Computes vault reallocations for a `borrow` or `withdraw` on a target market.
6
6
  *
7
7
  * First attempts "friendly" reallocations respecting withdrawal utilization
8
8
  * targets, then falls back to aggressive reallocations (100% withdrawal
9
9
  * utilization) if liquidity is still insufficient.
10
10
  *
11
+ * Algebra branches on `operation`:
12
+ * - `"borrow"`: `S' = S`, `B' = B + amount` (additional borrow demand).
13
+ * - `"withdraw"`: `S' = S − amount`, `B' = B` (supply-side shrinkage).
14
+ *
15
+ * In both cases reallocated assets are added on the supply side; `requiredAssets`
16
+ * and `absoluteShortfall` are derived from the operation-specific post-state.
17
+ *
11
18
  * @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
19
  * @param params.reallocationData - The local state containing market, vault, and position data.
13
20
  * @param params.marketId - The target market to reallocate liquidity into.
14
- * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
21
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
22
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
15
23
  * @param params.options - Optional reallocation computation options.
16
24
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
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.
25
+ * @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.
26
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
18
27
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
19
28
  * @example
20
29
  * ```ts
@@ -43,7 +52,8 @@ import { type ReallocationComputeOptions, type VaultReallocation } from "../type
43
52
  * const reallocations = computeReallocations({
44
53
  * reallocationData,
45
54
  * marketId: marketParams.id,
46
- * borrowAmount,
55
+ * operation: "borrow",
56
+ * amount: borrowAmount,
47
57
  * options: { timestamp: block.timestamp },
48
58
  * });
49
59
  * const positionData = await market.getPositionData(userAddress);
@@ -56,9 +66,10 @@ import { type ReallocationComputeOptions, type VaultReallocation } from "../type
56
66
  * // borrow.buildTx() includes any required PublicAllocator reallocations.
57
67
  * ```
58
68
  */
59
- export declare const computeReallocations: ({ reallocationData: data, marketId, borrowAmount, options, }: {
69
+ export declare const computeReallocations: ({ reallocationData: data, marketId, operation, amount, options, }: {
60
70
  readonly reallocationData: ReallocationData;
61
71
  readonly marketId: MarketId;
62
- readonly borrowAmount: bigint;
72
+ readonly operation: "borrow" | "withdraw";
73
+ readonly amount: bigint;
63
74
  readonly options?: ReallocationComputeOptions;
64
75
  }) => readonly VaultReallocation[];
@@ -38,6 +38,7 @@ const capVaultWithdrawals = (withdrawals, assets) => {
38
38
  let remainingAssets = assets;
39
39
  for (const withdrawal of withdrawals) {
40
40
  const cappedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, remainingAssets);
41
+ /* v8 ignore next: grouped withdrawals and positive reallocation cap keep this defensive guard unreachable. */
41
42
  if (cappedAssets <= 0n)
42
43
  continue;
43
44
  const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
@@ -57,19 +58,28 @@ const capVaultWithdrawals = (withdrawals, assets) => {
57
58
  return cappedWithdrawals;
58
59
  };
59
60
  /**
60
- * Computes vault reallocations for a borrow operation on a target market.
61
+ * Computes vault reallocations for a `borrow` or `withdraw` on a target market.
61
62
  *
62
63
  * First attempts "friendly" reallocations respecting withdrawal utilization
63
64
  * targets, then falls back to aggressive reallocations (100% withdrawal
64
65
  * utilization) if liquidity is still insufficient.
65
66
  *
67
+ * Algebra branches on `operation`:
68
+ * - `"borrow"`: `S' = S`, `B' = B + amount` (additional borrow demand).
69
+ * - `"withdraw"`: `S' = S − amount`, `B' = B` (supply-side shrinkage).
70
+ *
71
+ * In both cases reallocated assets are added on the supply side; `requiredAssets`
72
+ * and `absoluteShortfall` are derived from the operation-specific post-state.
73
+ *
66
74
  * @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
75
  * @param params.reallocationData - The local state containing market, vault, and position data.
68
76
  * @param params.marketId - The target market to reallocate liquidity into.
69
- * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
77
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
78
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
70
79
  * @param params.options - Optional reallocation computation options.
71
80
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
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.
81
+ * @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.
82
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
73
83
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
74
84
  * @example
75
85
  * ```ts
@@ -98,7 +108,8 @@ const capVaultWithdrawals = (withdrawals, assets) => {
98
108
  * const reallocations = computeReallocations({
99
109
  * reallocationData,
100
110
  * marketId: marketParams.id,
101
- * borrowAmount,
111
+ * operation: "borrow",
112
+ * amount: borrowAmount,
102
113
  * options: { timestamp: block.timestamp },
103
114
  * });
104
115
  * const positionData = await market.getPositionData(userAddress);
@@ -111,14 +122,29 @@ const capVaultWithdrawals = (withdrawals, assets) => {
111
122
  * // borrow.buildTx() includes any required PublicAllocator reallocations.
112
123
  * ```
113
124
  */
114
- const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
125
+ const computeReallocations = ({ reallocationData: data, marketId, operation, amount, options, }) => {
115
126
  if (options?.enabled === false)
116
127
  return [];
117
128
  // ReallocationData does not retain the fetch block; pass that block timestamp
118
129
  // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
119
130
  const market = data.getMarket(marketId).accrueInterest(options?.timestamp);
120
- const newTotalBorrowAssets = market.totalBorrowAssets + borrowAmount;
121
- const newTotalSupplyAssets = market.totalSupplyAssets;
131
+ // Reject unreachable withdraws before any utilization math: a negative
132
+ // post-supply yields a negative utilization that short-circuits the
133
+ // utilization gate below and silently returns `[]` — masking a sure revert.
134
+ if (operation === "withdraw" && amount > market.totalSupplyAssets) {
135
+ throw new index_js_1.ReallocationWithdrawExceedsMarketSupplyError({
136
+ marketId,
137
+ withdrawAmount: amount,
138
+ totalSupplyAssets: market.totalSupplyAssets,
139
+ });
140
+ }
141
+ // Post-state utilization is operation-dependent.
142
+ const newTotalBorrowAssets = operation === "borrow"
143
+ ? market.totalBorrowAssets + amount
144
+ : market.totalBorrowAssets;
145
+ const newTotalSupplyAssets = operation === "withdraw"
146
+ ? market.totalSupplyAssets - amount
147
+ : market.totalSupplyAssets;
122
148
  const supplyTargetUtilization = options?.supplyTargetUtilization?.[market.params.id] ??
123
149
  options?.defaultSupplyTargetUtilization ??
124
150
  constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION;
@@ -136,8 +162,14 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
136
162
  const { withdrawals: friendlyWithdrawals, data: friendlyReallocationData } = data.getMarketPublicReallocations(market.id, options);
137
163
  const withdrawals = [...friendlyWithdrawals];
138
164
  const friendlyReallocationMarket = friendlyReallocationData.getMarket(market.id);
139
- if (friendlyReallocationMarket.totalBorrowAssets + borrowAmount >
140
- friendlyReallocationMarket.totalSupplyAssets) {
165
+ // Operation-specific post-friendly check: would the on-chain call still revert?
166
+ const friendlyBorrow = operation === "borrow"
167
+ ? friendlyReallocationMarket.totalBorrowAssets + amount
168
+ : friendlyReallocationMarket.totalBorrowAssets;
169
+ const friendlySupply = operation === "withdraw"
170
+ ? friendlyReallocationMarket.totalSupplyAssets - amount
171
+ : friendlyReallocationMarket.totalSupplyAssets;
172
+ if (friendlyBorrow > friendlySupply) {
141
173
  // Phase 2: "aggressive" — fully withdraw from every market (100% utilization).
142
174
  requiredAssets = newTotalBorrowAssets - newTotalSupplyAssets;
143
175
  withdrawals.push(...friendlyReallocationData.getMarketPublicReallocations(market.id, {
@@ -148,7 +180,7 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
148
180
  }
149
181
  if (requiredAssets <= 0n)
150
182
  return [];
151
- // Liquidity strictly required for `morphoBorrow` to succeed onchain.
183
+ // Liquidity strictly required for the on-chain call to succeed.
152
184
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
153
185
  ? newTotalBorrowAssets - newTotalSupplyAssets
154
186
  : 0n;
@@ -157,6 +189,7 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
157
189
  let remainingRequiredAssets = requiredAssets;
158
190
  for (const group of groupWithdrawalsByVault(withdrawals)) {
159
191
  const reallocatedAssets = blue_sdk_1.MathLib.min(group.totalAssets, remainingRequiredAssets);
192
+ /* v8 ignore next: groups with non-positive assets are filtered before this point. */
160
193
  if (reallocatedAssets <= 0n)
161
194
  continue;
162
195
  reallocations.push({
@@ -168,7 +201,7 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
168
201
  if (remainingRequiredAssets === 0n)
169
202
  break;
170
203
  }
171
- // Refuse fee-bearing partial plans for an unreachable borrow.
204
+ // Refuse fee-bearing partial plans for an unreachable operation.
172
205
  if (totalReallocated < absoluteShortfall) {
173
206
  throw new index_js_1.InsufficientSharedLiquidityError({
174
207
  marketId,
@@ -1,5 +1,5 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
2
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";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
- export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./slippage.js";
5
- 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,6 +1,6 @@
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.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;
3
+ exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinWithdrawSharePrice = exports.computeMinBorrowSharePrice = exports.computeMaxSupplySharePrice = 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
6
  var constant_js_1 = require("./constant.js");
@@ -15,11 +15,13 @@ var metadata_js_1 = require("./metadata.js");
15
15
  Object.defineProperty(exports, "addTransactionMetadata", { enumerable: true, get: function () { return metadata_js_1.addTransactionMetadata; } });
16
16
  var slippage_js_1 = require("./slippage.js");
17
17
  Object.defineProperty(exports, "computeMaxRepaySharePrice", { enumerable: true, get: function () { return slippage_js_1.computeMaxRepaySharePrice; } });
18
+ Object.defineProperty(exports, "computeMaxSupplySharePrice", { enumerable: true, get: function () { return slippage_js_1.computeMaxSupplySharePrice; } });
18
19
  Object.defineProperty(exports, "computeMinBorrowSharePrice", { enumerable: true, get: function () { return slippage_js_1.computeMinBorrowSharePrice; } });
20
+ Object.defineProperty(exports, "computeMinWithdrawSharePrice", { enumerable: true, get: function () { return slippage_js_1.computeMinWithdrawSharePrice; } });
19
21
  var validate_js_1 = require("./validate.js");
20
22
  Object.defineProperty(exports, "validateAccrualPosition", { enumerable: true, get: function () { return validate_js_1.validateAccrualPosition; } });
21
23
  Object.defineProperty(exports, "validateChainId", { enumerable: true, get: function () { return validate_js_1.validateChainId; } });
22
- Object.defineProperty(exports, "validateNativeCollateral", { enumerable: true, get: function () { return validate_js_1.validateNativeCollateral; } });
24
+ Object.defineProperty(exports, "validateNativeAsset", { enumerable: true, get: function () { return validate_js_1.validateNativeAsset; } });
23
25
  Object.defineProperty(exports, "validatePositionHealth", { enumerable: true, get: function () { return validate_js_1.validatePositionHealth; } });
24
26
  Object.defineProperty(exports, "validatePositionHealthAfterWithdraw", { enumerable: true, get: function () { return validate_js_1.validatePositionHealthAfterWithdraw; } });
25
27
  Object.defineProperty(exports, "validateReallocations", { enumerable: true, get: function () { return validate_js_1.validateReallocations; } });
@@ -28,3 +30,5 @@ Object.defineProperty(exports, "validateRepayParams", { enumerable: true, get: f
28
30
  Object.defineProperty(exports, "validateRepayShares", { enumerable: true, get: function () { return validate_js_1.validateRepayShares; } });
29
31
  Object.defineProperty(exports, "validateSlippageTolerance", { enumerable: true, get: function () { return validate_js_1.validateSlippageTolerance; } });
30
32
  Object.defineProperty(exports, "validateUserAddress", { enumerable: true, get: function () { return validate_js_1.validateUserAddress; } });
33
+ Object.defineProperty(exports, "validateWithdrawAmount", { enumerable: true, get: function () { return validate_js_1.validateWithdrawAmount; } });
34
+ Object.defineProperty(exports, "validateWithdrawShares", { enumerable: true, get: function () { return validate_js_1.validateWithdrawShares; } });
@@ -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;
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.computeMinBorrowSharePrice = computeMinBorrowSharePrice;
4
4
  exports.computeMaxRepaySharePrice = computeMaxRepaySharePrice;
5
+ exports.computeMaxSupplySharePrice = computeMaxSupplySharePrice;
6
+ exports.computeMinWithdrawSharePrice = computeMinWithdrawSharePrice;
5
7
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
8
  const index_js_1 = require("../types/index.js");
7
9
  const constant_js_1 = require("./constant.js");
@@ -71,3 +73,83 @@ function computeMaxRepaySharePrice(params) {
71
73
  const maxSharePrice = blue_sdk_1.MathLib.mulDivUp(assets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD + slippageTolerance), shares);
72
74
  return blue_sdk_1.MathLib.min(maxSharePrice, constant_js_1.MAX_ABSOLUTE_SHARE_PRICE);
73
75
  }
76
+ /**
77
+ * Computes the maximum supply share price (in RAY, 1e27) for slippage protection.
78
+ *
79
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoSupply`:
80
+ * ```solidity
81
+ * require(suppliedAssets.rDivUp(suppliedShares) <= maxSharePriceE27)
82
+ * ```
83
+ *
84
+ * Caps at {@link MAX_ABSOLUTE_SHARE_PRICE} to prevent absurd values on extreme markets.
85
+ *
86
+ * @param params - Computation parameters.
87
+ * @param params.supplyAssets - The amount of loan assets to supply.
88
+ * @param params.market - The market to compute the maximum supply share price for.
89
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
90
+ * @returns `maxSharePriceE27` in RAY scale (1e27).
91
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
92
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
93
+ */
94
+ function computeMaxSupplySharePrice(params) {
95
+ const { supplyAssets, market, slippageTolerance } = params;
96
+ if (slippageTolerance >= blue_sdk_1.MathLib.WAD) {
97
+ throw new index_js_1.ExcessiveSlippageToleranceError(slippageTolerance);
98
+ }
99
+ const expectedShares = market.toSupplyShares(supplyAssets, "Down");
100
+ if (expectedShares === 0n) {
101
+ throw new index_js_1.ShareDivideByZeroError(market.params.id);
102
+ }
103
+ const maxSharePrice = blue_sdk_1.MathLib.mulDivUp(supplyAssets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD + slippageTolerance), expectedShares);
104
+ return blue_sdk_1.MathLib.min(maxSharePrice, constant_js_1.MAX_ABSOLUTE_SHARE_PRICE);
105
+ }
106
+ /**
107
+ * Computes the minimum withdraw share price (in RAY, 1e27) for slippage protection.
108
+ *
109
+ * Mirrors the on-chain check in GeneralAdapter1's `morphoWithdraw`:
110
+ * ```solidity
111
+ * require(withdrawnAssets.rDivDown(withdrawnShares) >= minSharePriceE27)
112
+ * ```
113
+ *
114
+ * Supports both assets and shares modes:
115
+ * - By assets: derives expected shares via `toSupplyShares("Up")` (upper bound, protects the
116
+ * withdrawer against over-burning shares).
117
+ * - By shares: derives expected assets via `toSupplyAssets("Down")` (lower bound, the on-chain
118
+ * amount paid out).
119
+ *
120
+ * Direction is opposite of supply's `maxSharePrice`:
121
+ * - Supply uses `(WAD + slippage)` → upper bound (anti-inflation).
122
+ * - Withdraw uses `(WAD − slippage)` → lower bound (protects withdrawer from receiving too few
123
+ * assets per share burned).
124
+ *
125
+ * @param params - Computation parameters.
126
+ * @param params.withdrawAssets - The amount of assets to withdraw (`0n` when withdrawing by shares).
127
+ * @param params.withdrawShares - The amount of shares to withdraw (`0n` when withdrawing by assets).
128
+ * @param params.market - The market to compute the minimum withdraw share price for.
129
+ * @param params.slippageTolerance - Slippage tolerance in WAD (e.g. `0.003e18` = 0.3%).
130
+ * @returns `minSharePriceE27` in RAY scale (1e27).
131
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance >= WAD`.
132
+ * @throws {ShareDivideByZeroError} when expected shares round down to zero.
133
+ */
134
+ function computeMinWithdrawSharePrice(params) {
135
+ const { withdrawAssets, withdrawShares, market, slippageTolerance } = params;
136
+ if (slippageTolerance >= blue_sdk_1.MathLib.WAD) {
137
+ throw new index_js_1.ExcessiveSlippageToleranceError(slippageTolerance);
138
+ }
139
+ let assets;
140
+ let shares;
141
+ if (withdrawShares > 0n) {
142
+ assets = market.toSupplyAssets(withdrawShares, "Down");
143
+ shares = withdrawShares;
144
+ }
145
+ else {
146
+ assets = withdrawAssets;
147
+ shares = market.toSupplyShares(withdrawAssets, "Up");
148
+ }
149
+ // Dust shares can round to `assets === 0n` here, which would make
150
+ // `minSharePriceE27 = 0` and silently nullify the on-chain slippage cap.
151
+ if (shares === 0n || assets === 0n) {
152
+ throw new index_js_1.ShareDivideByZeroError(market.params.id);
153
+ }
154
+ return blue_sdk_1.MathLib.mulDivDown(assets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD - slippageTolerance), shares);
155
+ }