@morpho-org/morpho-sdk 3.0.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/lib/cjs/actions/marketV1/index.d.ts +2 -0
  2. package/lib/cjs/actions/marketV1/index.js +2 -0
  3. package/lib/cjs/actions/marketV1/supply.d.ts +69 -0
  4. package/lib/cjs/actions/marketV1/supply.js +128 -0
  5. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +1 -1
  6. package/lib/cjs/actions/marketV1/supplyCollateral.js +2 -2
  7. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  8. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +2 -2
  9. package/lib/cjs/actions/marketV1/withdraw.d.ts +83 -0
  10. package/lib/cjs/actions/marketV1/withdraw.js +110 -0
  11. package/lib/cjs/bundler/actions.d.ts +82 -0
  12. package/lib/cjs/bundler/actions.js +135 -0
  13. package/lib/cjs/bundler/types.d.ts +19 -0
  14. package/lib/cjs/entities/marketV1/marketV1.d.ts +121 -18
  15. package/lib/cjs/entities/marketV1/marketV1.js +144 -12
  16. package/lib/cjs/helpers/computeReallocations.d.ts +17 -6
  17. package/lib/cjs/helpers/computeReallocations.js +42 -11
  18. package/lib/cjs/helpers/index.d.ts +2 -2
  19. package/lib/cjs/helpers/index.js +6 -2
  20. package/lib/cjs/helpers/slippage.d.ts +57 -0
  21. package/lib/cjs/helpers/slippage.js +82 -0
  22. package/lib/cjs/helpers/validate.d.ts +38 -7
  23. package/lib/cjs/helpers/validate.js +54 -11
  24. package/lib/cjs/types/action.d.ts +27 -6
  25. package/lib/cjs/types/error.d.ts +68 -6
  26. package/lib/cjs/types/error.js +85 -12
  27. package/lib/cjs/utils.d.ts +1 -1
  28. package/lib/cjs/utils.js +2 -2
  29. package/lib/esm/actions/marketV1/index.d.ts +2 -0
  30. package/lib/esm/actions/marketV1/index.js +2 -0
  31. package/lib/esm/actions/marketV1/supply.d.ts +69 -0
  32. package/lib/esm/actions/marketV1/supply.js +124 -0
  33. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +1 -1
  34. package/lib/esm/actions/marketV1/supplyCollateral.js +3 -3
  35. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  36. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +3 -3
  37. package/lib/esm/actions/marketV1/withdraw.d.ts +83 -0
  38. package/lib/esm/actions/marketV1/withdraw.js +106 -0
  39. package/lib/esm/bundler/actions.d.ts +82 -0
  40. package/lib/esm/bundler/actions.js +135 -0
  41. package/lib/esm/bundler/types.d.ts +19 -0
  42. package/lib/esm/entities/marketV1/marketV1.d.ts +121 -18
  43. package/lib/esm/entities/marketV1/marketV1.js +147 -15
  44. package/lib/esm/helpers/computeReallocations.d.ts +17 -6
  45. package/lib/esm/helpers/computeReallocations.js +43 -12
  46. package/lib/esm/helpers/index.d.ts +2 -2
  47. package/lib/esm/helpers/index.js +2 -2
  48. package/lib/esm/helpers/slippage.d.ts +57 -0
  49. package/lib/esm/helpers/slippage.js +80 -0
  50. package/lib/esm/helpers/validate.d.ts +38 -7
  51. package/lib/esm/helpers/validate.js +51 -10
  52. package/lib/esm/types/action.d.ts +27 -6
  53. package/lib/esm/types/error.d.ts +68 -6
  54. package/lib/esm/types/error.js +73 -9
  55. package/lib/esm/utils.d.ts +1 -1
  56. package/lib/esm/utils.js +1 -1
  57. package/package.json +14 -10
