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