@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
package/README.md CHANGED
@@ -31,10 +31,12 @@ pnpm add @morpho-org/morpho-sdk
31
31
  | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
32
32
  | | `withdraw` | Direct vault call | No attack surface |
33
33
  | | `redeem` | Direct vault call | No attack surface |
34
- | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
34
+ | **MarketV1** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
35
+ | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
35
36
  | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
36
37
  | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
37
38
  | | `repay` | Bundler (general adapter) | `erc20TransferFrom` + `morphoRepay` with `maxSharePrice` protection. Supports partial or full. |
39
+ | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
38
40
  | | `withdrawCollateral` | Direct Morpho call | No bundler overhead. Validates position health after withdrawal. |
39
41
  | | `repayWithdrawCollateral` | Bundler (general adapter) | Atomic repay + withdraw. Bundle order matters: repay first, then withdraw. |
40
42
 
@@ -81,9 +83,11 @@ const tx = buildTx(permitSignature);
81
83
  | | `withdraw` | Direct vault call | No attack surface |
82
84
  | | `redeem` | Direct vault call | No attack surface |
83
85
  | | `migrateToV2` | Bundler (general adapter) | Atomic V1 → V2 migration: redeem V1 shares + deposit into V2 in one tx. Slippage-protected. |
84
- | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
86
+ | **MarketV1** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
87
+ | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
85
88
  | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
86
89
  | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
90
+ | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
87
91
 
88
92
  ### VaultV2
89
93
 
@@ -252,6 +256,37 @@ const market = client.morpho.marketV1(
252
256
  );
253
257
  ```
254
258
 
259
+ #### Supply (loan asset)
260
+
261
+ Supply the loan asset to earn yield on the market.
262
+
263
+ ```typescript
264
+ const marketData = await market.getMarketData();
265
+
266
+ const { buildTx, getRequirements } = market.supply({
267
+ amount: 1000000000n,
268
+ userAddress: "0xUser...",
269
+ marketData,
270
+ });
271
+
272
+ const requirements = await getRequirements();
273
+ const tx = buildTx(requirementSignature);
274
+ ```
275
+
276
+ ##### Supply with native token wrapping
277
+
278
+ If the market's `loanToken` is the chain's wNative, you can supply native token that will be wrapped automatically:
279
+
280
+ ```typescript
281
+ const { buildTx, getRequirements } = market.supply({
282
+ nativeAmount: 1000000000000000000n,
283
+ userAddress: "0xUser...",
284
+ marketData,
285
+ });
286
+ ```
287
+
288
+ The bundle routes through `GeneralAdapter1` with `maxSharePrice` slippage protection (anti-inflation guard).
289
+
255
290
  #### Supply Collateral
256
291
 
257
292
  ```typescript
@@ -322,6 +357,33 @@ const tx = buildTx(requirementSignature);
322
357
 
323
358
  Repay does **not** require Morpho authorization (it only requires a loan token approval for `GeneralAdapter1`).
324
359
 
360
+ #### Withdraw (loan asset)
361
+
362
+ Two modes — `assets` (exact amount) or `shares` (full close, immune to interest accrual between quote and inclusion). Routed through bundler3 with `minSharePrice` slippage protection; the withdrawn assets are sent directly to `receiver` (defaults to `userAddress`). Optional `reallocations` top up market liquidity via the **PublicAllocator** when the on-market liquidity is insufficient (same mechanism as `borrow`).
363
+
364
+ ```typescript
365
+ const positionData = await market.getPositionData("0xUser...");
366
+
367
+ // Withdraw an exact amount of loan asset
368
+ const { buildTx, getRequirements } = market.withdraw({
369
+ assets: 500000000n,
370
+ userAddress: "0xUser...",
371
+ positionData,
372
+ });
373
+
374
+ // Or close the full supply position by shares
375
+ const { buildTx, getRequirements } = market.withdraw({
376
+ shares: positionData.supplyShares,
377
+ userAddress: "0xUser...",
378
+ positionData,
379
+ });
380
+
381
+ const requirements = await getRequirements();
382
+ const tx = buildTx();
383
+ ```
384
+
385
+ Loan-asset withdraw requires Morpho authorization for `GeneralAdapter1` (returned by `getRequirements` when missing). It does **not** require a token approval.
386
+
325
387
  #### Withdraw Collateral