@@ -0,0 +1,106 @@
1
+ import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ import { BundlerAction } from "../../bundler/index.js";
3
+ import { addTransactionMetadata } from "../../helpers/index.js";
4
+ import { MutuallyExclusiveWithdrawAmountsError, NegativeWithdrawMinSharePriceError, NonPositiveWithdrawAmountError, } from "../../types/index.js";
5
+ import { buildReallocationActions } from "./buildReallocationActions.js";
6
+ /**
7
+ * Prepares a loan-asset withdraw transaction for a Morpho Blue market.
8
+ *
9
+ * Routed through bundler3 via `morphoWithdraw`. Supports two modes (exactly one):
10
+ *
11
+ * - **By assets** (`assets > 0, shares = 0`): withdraws an exact asset amount.
12
+ * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
13
+ * supplier position close; immune to interest accrual between tx construction and execution).
14
+ *
15
+ * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
16
+ * liquidity from other markets into this one via the PublicAllocator before withdrawing.
17
+ * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
18
+ * computed on-chain directly to `receiver`; no skim is required.
19
+ *
20
+ * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
21
+ * separate `onBehalf` field; mirror `marketV1Borrow`. The entity layer keeps `receiver` aligned
22
+ * with the user when none is provided. Requires the user to have authorized `GeneralAdapter1`
23
+ * on Morpho.
24
+ *
25
+ * @param params.market.chainId - The chain the market lives on.
26
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
27
+ * @param params.args.assets - Withdraw amount in loan-token assets. Set to `0n` in shares mode.
28
+ * @param params.args.shares - Withdraw amount in supply shares. Set to `0n` in assets mode.
29
+ * @param params.args.receiver - Address that receives the withdrawn assets.
30
+ * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
31
+ * protection.
32
+ * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
33
+ * computed by the entity layer.
34
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
35
+ * @returns A deep-frozen `Transaction<MarketV1WithdrawAction>` with `to`, `value`, `data`, and
36
+ * the typed `action` discriminator the simulation layer consumes.
37
+ * @throws {NonPositiveWithdrawAmountError} when both `assets` and `shares` are zero, or either is negative.
38
+ * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
39
+ * @throws {NegativeWithdrawMinSharePriceError} when `minSharePrice < 0n` (zero is allowed despite
40
+ * the class name — pattern preserved for symmetry with `marketV1Borrow`).
41
+ * @throws Reallocation errors from `buildReallocationActions` when `reallocations` is malformed
42
+ * (see its JSDoc: `NegativeReallocationFeeError`, `EmptyReallocationWithdrawalsError`,
43
+ * `NonPositiveReallocationAmountError`, `ReallocationWithdrawalOnTargetMarketError`,
44
+ * `UnsortedReallocationWithdrawalsError`).
45
+ * @example
46
+ * ```ts
47
+ * import { marketV1Withdraw } from "@morpho-org/morpho-sdk";
48
+ *
49
+ * const tx = marketV1Withdraw({
50
+ * market: { chainId: 1, marketParams },
51
+ * args: {
52
+ * assets: 1_000_000_000n,
53
+ * shares: 0n,
54
+ * receiver: supplier,
55
+ * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinWithdrawSharePrice` from market state + slippage tolerance
56
+ * },
57
+ * });
58
+ * // tx satisfies Readonly<Transaction<MarketV1WithdrawAction>>
59
+ * ```
60
+ */
61
+ export const marketV1Withdraw = ({ market: { chainId, marketParams }, args: { assets, shares, receiver, minSharePrice, reallocations }, metadata, }) => {
62
+ // Mutual exclusion is detected on "both values present" (either non-zero),
63
+ // before sign checks — otherwise `{ assets: -1n, shares: 5n }` would be
64
+ // misreported as a positivity error rather than the actual mode conflict.
65
+ if (assets !== 0n && shares !== 0n) {
66
+ throw new MutuallyExclusiveWithdrawAmountsError(marketParams.id);
67
+ }
68
+ if (assets < 0n || shares < 0n || (assets === 0n && shares === 0n)) {
69
+ throw new NonPositiveWithdrawAmountError(marketParams.id);
70
+ }
71
+ if (minSharePrice < 0n) {
72
+ throw new NegativeWithdrawMinSharePriceError(marketParams.id);
73
+ }
74
+ const actions = [];
75
+ let reallocationFee = 0n;
76
+ if (reallocations && reallocations.length > 0) {
77
+ const result = buildReallocationActions(reallocations, marketParams);
78
+ actions.push(...result.actions);
79
+ reallocationFee = result.fee;
80
+ }
81
+ actions.push({
82
+ type: "morphoWithdraw",
83
+ args: [marketParams, assets, shares, minSharePrice, receiver, false],
84
+ });
85
+ let tx = {
86
+ ...BundlerAction.encodeBundle(chainId, actions),
87
+ value: reallocationFee,
88
+ };
89
+ if (metadata) {
90
+ tx = addTransactionMetadata(tx, metadata);
91
+ }
92
+ return deepFreeze({
93
+ ...tx,
94
+ action: {
95
+ type: "marketV1Withdraw",
96
+ args: {
97
+ market: marketParams.id,
98
+ assets,
99
+ shares,
100
+ receiver,
101
+ minSharePrice,
102
+ reallocationFee,
103
+ },
104
+ },
105
+ });
106
+ };
@@ -372,6 +372,48 @@ export declare namespace BundlerAction {
372
372
  * ```
373
373
  */
374
374
  function morphoSupplyCollateral(chainId: number, market: InputMarketParams, assets: bigint, onBehalf: Address, callbackCalls: BundlerCall[], skipRevert?: boolean): BundlerCall[];
375
+ /**
376
+ * Encodes a GeneralAdapter1 Morpho Blue supply call.
377
+ *
378
+ * @param chainId - Chain where the action will execute.
379
+ * @param market - Morpho Blue market parameters.
380
+ * @param assets - Supply asset amount.
381
+ * @param shares - Supply share amount.
382
+ * @param slippageAmount - Slippage guard amount (max share price in RAY for share-price slippage).
383
+ * @param onBehalf - Account receiving the supply position.
384
+ * @param callbackCalls - Calls executed in Morpho's callback.
385
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
386
+ * @returns Encoded Bundler3 calls.
387
+ *
388
+ * @example
389
+ * ```ts
390
+ * import { BundlerAction } from "@morpho-org/morpho-sdk/bundler";
391
+ *
392
+ * const loanToken = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
393
+ * const collateralToken = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
394
+ * const oracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419";
395
+ * const irm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC";
396
+ * const onBehalf = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
397
+ * const marketParams = {
398
+ * loanToken,
399
+ * collateralToken,
400
+ * oracle,
401
+ * irm,
402
+ * lltv: 860_000000000000000000n,
403
+ * };
404
+ *
405
+ * const calls = BundlerAction.morphoSupply(
406
+ * 1,
407
+ * marketParams,
408
+ * 100n,
409
+ * 0n,
410
+ * 1_010000000000000000000000000n,
411
+ * onBehalf,
412
+ * [],
413
+ * );
414
+ * ```
415
+ */
416
+ function morphoSupply(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, slippageAmount: bigint, onBehalf: Address, callbackCalls: BundlerCall[], skipRevert?: boolean): BundlerCall[];
375
417
  /**
376
418
  * Encodes a GeneralAdapter1 Morpho Blue borrow call.
377
419
  *
@@ -454,6 +496,46 @@ export declare namespace BundlerAction {
454
496
  * ```
455
497
  */
456
498
  function morphoRepay(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, slippageAmount: bigint, onBehalf: Address, callbackCalls: BundlerCall[], skipRevert?: boolean): BundlerCall[];
499
+ /**
500
+ * Encodes a GeneralAdapter1 Morpho Blue withdraw call.
501
+ *
502
+ * @param chainId - Chain where the action will execute.
503
+ * @param market - Morpho Blue market parameters.
504
+ * @param assets - Withdraw asset amount.
505
+ * @param shares - Withdraw share amount.
506
+ * @param slippageAmount - Slippage guard amount (min share price in RAY for share-price slippage).
507
+ * @param receiver - Recipient of withdrawn assets.
508
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
509
+ * @returns Encoded Bundler3 calls.
510
+ *
511
+ * @example
512
+ * ```ts
513
+ * import { BundlerAction } from "@morpho-org/morpho-sdk/bundler";
514
+ *
515
+ * const loanToken = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
516
+ * const collateralToken = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
517
+ * const oracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419";
518
+ * const irm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC";
519
+ * const receiver = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
520
+ * const marketParams = {
521
+ * loanToken,
522
+ * collateralToken,
523
+ * oracle,
524
+ * irm,
525
+ * lltv: 860_000000000000000000n,
526
+ * };
527
+ *
528
+ * const calls = BundlerAction.morphoWithdraw(
529
+ * 1,
530
+ * marketParams,
531
+ * 100n,
532
+ * 0n,
533
+ * 990000000000000000000000000n,
534
+ * receiver,
535
+ * );
536
+ * ```
537
+ */
538
+ function morphoWithdraw(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, slippageAmount: bigint, receiver: Address, skipRevert?: boolean): BundlerCall[];
457
539
  /**
458
540
  * Encodes a GeneralAdapter1 Morpho Blue withdraw-collateral call.
459
541
  *
@@ -162,9 +162,16 @@ export var BundlerAction;
162
162
  const [market, amount, onBehalf, onMorphoSupplyCollateral, skipRevert] = args;
163
163
  return BundlerAction.morphoSupplyCollateral(chainId, market, amount, onBehalf, onMorphoSupplyCollateral.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
164
164
  }
165
+ case "morphoSupply": {
166
+ const [market, assets, shares, slippageAmount, onBehalf, onMorphoSupply, skipRevert,] = args;
167
+ return BundlerAction.morphoSupply(chainId, market, assets, shares, slippageAmount, onBehalf, onMorphoSupply.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
168
+ }
165
169
  case "morphoBorrow": {
166
170
  return BundlerAction.morphoBorrow(chainId, ...args);
167
171
  }
172
+ case "morphoWithdraw": {
173
+ return BundlerAction.morphoWithdraw(chainId, ...args);
174
+ }
168
175
  case "morphoRepay": {
169
176
  const [market, assets, shares, slippageAmount, onBehalf, onMorphoRepay, skipRevert,] = args;
170
177
  return BundlerAction.morphoRepay(chainId, market, assets, shares, slippageAmount, onBehalf, onMorphoRepay.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
@@ -209,6 +216,17 @@ export var BundlerAction;
209
216
  nextValueState = encodedCallback.valueState;
210
217
  }
211
218
  }
219
+ if (action.type === "morphoSupply") {
220
+ const [, , , , , onMorphoSupply] = action.args;
221
+ for (const callbackAction of onMorphoSupply) {
222
+ const encodedCallback = encodeBundleAction({
223
+ chainId,
224
+ action: callbackAction,
225
+ valueState: nextValueState,
226
+ });
227
+ nextValueState = encodedCallback.valueState;
228
+ }
229
+ }
212
230
  if (action.type === "morphoRepay") {
213
231
  const [, , , , , onMorphoRepay] = action.args;
214
232
  for (const callbackAction of onMorphoRepay) {
@@ -678,6 +696,66 @@ export var BundlerAction;
678
696
  ];
679
697
  }
680
698
  BundlerAction.morphoSupplyCollateral = morphoSupplyCollateral;
699
+ /**
700
+ * Encodes a GeneralAdapter1 Morpho Blue supply call.
701
+ *
702
+ * @param chainId - Chain where the action will execute.
703
+ * @param market - Morpho Blue market parameters.
704
+ * @param assets - Supply asset amount.
705
+ * @param shares - Supply share amount.
706
+ * @param slippageAmount - Slippage guard amount (max share price in RAY for share-price slippage).
707
+ * @param onBehalf - Account receiving the supply position.
708
+ * @param callbackCalls - Calls executed in Morpho's callback.
709
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
710
+ * @returns Encoded Bundler3 calls.
711
+ *
712
+ * @example
713
+ * ```ts
714
+ * import { BundlerAction } from "@morpho-org/morpho-sdk/bundler";
715
+ *
716
+ * const loanToken = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
717
+ * const collateralToken = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
718
+ * const oracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419";
719
+ * const irm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC";
720
+ * const onBehalf = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
721
+ * const marketParams = {
722
+ * loanToken,
723
+ * collateralToken,
724
+ * oracle,
725
+ * irm,
726
+ * lltv: 860_000000000000000000n,
727
+ * };
728
+ *
729
+ * const calls = BundlerAction.morphoSupply(
730
+ * 1,
731
+ * marketParams,
732
+ * 100n,
733
+ * 0n,
734
+ * 1_010000000000000000000000000n,
735
+ * onBehalf,
736
+ * [],
737
+ * );
738
+ * ```
739
+ */
740
+ // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
741
+ function morphoSupply(chainId, market, assets, shares, slippageAmount, onBehalf, callbackCalls, skipRevert = false) {
742
+ const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
743
+ const { callbackHash, reenterData } = encodeCallbackCalls(callbackCalls);
744
+ return [
745
+ {
746
+ to: generalAdapter1,
747
+ data: encodeFunctionData({
748
+ abi: generalAdapter1Abi,
749
+ functionName: "morphoSupply",
750
+ args: [market, assets, shares, slippageAmount, onBehalf, reenterData],
751
+ }),
752
+ value: 0n,
753
+ skipRevert,
754
+ callbackHash,
755
+ },
756
+ ];
757
+ }
758
+ BundlerAction.morphoSupply = morphoSupply;
681
759
  /**
682
760
  * Encodes a GeneralAdapter1 Morpho Blue borrow call.
683
761
  *
@@ -795,6 +873,63 @@ export var BundlerAction;
795
873
  ];
796
874
  }
797
875
  BundlerAction.morphoRepay = morphoRepay;
876
+ /**
877
+ * Encodes a GeneralAdapter1 Morpho Blue withdraw call.
878
+ *
879
+ * @param chainId - Chain where the action will execute.
880
+ * @param market - Morpho Blue market parameters.
881
+ * @param assets - Withdraw asset amount.
882
+ * @param shares - Withdraw share amount.
883
+ * @param slippageAmount - Slippage guard amount (min share price in RAY for share-price slippage).
884
+ * @param receiver - Recipient of withdrawn assets.
885
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
886
+ * @returns Encoded Bundler3 calls.
887
+ *
888
+ * @example
889
+ * ```ts
890
+ * import { BundlerAction } from "@morpho-org/morpho-sdk/bundler";
891
+ *
892
+ * const loanToken = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
893
+ * const collateralToken = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2";
894
+ * const oracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419";
895
+ * const irm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC";
896
+ * const receiver = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045";
897
+ * const marketParams = {
898
+ * loanToken,
899
+ * collateralToken,
900
+ * oracle,
901
+ * irm,
902
+ * lltv: 860_000000000000000000n,
903
+ * };
904
+ *
905
+ * const calls = BundlerAction.morphoWithdraw(
906
+ * 1,
907
+ * marketParams,
908
+ * 100n,
909
+ * 0n,
910
+ * 990000000000000000000000000n,
911
+ * receiver,
912
+ * );
913
+ * ```
914
+ */
915
+ // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
916
+ function morphoWithdraw(chainId, market, assets, shares, slippageAmount, receiver, skipRevert = false) {
917
+ const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
918
+ return [
919
+ {
920
+ to: generalAdapter1,
921
+ data: encodeFunctionData({
922
+ abi: generalAdapter1Abi,
923
+ functionName: "morphoWithdraw",
924
+ args: [market, assets, shares, slippageAmount, receiver],
925
+ }),
926
+ value: 0n,
927
+ skipRevert,
928
+ callbackHash: zeroHash,
929
+ },
930
+ ];
931
+ }
932
+ BundlerAction.morphoWithdraw = morphoWithdraw;
798
933
  /**
799
934
  * Encodes a GeneralAdapter1 Morpho Blue withdraw-collateral call.
800
935
  *
@@ -121,6 +121,16 @@ export interface ActionArgs {
121
121
  onMorphoSupplyCollateral: Action[],
122
122
  skipRevert?: boolean
123
123
  ];
124
+ /** Morpho Blue supply call for `market`, `assets` or `shares`, `slippageAmount`, `onBehalf`, and callback actions; `skipRevert` controls Bundler3 revert handling. */
125
+ readonly morphoSupply: [
126
+ market: InputMarketParams,
127
+ assets: bigint,
128
+ shares: bigint,
129
+ slippageAmount: bigint,
130
+ onBehalf: Address,
131
+ onMorphoSupply: Action[],
132
+ skipRevert?: boolean
133
+ ];
124
134
  /** Morpho Blue borrow call for `market`, `assets` or `shares`, `slippageAmount`, and `receiver`; `skipRevert` controls Bundler3 revert handling. */
125
135
  readonly morphoBorrow: [
126
136
  market: InputMarketParams,
@@ -140,6 +150,15 @@ export interface ActionArgs {
140
150
  onMorphoRepay: Action[],
141
151
  skipRevert?: boolean
142
152
  ];
153
+ /** Morpho Blue withdraw call for `market`, `assets` or `shares`, `slippageAmount`, and `receiver`; `skipRevert` controls Bundler3 revert handling. */
154
+ readonly morphoWithdraw: [
155
+ market: InputMarketParams,
156
+ assets: bigint,
157
+ shares: bigint,
158
+ slippageAmount: bigint,
159
+ receiver: Address,
160
+ skipRevert?: boolean
161
+ ];
143
162
  /** Morpho Blue withdraw-collateral call for `market`, `assets`, and `receiver`; `skipRevert` controls Bundler3 revert handling. */
144
163
  readonly morphoWithdrawCollateral: [
145
164
  market: InputMarketParams,
@@ -1,7 +1,7 @@
1
1
  import { type AccrualPosition, type Market, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
3
  import type { FetchParameters } from "../../types/data.js";
4
- import { type DepositAmountArgs, type ERC20ApprovalAction, type MarketV1BorrowAction, type MarketV1RepayAction, type MarketV1RepayWithdrawCollateralAction, type MarketV1SupplyCollateralAction, type MarketV1SupplyCollateralBorrowAction, type MarketV1WithdrawCollateralAction, type MorphoAuthorizationAction, type MorphoClientType, type ReallocationComputeOptions, type RepayAmountArgs, type Requirement, type RequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
4
+ import { type AssetsOrSharesArgs, type DepositAmountArgs, type ERC20ApprovalAction, type MarketV1BorrowAction, type MarketV1RepayAction, type MarketV1RepayWithdrawCollateralAction, type MarketV1SupplyAction, type MarketV1SupplyCollateralAction, type MarketV1SupplyCollateralBorrowAction, type MarketV1WithdrawAction, type MarketV1WithdrawCollateralAction, type MorphoAuthorizationAction, type MorphoClientType, type ReallocationComputeOptions, type RepayAmountArgs, type Requirement, type RequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
5
5
  import { ReallocationData } from "../reallocationData.js";
6
6
  export interface MarketV1Actions {
7
7
  /**
@@ -37,6 +37,61 @@ export interface MarketV1Actions {
37
37
  useSimplePermit?: boolean;
38
38
  }) => Promise<(Readonly<Transaction<ERC20ApprovalAction>> | Requirement)[]>;
39
39
  };
40
+ /**
41
+ * Prepares a loan-asset supply transaction.
42
+ *
43
+ * Routed through bundler via GeneralAdapter1. Computes `maxSharePrice` from market supply
44
+ * state and `slippageTolerance` to protect against share-price inflation.
45
+ * `getRequirements` returns ERC20 approval or permit for `GeneralAdapter1` on the loan token.
46
+ * When `nativeAmount` is provided, native token is wrapped; the loan token must be wNative.
47
+ *
48
+ * No Morpho authorization required (supplier is crediting, not withdrawing).
49
+ *
50
+ * @param params - Supply parameters.
51
+ * @returns Object with `buildTx` and `getRequirements`.
52
+ */
53
+ supply: (params: {
54
+ userAddress: Address;
55
+ marketData: Market;
56
+ slippageTolerance?: bigint;
57
+ } & DepositAmountArgs) => {
58
+ buildTx: (requirementSignature?: RequirementSignature) => Readonly<Transaction<MarketV1SupplyAction>>;
59
+ getRequirements: (params?: {
60
+ useSimplePermit?: boolean;
61
+ }) => Promise<(Readonly<Transaction<ERC20ApprovalAction>> | Requirement)[]>;
62
+ };
63
+ /**
64
+ * Prepares a loan-asset withdraw transaction.
65
+ *
66
+ * Routed through bundler3 via `morphoWithdraw`. Supports two modes via {@link AssetsOrSharesArgs}:
67
+ * - **By assets** (`{ assets }`): withdraws an exact asset amount.
68
+ * - **By shares** (`{ shares }`): burns an exact share count (full close, immune to interest accrual).
69
+ *
70
+ * Computes `minSharePrice` from market supply state and `slippageTolerance`.
71
+ *
72
+ * When `reallocations` is provided, `reallocateTo` actions are prepended to the bundle,
73
+ * moving liquidity from other markets via the PublicAllocator before withdrawing — used to
74
+ * unblock withdraws that exceed on-market liquidity.
75
+ *
76
+ * `getRequirements` returns `morpho.setAuthorization(generalAdapter1, true)` if GA1 is not
77
+ * yet authorized on Morpho (returns `[]` when already authorized), since the bundler calls
78
+ * `withdraw(...,onBehalf=user,...)`.
79
+ *
80
+ * **Stale `positionData` may cause unexpected supply share calculations.**
81
+ *
82
+ * @param params - Withdraw parameters including pre-fetched `positionData`.
83
+ * @returns Object with `buildTx` and `getRequirements`.
84
+ */
85
+ withdraw: (params: {
86
+ userAddress: Address;
87
+ receiver?: Address;
88
+ positionData: AccrualPosition;
89
+ slippageTolerance?: bigint;
90
+ reallocations?: readonly VaultReallocation[];
91
+ } & AssetsOrSharesArgs) => {
92
+ buildTx: () => Readonly<Transaction<MarketV1WithdrawAction>>;
93
+ getRequirements: () => Promise<Readonly<Transaction<MorphoAuthorizationAction>>[]>;
94
+ };
40
95
  /**
41
96
  * Prepares a borrow transaction.
42
97
  *
@@ -201,29 +256,43 @@ export interface MarketV1Actions {
201
256
  };
202
257
  }) => Promise<ReallocationData>;
203
258
  /**
204
- * Computes vault reallocations for a borrow on this market.
259
+ * Computes vault reallocations for a borrow or withdraw on this market.
205
260
  *
206
- * Uses the shared liquidity algorithm to determine which vaults should
207
- * reallocate liquidity to this market via the PublicAllocator, based on
208
- * post-borrow utilization targets.
261
+ * Uses the shared-liquidity algorithm to determine which vaults should reallocate liquidity to
262
+ * this market via the PublicAllocator, based on the post-operation utilization target.
263
+ *
264
+ * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow",
265
+ * amount }`) or `{ operation: "withdraw", amount }` for a loan-asset withdraw.
209
266
  *
210
267
  * @param params.reallocationData - The current on-chain state (from {@link getReallocationData}).
211
- * @param params.borrowAmount - The intended borrow amount.
268
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
269
+ * Defaults to `"borrow"` when `borrowAmount` is provided.
270
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
271
+ * @param params.borrowAmount - {@deprecated} Equivalent to `{ operation: "borrow", amount }`. Use the
272
+ * `operation` + `amount` form on new code.
212
273
  * @param params.options - Optional reallocation computation options
213
274
  * (timestamp, utilization targets, reallocatable vaults filter, etc.).
214
275
  * Pass the fetched block timestamp to compute reallocations at the same block.
215
- * @returns Array of vault reallocations ready to pass to `borrow()` or
216
- * `supplyCollateralBorrow()`. Empty array if no reallocation is needed.
276
+ * @returns Array of vault reallocations ready to pass to `borrow()`, `supplyCollateralBorrow()`,
277
+ * or `withdraw()`. Empty array if no reallocation is needed.
217
278
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market.
218
- * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market.
279
+ * @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.
219
280
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
220
281
  * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data.
221
282
  */
222
283
  getReallocations: (params: {
223
284
  reallocationData: ReallocationData;
224
- borrowAmount: bigint;
225
285
  options?: ReallocationComputeOptions;
226
- }) => readonly VaultReallocation[];
286
+ } & ({
287
+ operation: "borrow" | "withdraw";
288
+ amount: bigint;
289
+ borrowAmount?: never;
290
+ } | {
291
+ /** @deprecated Pass `{ operation: "borrow", amount }` instead. */
292
+ borrowAmount: bigint;
293
+ operation?: never;
294
+ amount?: never;
295
+ })) => readonly VaultReallocation[];
227
296
  }
228
297
  export declare class MorphoMarketV1 implements MarketV1Actions {
229
298
  private readonly client;
@@ -232,6 +301,26 @@ export declare class MorphoMarketV1 implements MarketV1Actions {
232
301
  constructor(client: MorphoClientType, marketParams: MarketParams, chainId: number);
233
302
  getMarketData(parameters?: FetchParameters): Promise<Market>;
234
303
  getPositionData(userAddress: Address, parameters?: FetchParameters): Promise<AccrualPosition>;
304
+ supply({ amount, userAddress, nativeAmount, marketData, slippageTolerance, }: {
305
+ userAddress: Address;
306
+ marketData: Market;
307
+ slippageTolerance?: bigint;
308
+ } & DepositAmountArgs): {
309
+ getRequirements: (params?: {
310
+ useSimplePermit?: boolean;
311
+ }) => Promise<(Requirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
312
+ buildTx: (requirementSignature?: RequirementSignature) => Readonly<Transaction<MarketV1SupplyAction>>;
313
+ };
314
+ withdraw(params: {
315
+ userAddress: Address;
316
+ receiver?: Address;
317
+ positionData: AccrualPosition;
318
+ slippageTolerance?: bigint;
319
+ reallocations?: readonly VaultReallocation[];
320
+ } & AssetsOrSharesArgs): {
321
+ getRequirements: () => Promise<Readonly<Transaction<MorphoAuthorizationAction>>[]>;
322
+ buildTx: () => Readonly<Transaction<MarketV1WithdrawAction>>;
323
+ };
235
324
  supplyCollateral({ amount, userAddress, nativeAmount, }: {
236
325
  userAddress: Address;
237
326
  } & DepositAmountArgs): {
@@ -307,21 +396,35 @@ export declare class MorphoMarketV1 implements MarketV1Actions {
307
396
  };
308
397
  }): Promise<ReallocationData>;
309
398
  /**
310
- * Computes public allocator reallocations for a borrow on this market.
399
+ * Computes public allocator reallocations for a borrow or withdraw on this market.
400
+ *
401
+ * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow", amount }`)
402
+ * or `{ operation, amount }` for a borrow or loan-asset withdraw.
311
403
  *
312
404
  * @param params - Reallocation computation parameters.
313
405
  * @param params.reallocationData - State returned by {@link getReallocationData}.
314
- * @param params.borrowAmount - Borrow amount to test against post-borrow utilization.
406
+ * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
407
+ * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
408
+ * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.}
315
409
  * @param params.options - Optional allocator and utilization options.
316
- * @returns Vault reallocations ready to pass to `borrow` or `supplyCollateralBorrow`.
410
+ * @returns Vault reallocations ready to pass to `borrow`, `supplyCollateralBorrow`, or `withdraw`.
317
411
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market.
318
- * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market.
412
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market.
413
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`.
319
414
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
320
415
  * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data.
321
416
  */
322
- getReallocations({ reallocationData, borrowAmount, options, }: {
417
+ getReallocations(params: {
323
418
  reallocationData: ReallocationData;
324
- borrowAmount: bigint;
325
419
  options?: ReallocationComputeOptions;
326
- }): readonly VaultReallocation[];
420
+ } & ({
421
+ operation: "borrow" | "withdraw";
422
+ amount: bigint;
423
+ borrowAmount?: never;
424
+ } | {
425
+ /** @deprecated Pass `{ operation: "borrow", amount }` instead. */
426
+ borrowAmount: bigint;
427
+ operation?: never;
428
+ amount?: never;
429
+ })): readonly VaultReallocation[];
327
430
  }