326
388
 
327
389
  ```typescript
@@ -443,13 +505,17 @@ graph LR
443
505
 
444
506
  subgraph MarketV1 Flow
445
507
  MM1[MorphoMarketV1]
508
+ MM1 --> M1S[marketV1Supply]
446
509
  MM1 --> M1SC[marketV1SupplyCollateral]
447
510
  MM1 --> M1B[marketV1Borrow]
448
511
  MM1 --> M1SCB[marketV1SupplyCollateralBorrow]
512
+ MM1 --> M1W[marketV1Withdraw]
449
513
 
450
- M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3[Bundler3]
514
+ M1S -->|nativeWrap? + erc20TransferFrom + morphoSupply| B3[Bundler3]
515
+ M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3
451
516
  M1B -->|reallocateTo? + morphoBorrow| B3
452
517
  M1SCB -->|transfer + supplyCollateral + reallocateTo? + borrow| B3
518
+ M1W -->|reallocateTo? + morphoWithdraw| B3
453
519
 
454
520
  B3 -.->|reallocateTo| PA[PublicAllocator]
455
521
  end
@@ -1,6 +1,8 @@
1
1
  export * from "./borrow.js";
2
2
  export * from "./repay.js";
3
3
  export * from "./repayWithdrawCollateral.js";
4
+ export * from "./supply.js";
4
5
  export * from "./supplyCollateral.js";
5
6
  export * from "./supplyCollateralBorrow.js";
7
+ export * from "./withdraw.js";
6
8
  export * from "./withdrawCollateral.js";
@@ -17,6 +17,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./borrow.js"), exports);
18
18
  __exportStar(require("./repay.js"), exports);
19
19
  __exportStar(require("./repayWithdrawCollateral.js"), exports);
20
+ __exportStar(require("./supply.js"), exports);
20
21
  __exportStar(require("./supplyCollateral.js"), exports);
21
22
  __exportStar(require("./supplyCollateralBorrow.js"), exports);
23
+ __exportStar(require("./withdraw.js"), exports);
22
24
  __exportStar(require("./withdrawCollateral.js"), exports);
@@ -0,0 +1,69 @@
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
+ import type { Address } from "viem";
3
+ import { type DepositAmountArgs, type MarketV1SupplyAction, type Metadata, type RequirementSignature, type Transaction } from "../../types/index.js";
4
+ /** Parameters for {@link marketV1Supply}. */
5
+ export interface MarketV1SupplyParams {
6
+ market: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ args: DepositAmountArgs & {
11
+ onBehalf: Address;
12
+ /** Maximum supply share price (in ray). Slippage protection against inflation attacks. */
13
+ maxSharePrice: bigint;
14
+ requirementSignature?: RequirementSignature;
15
+ };
16
+ metadata?: Metadata;
17
+ }
18
+ /**
19
+ * Prepares a loan-asset supply transaction for a Morpho Blue market.
20
+ *
21
+ * Routed through bundler3 via `GeneralAdapter1`. When `nativeAmount > 0`, native ETH is wrapped
22
+ * via `GeneralAdapter1.wrapNative()` before the supply; the loan token must be the chain's
23
+ * wNative for that path. Uses `maxSharePrice` to protect against share-price inflation between
24
+ * transaction construction and execution.
25
+ *
26
+ * Zero loss: all supplied assets reach Morpho. No dust left in bundler or adapter.
27
+ *
28
+ * @param params.market.chainId - The chain the market lives on.
29
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
30
+ * @param params.args.amount - Amount of ERC-20 loan asset to supply. At least one of `amount` or
31
+ * `nativeAmount` must be positive. Defaults to `0n`.
32
+ * @param params.args.onBehalf - Address whose Morpho supply position is credited.
33
+ * @param params.args.maxSharePrice - Maximum acceptable supply share price (in ray). Slippage
34
+ * protection.
35
+ * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
36
+ * supply. Requires the loan token to be the chain's wNative.
37
+ * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval. When
38
+ * absent, the bundle uses a plain `erc20TransferFrom` and assumes the user has already
39
+ * approved `GeneralAdapter1`.
40
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
41
+ * @returns A deep-frozen `Transaction<MarketV1SupplyAction>` with `to`, `value`, `data`, and the
42
+ * typed `action` discriminator the simulation layer consumes.
43
+ * @throws {NegativeSupplyAmountError} when `amount < 0n`.
44
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
45
+ * @throws {ZeroSupplyAmountError} when both `amount` and `nativeAmount` resolve to zero.
46
+ * @throws {NegativeSupplyMaxSharePriceError} when `maxSharePrice < 0n`.
47
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
48
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
49
+ * the chain's wNative.
50
+ * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
51
+ * is provided and the signed asset differs from `marketParams.loanToken`.
52
+ * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
53
+ * is provided and the signed amount differs from `args.amount`.
54
+ * @example
55
+ * ```ts
56
+ * import { marketV1Supply } from "@morpho-org/morpho-sdk";
57
+ *
58
+ * const tx = marketV1Supply({
59
+ * market: { chainId: 1, marketParams },
60
+ * args: {
61
+ * amount: 1_000_000_000n,
62
+ * onBehalf: supplier,
63
+ * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
64
+ * },
65
+ * });
66
+ * // tx satisfies Readonly<Transaction<MarketV1SupplyAction>>
67
+ * ```
68
+ */
69
+ export declare const marketV1Supply: ({ market: { chainId, marketParams }, args: { amount, onBehalf, maxSharePrice, requirementSignature, nativeAmount, }, metadata, }: MarketV1SupplyParams) => Readonly<Transaction<MarketV1SupplyAction>>;
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.marketV1Supply = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const index_js_1 = require("../../bundler/index.js");
7
+ const index_js_2 = require("../../helpers/index.js");
8
+ const index_js_3 = require("../../types/index.js");
9
+ const getRequirementsAction_js_1 = require("../requirements/getRequirementsAction.js");
10
+ /**
11
+ * Prepares a loan-asset supply transaction for a Morpho Blue market.
12
+ *
13
+ * Routed through bundler3 via `GeneralAdapter1`. When `nativeAmount > 0`, native ETH is wrapped
14
+ * via `GeneralAdapter1.wrapNative()` before the supply; the loan token must be the chain's
15
+ * wNative for that path. Uses `maxSharePrice` to protect against share-price inflation between
16
+ * transaction construction and execution.
17
+ *
18
+ * Zero loss: all supplied assets reach Morpho. No dust left in bundler or adapter.
19
+ *
20
+ * @param params.market.chainId - The chain the market lives on.
21
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
22
+ * @param params.args.amount - Amount of ERC-20 loan asset to supply. At least one of `amount` or
23
+ * `nativeAmount` must be positive. Defaults to `0n`.
24
+ * @param params.args.onBehalf - Address whose Morpho supply position is credited.
25
+ * @param params.args.maxSharePrice - Maximum acceptable supply share price (in ray). Slippage
26
+ * protection.
27
+ * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
28
+ * supply. Requires the loan token to be the chain's wNative.
29
+ * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval. When
30
+ * absent, the bundle uses a plain `erc20TransferFrom` and assumes the user has already
31
+ * approved `GeneralAdapter1`.
32
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
33
+ * @returns A deep-frozen `Transaction<MarketV1SupplyAction>` with `to`, `value`, `data`, and the
34
+ * typed `action` discriminator the simulation layer consumes.
35
+ * @throws {NegativeSupplyAmountError} when `amount < 0n`.
36
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
37
+ * @throws {ZeroSupplyAmountError} when both `amount` and `nativeAmount` resolve to zero.
38
+ * @throws {NegativeSupplyMaxSharePriceError} when `maxSharePrice < 0n`.
39
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
40
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
41
+ * the chain's wNative.
42
+ * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
43
+ * is provided and the signed asset differs from `marketParams.loanToken`.
44
+ * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
45
+ * is provided and the signed amount differs from `args.amount`.
46
+ * @example
47
+ * ```ts
48
+ * import { marketV1Supply } from "@morpho-org/morpho-sdk";
49
+ *
50
+ * const tx = marketV1Supply({
51
+ * market: { chainId: 1, marketParams },
52
+ * args: {
53
+ * amount: 1_000_000_000n,
54
+ * onBehalf: supplier,
55
+ * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
56
+ * },
57
+ * });
58
+ * // tx satisfies Readonly<Transaction<MarketV1SupplyAction>>
59
+ * ```
60
+ */
61
+ const marketV1Supply = ({ market: { chainId, marketParams }, args: { amount = 0n, onBehalf, maxSharePrice, requirementSignature, nativeAmount, }, metadata, }) => {
62
+ if (amount < 0n) {
63
+ throw new index_js_3.NegativeSupplyAmountError(marketParams.id);
64
+ }
65
+ if (nativeAmount !== undefined && nativeAmount < 0n) {
66
+ throw new index_js_3.NegativeNativeAmountError(nativeAmount);
67
+ }
68
+ if (maxSharePrice < 0n) {
69
+ throw new index_js_3.NegativeSupplyMaxSharePriceError(marketParams.id);
70
+ }
71
+ const totalAssets = amount + (nativeAmount ?? 0n);
72
+ if (totalAssets === 0n) {
73
+ throw new index_js_3.ZeroSupplyAmountError(marketParams.id);
74
+ }
75
+ const { bundler3: { generalAdapter1, bundler3 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
76
+ const actions = [];
77
+ if (nativeAmount !== undefined && nativeAmount > 0n) {
78
+ (0, index_js_2.validateNativeAsset)(chainId, marketParams.loanToken);
79
+ actions.push({
80
+ type: "nativeTransfer",
81
+ args: [bundler3, generalAdapter1, nativeAmount, false],
82
+ }, {
83
+ type: "wrapNative",
84
+ args: [nativeAmount, generalAdapter1, false],
85
+ });
86
+ }
87
+ if (amount > 0n) {
88
+ if (requirementSignature) {
89
+ actions.push(...(0, getRequirementsAction_js_1.getRequirementsAction)({
90
+ asset: marketParams.loanToken,
91
+ amount,
92
+ recipient: generalAdapter1,
93
+ requirementSignature,
94
+ }));
95
+ }
96
+ else {
97
+ actions.push({
98
+ type: "erc20TransferFrom",
99
+ args: [marketParams.loanToken, amount, generalAdapter1, false],
100
+ });
101
+ }
102
+ }
103
+ actions.push({
104
+ type: "morphoSupply",
105
+ args: [marketParams, totalAssets, 0n, maxSharePrice, onBehalf, [], false],
106
+ });
107
+ let tx = {
108
+ ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
109
+ value: nativeAmount ?? 0n,
110
+ };
111
+ if (metadata) {
112
+ tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
113
+ }
114
+ return (0, morpho_ts_1.deepFreeze)({
115
+ ...tx,
116
+ action: {
117
+ type: "marketV1Supply",
118
+ args: {
119
+ market: marketParams.id,
120
+ amount: totalAssets,
121
+ onBehalf,
122
+ maxSharePrice,
123
+ nativeAmount,
124
+ },
125
+ },
126
+ });
127
+ };
128
+ exports.marketV1Supply = marketV1Supply;
@@ -39,7 +39,7 @@ export interface MarketV1SupplyCollateralParams {
39
39
  * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
40
40
  * @throws {ZeroCollateralAmountError} when both `amount` and `nativeAmount` resolve to zero.
41
41
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
42
- * @throws {NativeAmountOnNonWNativeCollateralError} when `nativeAmount > 0n` but the collateral
42
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
43
43
  * token is not the chain's wNative.
44
44
  * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
45
45
  * is provided and the signed asset differs from `marketParams.collateralToken`.
@@ -33,7 +33,7 @@ const getRequirementsAction_js_1 = require("../requirements/getRequirementsActio
33
33
  * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
34
34
  * @throws {ZeroCollateralAmountError} when both `amount` and `nativeAmount` resolve to zero.
35
35
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
36
- * @throws {NativeAmountOnNonWNativeCollateralError} when `nativeAmount > 0n` but the collateral
36
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
37
37
  * token is not the chain's wNative.
38
38
  * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
39
39
  * is provided and the signed asset differs from `marketParams.collateralToken`.
@@ -66,7 +66,7 @@ const marketV1SupplyCollateral = ({ market: { chainId, marketParams }, args: { a
66
66
  const { bundler3: { generalAdapter1, bundler3 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
67
67
  const actions = [];
68
68
  if (nativeAmount !== undefined && nativeAmount > 0n) {
69
- (0, index_js_2.validateNativeCollateral)(chainId, marketParams.collateralToken);
69
+ (0, index_js_2.validateNativeAsset)(chainId, marketParams.collateralToken);
70
70
  actions.push({
71
71
  type: "nativeTransfer",
72
72
  args: [bundler3, generalAdapter1, nativeAmount, false],
@@ -55,7 +55,7 @@ export interface MarketV1SupplyCollateralBorrowParams {
55
55
  * @throws {NonPositiveMinBorrowSharePriceError} when `minSharePrice < 0n`.
56
56
  * @throws {ZeroCollateralAmountError} when both `amount` and `nativeAmount` resolve to zero.
57
57
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
58
- * @throws {NativeAmountOnNonWNativeCollateralError} when `nativeAmount > 0n` but the collateral
58
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
59
59
  * token is not the chain's wNative.
60
60
  * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
61
61
  * is provided and the signed asset differs from `marketParams.collateralToken`.
@@ -44,7 +44,7 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
44
44
  * @throws {NonPositiveMinBorrowSharePriceError} when `minSharePrice < 0n`.
45
45
  * @throws {ZeroCollateralAmountError} when both `amount` and `nativeAmount` resolve to zero.
46
46
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
47
- * @throws {NativeAmountOnNonWNativeCollateralError} when `nativeAmount > 0n` but the collateral
47
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
48
48
  * token is not the chain's wNative.
49
49
  * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
50
50
  * is provided and the signed asset differs from `marketParams.collateralToken`.
@@ -99,7 +99,7 @@ const marketV1SupplyCollateralBorrow = ({ market: { chainId, marketParams }, arg
99
99
  const { bundler3: { generalAdapter1, bundler3 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
100
100
  const actions = [];
101
101
  if (nativeAmount !== undefined && nativeAmount > 0n) {
102
- (0, index_js_2.validateNativeCollateral)(chainId, marketParams.collateralToken);
102
+ (0, index_js_2.validateNativeAsset)(chainId, marketParams.collateralToken);
103
103
  actions.push({
104
104
  type: "nativeTransfer",
105
105
  args: [bundler3, generalAdapter1, nativeAmount, false],
@@ -0,0 +1,83 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import type { Address } from "viem";
3
+ import { type MarketV1WithdrawAction, type Metadata, type Transaction, type VaultReallocation } from "../../types/index.js";
4
+ /** Parameters for {@link marketV1Withdraw}. */
5
+ export interface MarketV1WithdrawParams {
6
+ market: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ args: {
11
+ /** Withdraw assets amount (`0n` when withdrawing by shares). */
12
+ assets: bigint;
13
+ /** Withdraw shares amount (`0n` when withdrawing by assets). */
14
+ shares: bigint;
15
+ /** Address that receives the withdrawn assets. */
16
+ receiver: Address;
17
+ /** Minimum withdraw share price (in ray). Slippage protection. */
18
+ minSharePrice: bigint;
19
+ /**
20
+ * Vault reallocations to execute before withdrawing. Compute via
21
+ * `MorphoMarketV1.getReallocations({ operation: "withdraw", amount })` or directly via
22
+ * `computeReallocations({ operation: "withdraw", amount, ... })`.
23
+ */
24
+ reallocations?: readonly VaultReallocation[];
25
+ };
26
+ metadata?: Metadata;
27
+ }
28
+ /**
29
+ * Prepares a loan-asset withdraw transaction for a Morpho Blue market.
30
+ *
31
+ * Routed through bundler3 via `morphoWithdraw`. Supports two modes (exactly one):
32
+ *
33
+ * - **By assets** (`assets > 0, shares = 0`): withdraws an exact asset amount.
34
+ * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
35
+ * supplier position close; immune to interest accrual between tx construction and execution).
36
+ *
37
+ * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
38
+ * liquidity from other markets into this one via the PublicAllocator before withdrawing.
39
+ * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
40
+ * computed on-chain directly to `receiver`; no skim is required.
41
+ *
42
+ * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
43
+ * separate `onBehalf` field; mirror `marketV1Borrow`. The entity layer keeps `receiver` aligned
44
+ * with the user when none is provided. Requires the user to have authorized `GeneralAdapter1`
45
+ * on Morpho.
46
+ *
47
+ * @param params.market.chainId - The chain the market lives on.
48
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
49
+ * @param params.args.assets - Withdraw amount in loan-token assets. Set to `0n` in shares mode.
50
+ * @param params.args.shares - Withdraw amount in supply shares. Set to `0n` in assets mode.
51
+ * @param params.args.receiver - Address that receives the withdrawn assets.
52
+ * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
53
+ * protection.
54
+ * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
55
+ * computed by the entity layer.
56
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
57
+ * @returns A deep-frozen `Transaction<MarketV1WithdrawAction>` with `to`, `value`, `data`, and
58
+ * the typed `action` discriminator the simulation layer consumes.
59
+ * @throws {NonPositiveWithdrawAmountError} when both `assets` and `shares` are zero, or either is negative.
60
+ * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
61
+ * @throws {NegativeWithdrawMinSharePriceError} when `minSharePrice < 0n` (zero is allowed despite
62
+ * the class name — pattern preserved for symmetry with `marketV1Borrow`).
63
+ * @throws Reallocation errors from `buildReallocationActions` when `reallocations` is malformed
64
+ * (see its JSDoc: `NegativeReallocationFeeError`, `EmptyReallocationWithdrawalsError`,
65
+ * `NonPositiveReallocationAmountError`, `ReallocationWithdrawalOnTargetMarketError`,
66
+ * `UnsortedReallocationWithdrawalsError`).
67
+ * @example
68
+ * ```ts
69
+ * import { marketV1Withdraw } from "@morpho-org/morpho-sdk";
70
+ *
71
+ * const tx = marketV1Withdraw({
72
+ * market: { chainId: 1, marketParams },
73
+ * args: {
74
+ * assets: 1_000_000_000n,
75
+ * shares: 0n,
76
+ * receiver: supplier,
77
+ * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinWithdrawSharePrice` from market state + slippage tolerance
78
+ * },
79
+ * });
80
+ * // tx satisfies Readonly<Transaction<MarketV1WithdrawAction>>
81
+ * ```
82
+ */
83
+ export declare const marketV1Withdraw: ({ market: { chainId, marketParams }, args: { assets, shares, receiver, minSharePrice, reallocations }, metadata, }: MarketV1WithdrawParams) => Readonly<Transaction<MarketV1WithdrawAction>>;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.marketV1Withdraw = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const index_js_1 = require("../../bundler/index.js");
6
+ const index_js_2 = require("../../helpers/index.js");
7
+ const index_js_3 = require("../../types/index.js");
8
+ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
9
+ /**
10
+ * Prepares a loan-asset withdraw transaction for a Morpho Blue market.
11
+ *
12
+ * Routed through bundler3 via `morphoWithdraw`. Supports two modes (exactly one):
13
+ *
14
+ * - **By assets** (`assets > 0, shares = 0`): withdraws an exact asset amount.
15
+ * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
16
+ * supplier position close; immune to interest accrual between tx construction and execution).
17
+ *
18
+ * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
19
+ * liquidity from other markets into this one via the PublicAllocator before withdrawing.
20
+ * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
21
+ * computed on-chain directly to `receiver`; no skim is required.
22
+ *
23
+ * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
24
+ * separate `onBehalf` field; mirror `marketV1Borrow`. The entity layer keeps `receiver` aligned
25
+ * with the user when none is provided. Requires the user to have authorized `GeneralAdapter1`
26
+ * on Morpho.
27
+ *
28
+ * @param params.market.chainId - The chain the market lives on.
29
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
30
+ * @param params.args.assets - Withdraw amount in loan-token assets. Set to `0n` in shares mode.
31
+ * @param params.args.shares - Withdraw amount in supply shares. Set to `0n` in assets mode.
32
+ * @param params.args.receiver - Address that receives the withdrawn assets.
33
+ * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
34
+ * protection.
35
+ * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
36
+ * computed by the entity layer.
37
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
38
+ * @returns A deep-frozen `Transaction<MarketV1WithdrawAction>` with `to`, `value`, `data`, and
39
+ * the typed `action` discriminator the simulation layer consumes.
40
+ * @throws {NonPositiveWithdrawAmountError} when both `assets` and `shares` are zero, or either is negative.
41
+ * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
42
+ * @throws {NegativeWithdrawMinSharePriceError} when `minSharePrice < 0n` (zero is allowed despite
43
+ * the class name — pattern preserved for symmetry with `marketV1Borrow`).
44
+ * @throws Reallocation errors from `buildReallocationActions` when `reallocations` is malformed
45
+ * (see its JSDoc: `NegativeReallocationFeeError`, `EmptyReallocationWithdrawalsError`,
46
+ * `NonPositiveReallocationAmountError`, `ReallocationWithdrawalOnTargetMarketError`,
47
+ * `UnsortedReallocationWithdrawalsError`).
48
+ * @example
49
+ * ```ts
50
+ * import { marketV1Withdraw } from "@morpho-org/morpho-sdk";
51
+ *
52
+ * const tx = marketV1Withdraw({
53
+ * market: { chainId: 1, marketParams },
54
+ * args: {
55
+ * assets: 1_000_000_000n,
56
+ * shares: 0n,
57
+ * receiver: supplier,
58
+ * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinWithdrawSharePrice` from market state + slippage tolerance
59
+ * },
60
+ * });
61
+ * // tx satisfies Readonly<Transaction<MarketV1WithdrawAction>>
62
+ * ```
63
+ */
64
+ const marketV1Withdraw = ({ market: { chainId, marketParams }, args: { assets, shares, receiver, minSharePrice, reallocations }, metadata, }) => {
65
+ // Mutual exclusion is detected on "both values present" (either non-zero),
66
+ // before sign checks — otherwise `{ assets: -1n, shares: 5n }` would be
67
+ // misreported as a positivity error rather than the actual mode conflict.
68
+ if (assets !== 0n && shares !== 0n) {
69
+ throw new index_js_3.MutuallyExclusiveWithdrawAmountsError(marketParams.id);
70
+ }
71
+ if (assets < 0n || shares < 0n || (assets === 0n && shares === 0n)) {
72
+ throw new index_js_3.NonPositiveWithdrawAmountError(marketParams.id);
73
+ }
74
+ if (minSharePrice < 0n) {
75
+ throw new index_js_3.NegativeWithdrawMinSharePriceError(marketParams.id);
76
+ }
77
+ const actions = [];
78
+ let reallocationFee = 0n;
79
+ if (reallocations && reallocations.length > 0) {
80
+ const result = (0, buildReallocationActions_js_1.buildReallocationActions)(reallocations, marketParams);
81
+ actions.push(...result.actions);
82
+ reallocationFee = result.fee;
83
+ }
84
+ actions.push({
85
+ type: "morphoWithdraw",
86
+ args: [marketParams, assets, shares, minSharePrice, receiver, false],
87
+ });
88
+ let tx = {
89
+ ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
90
+ value: reallocationFee,
91
+ };
92
+ if (metadata) {
93
+ tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
94
+ }
95
+ return (0, morpho_ts_1.deepFreeze)({
96
+ ...tx,
97
+ action: {
98
+ type: "marketV1Withdraw",
99
+ args: {
100
+ market: marketParams.id,
101
+ assets,
102
+ shares,
103
+ receiver,
104
+ minSharePrice,
105
+ reallocationFee,
106
+ },
107
+ },
108
+ });
109
+ };
110
+ exports.marketV1Withdraw = marketV1Withdraw;