@morpho-org/consumer-sdk 0.3.0 → 0.5.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 (82) hide show
  1. package/README.md +301 -41
  2. package/lib/actions/index.d.ts +2 -0
  3. package/lib/actions/index.js +2 -0
  4. package/lib/actions/marketV1/borrow.d.ts +34 -0
  5. package/lib/actions/marketV1/borrow.js +62 -0
  6. package/lib/actions/marketV1/buildReallocationActions.d.ts +17 -0
  7. package/lib/actions/marketV1/buildReallocationActions.js +36 -0
  8. package/lib/actions/marketV1/index.d.ts +6 -0
  9. package/lib/actions/marketV1/index.js +22 -0
  10. package/lib/actions/marketV1/repay.d.ts +44 -0
  11. package/lib/actions/marketV1/repay.js +93 -0
  12. package/lib/actions/marketV1/repayWithdrawCollateral.d.ts +51 -0
  13. package/lib/actions/marketV1/repayWithdrawCollateral.js +108 -0
  14. package/lib/actions/marketV1/supplyCollateral.d.ts +28 -0
  15. package/lib/actions/marketV1/supplyCollateral.js +85 -0
  16. package/lib/actions/marketV1/supplyCollateralBorrow.d.ts +37 -0
  17. package/lib/actions/marketV1/supplyCollateralBorrow.js +109 -0
  18. package/lib/actions/marketV1/withdrawCollateral.d.ts +28 -0
  19. package/lib/actions/marketV1/withdrawCollateral.js +51 -0
  20. package/lib/actions/requirements/encode/encodeErc20Permit.js +4 -1
  21. package/lib/actions/requirements/encode/encodeErc20Permit2.js +4 -1
  22. package/lib/actions/requirements/getMorphoAuthorizationRequirement.d.ts +21 -0
  23. package/lib/actions/requirements/getMorphoAuthorizationRequirement.js +55 -0
  24. package/lib/actions/requirements/getRequirements.js +3 -0
  25. package/lib/actions/requirements/getRequirementsAction.d.ts +2 -2
  26. package/lib/actions/requirements/getRequirementsAction.js +7 -7
  27. package/lib/actions/requirements/index.d.ts +1 -0
  28. package/lib/actions/requirements/index.js +1 -0
  29. package/lib/actions/vaultV1/deposit.d.ts +41 -0
  30. package/lib/actions/vaultV1/deposit.js +116 -0
  31. package/lib/actions/vaultV1/index.d.ts +3 -0
  32. package/lib/actions/vaultV1/index.js +19 -0
  33. package/lib/actions/vaultV1/redeem.d.ts +29 -0
  34. package/lib/actions/vaultV1/redeem.js +48 -0
  35. package/lib/actions/vaultV1/withdraw.d.ts +29 -0
  36. package/lib/actions/vaultV1/withdraw.js +48 -0
  37. package/lib/actions/vaultV2/deposit.d.ts +20 -25
  38. package/lib/actions/vaultV2/deposit.js +78 -40
  39. package/lib/actions/vaultV2/forceRedeem.js +2 -2
  40. package/lib/actions/vaultV2/forceWithdraw.d.ts +2 -2
  41. package/lib/actions/vaultV2/forceWithdraw.js +12 -8
  42. package/lib/actions/vaultV2/redeem.js +2 -2
  43. package/lib/actions/vaultV2/withdraw.d.ts +3 -3
  44. package/lib/actions/vaultV2/withdraw.js +6 -6
  45. package/lib/client/morphoClient.d.ts +4 -1
  46. package/lib/client/morphoClient.js +6 -0
  47. package/lib/client/morphoViemExtension.d.ts +12 -9
  48. package/lib/client/morphoViemExtension.js +12 -9
  49. package/lib/entities/index.d.ts +2 -0
  50. package/lib/entities/index.js +2 -0
  51. package/lib/entities/marketV1/index.d.ts +1 -0
  52. package/lib/entities/marketV1/index.js +17 -0
  53. package/lib/entities/marketV1/marketV1.d.ts +290 -0
  54. package/lib/entities/marketV1/marketV1.js +528 -0
  55. package/lib/entities/vaultV1/index.d.ts +1 -0
  56. package/lib/entities/vaultV1/index.js +17 -0
  57. package/lib/entities/vaultV1/vaultV1.d.ts +95 -0
  58. package/lib/entities/vaultV1/vaultV1.js +129 -0
  59. package/lib/entities/vaultV2/vaultV2.d.ts +24 -21
  60. package/lib/entities/vaultV2/vaultV2.js +43 -16
  61. package/lib/helpers/computeReallocations.d.ts +23 -0
  62. package/lib/helpers/computeReallocations.js +98 -0
  63. package/lib/helpers/constant.d.ts +5 -0
  64. package/lib/helpers/constant.js +6 -1
  65. package/lib/helpers/encodeDeallocation.js +3 -3
  66. package/lib/helpers/index.d.ts +3 -0
  67. package/lib/helpers/index.js +18 -1
  68. package/lib/helpers/slippage.d.ts +46 -0
  69. package/lib/helpers/slippage.js +73 -0
  70. package/lib/helpers/validate.d.ts +150 -0
  71. package/lib/helpers/validate.js +279 -0
  72. package/lib/types/action.d.ts +113 -6
  73. package/lib/types/action.js +12 -1
  74. package/lib/types/client.d.ts +4 -1
  75. package/lib/types/deallocation.d.ts +1 -1
  76. package/lib/types/error.d.ts +127 -4
  77. package/lib/types/error.js +210 -12
  78. package/lib/types/index.d.ts +1 -0
  79. package/lib/types/index.js +1 -0
  80. package/lib/types/sharedLiquidity.d.ts +41 -0
  81. package/lib/types/sharedLiquidity.js +2 -0
  82. package/package.json +1 -1
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Consumer sdk
1
+ # Consumer SDK
2
2
 
3
3
  ![Beta](https://img.shields.io/badge/status-beta-orange)
4
4
 
@@ -6,82 +6,342 @@
6
6
 
7
7
  > **The abstraction layer that simplifies Morpho protocol**
8
8
 
9
- ## How to use it? (two ways to build transactions)
9
+ ## Entities & Actions
10
10
 
11
- ### 1️⃣ **With MorphoClient**
11
+ | Entity | Action | Route | Why |
12
+ | ------------ | ------------------------ | ------------------------- | --------------------------------------------------------------------------------------------------- |
13
+ | **VaultV2** | `deposit` | Bundler (general adapter) | Enforces `maxSharePrice` — inflation attack prevention. Supports native token wrapping. |
14
+ | | `withdraw` | Direct vault call | No attack surface, no bundler overhead needed |
15
+ | | `redeem` | Direct vault call | No attack surface, no bundler overhead needed |
16
+ | | `forceWithdraw` | Vault `multicall` | N `forceDeallocate` + 1 `withdraw` in a single tx |
17
+ | | `forceRedeem` | Vault `multicall` | N `forceDeallocate` + 1 `redeem` in a single tx |
18
+ | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
19
+ | | `withdraw` | Direct vault call | No attack surface |
20
+ | | `redeem` | Direct vault call | No attack surface |
21
+ | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
22
+ | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
23
+ | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
24
+
25
+ ## VaultV2
12
26
 
13
27
  ```typescript
14
28
  import { MorphoClient } from "@morpho-org/consumer-sdk";
15
- import { createWalletClient, http } from "viem";
29
+ import { createPublicClient, http } from "viem";
30
+ import { mainnet } from "viem/chains";
31
+
32
+ const viemClient = createPublicClient({ chain: mainnet, transport: http() });
33
+ const morpho = new MorphoClient(viemClient);
34
+
35
+ const vault = morpho.vaultV2("0xVault...", 1);
36
+ ```
37
+
38
+ ### Deposit
39
+
40
+ ```typescript
41
+ const { buildTx, getRequirements } = await vault.deposit({
42
+ amount: 1000000000000000000n,
43
+ userAddress: "0xUser...",
44
+ });
45
+
46
+ const requirements = await getRequirements();
47
+ const tx = buildTx(requirementSignature);
48
+ ```
49
+
50
+ #### Deposit with native token wrapping
51
+
52
+ For vaults whose underlying asset is wNative, you can deposit native token that will be automatically wrapped:
53
+
54
+ ```typescript
55
+ // Native ETH only — wraps 1 ETH to WETH and deposits
56
+ const { buildTx, getRequirements } = await vault.deposit({
57
+ nativeAmount: 1000000000000000000n,
58
+ userAddress: "0xUser...",
59
+ });
60
+
61
+ // Mixed — 0.5 WETH (ERC-20) + 0.5 native ETH wrapped to WETH
62
+ const { buildTx, getRequirements } = await vault.deposit({
63
+ amount: 500000000000000000n,
64
+ nativeAmount: 500000000000000000n,
65
+ userAddress: "0xUser...",
66
+ });
67
+ ```
68
+
69
+ The bundler atomically transfers native token, wraps it to wNative, and deposits alongside any ERC-20 amount. The transaction's `value` field is set to `nativeAmount`.
70
+
71
+ ### Withdraw
72
+
73
+ ```typescript
74
+ const { buildTx } = vault.withdraw({
75
+ amount: 500000000000000000n,
76
+ userAddress: "0xUser...",
77
+ });
78
+
79
+ const tx = buildTx();
80
+ ```
81
+
82
+ ### Redeem
16
83
 
17
- const client = createWalletClient({
18
- chain: mainnet,
19
- transport: http(),
20
- account: "0x...",
84
+ ```typescript
85
+ const { buildTx } = vault.redeem({
86
+ shares: 1000000000000000000n,
87
+ userAddress: "0xUser...",
21
88
  });
22
89
 
23
- const morpho = new MorphoClient(client);
90
+ const tx = buildTx();
91
+ ```
92
+
93
+ ### Force Withdraw
24
94
 
25
- const vault = morpho.vaultV2("0x1234...", 1); // vault address, chain ID
26
- const deposit = await vault.deposit({
27
- assets: 1000000000000000000n, // vault asset amount
28
- userAddress: "0x1234...", // recipient address
95
+ ```typescript
96
+ const { buildTx } = vault.forceWithdraw({
97
+ deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
98
+ withdraw: { amount: 500000000000000000n },
99
+ userAddress: "0xUser...",
29
100
  });
30
- console.log(deposit.buildTx());
31
- console.log(await deposit.getRequirements());
32
101
 
33
- const withdraw = vault.withdraw({
34
- assets: 1000000000000000000n, // vault asset amount
35
- userAddress: "0x1234...", // recipient address
102
+ const tx = buildTx();
103
+ ```
104
+
105
+ ### Force Redeem
106
+
107
+ ```typescript
108
+ const { buildTx } = vault.forceRedeem({
109
+ deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
110
+ redeem: { shares: 1000000000000000000n },
111
+ userAddress: "0xUser...",
112
+ });
113
+
114
+ const tx = buildTx();
115
+ ```
116
+
117
+ ## VaultV1
118
+
119
+ ```typescript
120
+ const vault = morpho.vaultV1("0xVault...", 1);
121
+ ```
122
+
123
+ ### Deposit
124
+
125
+ ```typescript
126
+ const { buildTx, getRequirements } = await vault.deposit({
127
+ amount: 1000000000000000000n,
128
+ userAddress: "0xUser...",
36
129
  });
37
- console.log(withdraw.buildTx());
38
130
 
39
- const redeem = vault.redeem({
40
- shares: 1000000000000000000n, // vault shares amount
41
- userAddress: "0x1234...", // recipient address
131
+ const requirements = await getRequirements();
132
+ const tx = buildTx(requirementSignature);
133
+ ```
134
+
135
+ ### Withdraw
136
+
137
+ ```typescript
138
+ const { buildTx } = vault.withdraw({
139
+ amount: 500000000000000000n,
140
+ userAddress: "0xUser...",
42
141
  });
43
- console.log(redeem.buildTx());
142
+
143
+ const tx = buildTx();
44
144
  ```
45
145
 
46
- ### 2️⃣ **Direct construction** (Full control)
146
+ ### Redeem
47
147
 
48
148
  ```typescript
49
- import { vaultV2Deposit } from "@morpho-org/consumer-sdk";
149
+ const { buildTx } = vault.redeem({
150
+ shares: 1000000000000000000n,
151
+ userAddress: "0xUser...",
152
+ });
153
+
154
+ const tx = buildTx();
155
+ ```
50
156
 
51
- const deposit = vaultV2Deposit({
52
- vault: {
53
- chainId: mainnet.id,
54
- address: "0x1234...", // vault address
55
- asset: "0x1234...", // asset address
157
+ ## MarketV1
158
+
159
+ ```typescript
160
+ const market = morpho.marketV1(
161
+ {
162
+ loanToken: "0xLoan...",
163
+ collateralToken: "0xCollateral...",
164
+ oracle: "0xOracle...",
165
+ irm: "0xIrm...",
166
+ lltv: 860000000000000000n,
56
167
  },
57
- args: {
58
- assets: 1000000000000000000n, // vault asset amount
59
- maxSharePrice: 995180497664595699494513674403n,
60
- recipient: "0x1234...", // recipient address
168
+ 1
169
+ );
170
+ ```
171
+
172
+ ### Supply Collateral
173
+
174
+ ```typescript
175
+ const { buildTx, getRequirements } = market.supplyCollateral({
176
+ amount: 1000000000000000000n,
177
+ userAddress: "0xUser...",
178
+ });
179
+
180
+ const requirements = await getRequirements();
181
+ const tx = buildTx(requirementSignature);
182
+ ```
183
+
184
+ ### Borrow
185
+
186
+ ```typescript
187
+ const positionData = await market.getPositionData("0xUser...");
188
+
189
+ const { buildTx, getRequirements } = market.borrow({
190
+ amount: 500000000000000000n,
191
+ userAddress: "0xUser...",
192
+ positionData,
193
+ });
194
+
195
+ const requirements = await getRequirements();
196
+ const tx = buildTx();
197
+ ```
198
+
199
+ ### Supply Collateral & Borrow
200
+
201
+ ```typescript
202
+ const positionData = await market.getPositionData("0xUser...");
203
+
204
+ const { buildTx, getRequirements } = market.supplyCollateralBorrow({
205
+ amount: 1000000000000000000n,
206
+ borrowAmount: 500000000000000000n,
207
+ userAddress: "0xUser...",
208
+ positionData,
209
+ });
210
+
211
+ const requirements = await getRequirements();
212
+ const tx = buildTx(requirementSignature);
213
+ ```
214
+
215
+ ### Borrow with Shared Liquidity (Reallocations)
216
+
217
+ When a market lacks sufficient liquidity, you can reallocate liquidity from other markets managed by MetaMorpho Vaults via the **PublicAllocator** contract:
218
+
219
+ ```typescript
220
+ import type { VaultReallocation } from "@morpho-org/consumer-sdk";
221
+
222
+ const reallocations: VaultReallocation[] = [
223
+ {
224
+ vault: "0xVault...", // MetaMorpho vault to reallocate from
225
+ fee: 0n, // PublicAllocator fee in native token (can be 0)
226
+ withdrawals: [
227
+ {
228
+ marketParams: sourceMarketParams, // Source market to withdraw from
229
+ amount: 2000000000n, // Amount to withdraw
230
+ },
231
+ ],
61
232
  },
233
+ ];
234
+
235
+ const positionData = await market.getPositionData("0xUser...");
236
+
237
+ // Borrow with reallocations
238
+ const { buildTx, getRequirements } = market.borrow({
239
+ amount: 500000000000000000n,
240
+ userAddress: "0xUser...",
241
+ positionData,
242
+ reallocations,
62
243
  });
244
+
245
+ const requirements = await getRequirements();
246
+ const tx = buildTx();
247
+ // tx.value includes the sum of all reallocation fees
63
248
  ```
64
249
 
65
- ## Link Integration - Local Development Guide
250
+ Reallocations also work with `supplyCollateralBorrow`:
251
+
252
+ ```typescript
253
+ const { buildTx, getRequirements } = market.supplyCollateralBorrow({
254
+ amount: 1000000000000000000n,
255
+ borrowAmount: 500000000000000000n,
256
+ userAddress: "0xUser...",
257
+ positionData,
258
+ reallocations,
259
+ });
260
+ ```
261
+
262
+ ## Architecture
263
+
264
+ ```mermaid
265
+ graph LR
266
+ MC[MorphoClient]
267
+
268
+ MC -->|.vaultV1| MV1
269
+ MC -->|.vaultV2| MV2
270
+ MC -->|.marketV1| MM1
271
+
272
+ subgraph VaultV1 Flow
273
+ MV1[MorphoVaultV1]
274
+ MV1 --> V1D[vaultV1Deposit]
275
+ MV1 --> V1W[vaultV1Withdraw]
276
+ MV1 --> V1R[vaultV1Redeem]
66
277
 
67
- This guide explains how to link this local package to your Next.js application for easier debugging.
278
+ V1D -->|nativeTransfer + wrapNative + erc4626Deposit| B1[Bundler3]
279
+ V1W -->|direct call| MM[MetaMorpho]
280
+ V1R -->|direct call| MM
281
+ end
68
282
 
69
- ### **Step 1: Initial setup (one time only)**
283
+ subgraph VaultV2 Flow
284
+ MV2[MorphoVaultV2]
285
+ MV2 --> V2D[vaultV2Deposit]
286
+ MV2 --> V2W[vaultV2Withdraw]
287
+ MV2 --> V2R[vaultV2Redeem]
288
+ MV2 --> V2FW[vaultV2ForceWithdraw]
289
+ MV2 --> V2FR[vaultV2ForceRedeem]
290
+
291
+ V2D -->|nativeTransfer + wrapNative + erc4626Deposit| B2[Bundler3]
292
+ V2W -->|direct call| V2C[VaultV2 Contract]
293
+ V2R -->|direct call| V2C
294
+ V2FW -->|multicall| V2C
295
+ V2FR -->|multicall| V2C
296
+ end
297
+
298
+ subgraph MarketV1 Flow
299
+ MM1[MorphoMarketV1]
300
+ MM1 --> M1SC[marketV1SupplyCollateral]
301
+ MM1 --> M1B[marketV1Borrow]
302
+ MM1 --> M1SCB[marketV1SupplyCollateralBorrow]
303
+
304
+ M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3[Bundler3]
305
+ M1B -->|reallocateTo? + morphoBorrow| B3
306
+ M1SCB -->|transfer + supplyCollateral + reallocateTo? + borrow| B3
307
+
308
+ B3 -.->|reallocateTo| PA[PublicAllocator]
309
+ end
310
+
311
+
312
+ subgraph Shared
313
+ REQ[getRequirements]
314
+ end
315
+
316
+ MV1 -.->|approval / permit| REQ
317
+ MV2 -.->|approval / permit| REQ
318
+ MM1 -.->|approval / permit / authorization| REQ
319
+
320
+ style B1 fill:#e8f5e9,stroke:#4caf50
321
+ style B2 fill:#e8f5e9,stroke:#4caf50
322
+ style B3 fill:#e8f5e9,stroke:#4caf50
323
+ style MM fill:#fff3e0,stroke:#ff9800
324
+ style V2C fill:#e3f2fd,stroke:#2196f3
325
+ style REQ fill:#f3e5f5,stroke:#9c27b0
326
+ style PA fill:#fff9c4,stroke:#f9a825
327
+ ```
328
+
329
+ ## Local Development
330
+
331
+ Link this package to your app for local debugging:
70
332
 
71
333
  ```bash
72
334
  # In this consumer-sdk project
73
335
  pnpm run build:link
74
336
  ```
75
337
 
76
- ### **Step 2: In your other project**
338
+ In your other project:
77
339
 
78
340
  ```bash
79
341
  # Link the local package
80
342
  pnpm link consumer-sdk
81
343
  ```
82
344
 
83
- ## 🤝 Contributing
345
+ ## Contributing
84
346
 
85
347
  Contributions are welcome! Feel free to open an issue or PR.
86
-
87
- **Made with ❤️ by the Morpho team**
@@ -1,2 +1,4 @@
1
+ export * from "./marketV1";
1
2
  export * from "./requirements";
3
+ export * from "./vaultV1";
2
4
  export * from "./vaultV2";
@@ -14,5 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./marketV1"), exports);
17
18
  __exportStar(require("./requirements"), exports);
19
+ __exportStar(require("./vaultV1"), exports);
18
20
  __exportStar(require("./vaultV2"), exports);
@@ -0,0 +1,34 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import type { Address } from "viem";
3
+ import { type MarketV1BorrowAction, type Metadata, type Transaction, type VaultReallocation } from "../../types";
4
+ /** Parameters for {@link marketV1Borrow}. */
5
+ export interface MarketV1BorrowParams {
6
+ market: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ args: {
11
+ amount: bigint;
12
+ receiver: Address;
13
+ /** Minimum borrow share price (in ray). Protects against share price manipulation. */
14
+ minSharePrice: bigint;
15
+ /** Vault reallocations to execute before borrowing (computed by entity). */
16
+ reallocations?: readonly VaultReallocation[];
17
+ };
18
+ metadata?: Metadata;
19
+ }
20
+ /**
21
+ * Prepares a borrow transaction for a Morpho Blue market.
22
+ *
23
+ * Routed through bundler3 via `morphoBorrow`. The bundler uses the transaction
24
+ * initiator as `onBehalf`. Uses `minSharePrice` to protect against share price
25
+ * manipulation between transaction construction and execution.
26
+ *
27
+ * When `reallocations` are provided, `reallocateTo` actions are prepended to
28
+ * the bundle, moving liquidity from other markets via the PublicAllocator
29
+ * before borrowing. The reallocation fees are set as the transaction value.
30
+ *
31
+ * @param params - Borrow parameters.
32
+ * @returns Deep-frozen transaction.
33
+ */
34
+ export declare const marketV1Borrow: ({ market: { chainId, marketParams }, args: { amount, receiver, minSharePrice, reallocations }, metadata, }: MarketV1BorrowParams) => Readonly<Transaction<MarketV1BorrowAction>>;
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.marketV1Borrow = void 0;
4
+ const bundler_sdk_viem_1 = require("@morpho-org/bundler-sdk-viem");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const helpers_1 = require("../../helpers");
7
+ const types_1 = require("../../types");
8
+ const buildReallocationActions_1 = require("./buildReallocationActions");
9
+ /**
10
+ * Prepares a borrow transaction for a Morpho Blue market.
11
+ *
12
+ * Routed through bundler3 via `morphoBorrow`. The bundler uses the transaction
13
+ * initiator as `onBehalf`. Uses `minSharePrice` to protect against share price
14
+ * manipulation between transaction construction and execution.
15
+ *
16
+ * When `reallocations` are provided, `reallocateTo` actions are prepended to
17
+ * the bundle, moving liquidity from other markets via the PublicAllocator
18
+ * before borrowing. The reallocation fees are set as the transaction value.
19
+ *
20
+ * @param params - Borrow parameters.
21
+ * @returns Deep-frozen transaction.
22
+ */
23
+ const marketV1Borrow = ({ market: { chainId, marketParams }, args: { amount, receiver, minSharePrice, reallocations }, metadata, }) => {
24
+ if (amount <= 0n) {
25
+ throw new types_1.NonPositiveBorrowAmountError(marketParams.id);
26
+ }
27
+ if (minSharePrice < 0n) {
28
+ throw new types_1.NonPositiveMinBorrowSharePriceError(marketParams.id);
29
+ }
30
+ const actions = [];
31
+ let reallocationFee = 0n;
32
+ if (reallocations && reallocations.length > 0) {
33
+ const result = (0, buildReallocationActions_1.buildReallocationActions)(reallocations, marketParams);
34
+ actions.push(...result.actions);
35
+ reallocationFee = result.fee;
36
+ }
37
+ actions.push({
38
+ type: "morphoBorrow",
39
+ args: [marketParams, amount, 0n, minSharePrice, receiver, false],
40
+ });
41
+ let tx = {
42
+ ...bundler_sdk_viem_1.BundlerAction.encodeBundle(chainId, actions),
43
+ value: reallocationFee,
44
+ };
45
+ if (metadata) {
46
+ tx = (0, helpers_1.addTransactionMetadata)(tx, metadata);
47
+ }
48
+ return (0, morpho_ts_1.deepFreeze)({
49
+ ...tx,
50
+ action: {
51
+ type: "marketV1Borrow",
52
+ args: {
53
+ market: marketParams.id,
54
+ amount,
55
+ receiver,
56
+ minSharePrice,
57
+ reallocationFee,
58
+ },
59
+ },
60
+ });
61
+ };
62
+ exports.marketV1Borrow = marketV1Borrow;
@@ -0,0 +1,17 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import type { Action } from "@morpho-org/bundler-sdk-viem";
3
+ import type { VaultReallocation } from "../../types";
4
+ /**
5
+ * Builds reallocation bundler actions and computes the total fee.
6
+ *
7
+ * Validates the reallocations, then encodes each as a `reallocateTo` action.
8
+ * Caller must ensure `reallocations` is non-empty before calling.
9
+ *
10
+ * @param reallocations - The vault reallocations to encode.
11
+ * @param targetMarketParams - The target market params for the borrow.
12
+ * @returns The encoded actions and total reallocation fee.
13
+ */
14
+ export declare const buildReallocationActions: (reallocations: readonly VaultReallocation[], targetMarketParams: MarketParams) => {
15
+ readonly actions: Action[];
16
+ readonly fee: bigint;
17
+ };
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildReallocationActions = void 0;
4
+ const helpers_1 = require("../../helpers");
5
+ /**
6
+ * Builds reallocation bundler actions and computes the total fee.
7
+ *
8
+ * Validates the reallocations, then encodes each as a `reallocateTo` action.
9
+ * Caller must ensure `reallocations` is non-empty before calling.
10
+ *
11
+ * @param reallocations - The vault reallocations to encode.
12
+ * @param targetMarketParams - The target market params for the borrow.
13
+ * @returns The encoded actions and total reallocation fee.
14
+ */
15
+ const buildReallocationActions = (reallocations, targetMarketParams) => {
16
+ (0, helpers_1.validateReallocations)(reallocations, targetMarketParams.id);
17
+ const fee = reallocations.reduce((sum, r) => sum + r.fee, 0n);
18
+ const actions = [];
19
+ for (const r of reallocations) {
20
+ actions.push({
21
+ type: "reallocateTo",
22
+ args: [
23
+ r.vault,
24
+ r.fee,
25
+ r.withdrawals.map((w) => ({
26
+ marketParams: w.marketParams,
27
+ amount: w.amount,
28
+ })),
29
+ targetMarketParams,
30
+ false,
31
+ ],
32
+ });
33
+ }
34
+ return { actions, fee };
35
+ };
36
+ exports.buildReallocationActions = buildReallocationActions;
@@ -0,0 +1,6 @@
1
+ export * from "./borrow";
2
+ export * from "./repay";
3
+ export * from "./repayWithdrawCollateral";
4
+ export * from "./supplyCollateral";
5
+ export * from "./supplyCollateralBorrow";
6
+ export * from "./withdrawCollateral";
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./borrow"), exports);
18
+ __exportStar(require("./repay"), exports);
19
+ __exportStar(require("./repayWithdrawCollateral"), exports);
20
+ __exportStar(require("./supplyCollateral"), exports);
21
+ __exportStar(require("./supplyCollateralBorrow"), exports);
22
+ __exportStar(require("./withdrawCollateral"), exports);
@@ -0,0 +1,44 @@
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
+ import type { MarketV1RepayAction, Metadata, RequirementSignature, Transaction } from "../../types";
4
+ /** Parameters for {@link marketV1Repay}. */
5
+ export interface MarketV1RepayParams {
6
+ market: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ args: {
11
+ /** Repay assets amount (0n when repaying by shares). */
12
+ assets: bigint;
13
+ /** Repay shares amount (0n when repaying by assets). */
14
+ shares: bigint;
15
+ /** ERC20 amount to transfer to GeneralAdapter1. Must be greater than or equal to the repay amount to take into account the slippage. */
16
+ transferAmount: bigint;
17
+ /** Address whose debt is being repaid. */
18
+ onBehalf: Address;
19
+ /** Receives residual loan tokens in shares mode. */
20
+ receiver: Address;
21
+ /** Maximum repay share price (in ray). Protects against share price manipulation. */
22
+ maxSharePrice: bigint;
23
+ requirementSignature?: RequirementSignature;
24
+ };
25
+ metadata?: Metadata;
26
+ }
27
+ /**
28
+ * Prepares a repay transaction for a Morpho Blue market.
29
+ *
30
+ * Routed through bundler3 via GeneralAdapter1. Supports two modes:
31
+ * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
32
+ * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay).
33
+ *
34
+ * Exactly one of `assets`/`shares` must be non-zero. The `transferAmount` controls
35
+ * how many ERC20 tokens are pulled from the user (may differ from `assets` in
36
+ * shares mode where the entity computes an upper-bound estimate).
37
+ *
38
+ * Uses `maxSharePrice` to protect against share price manipulation between
39
+ * transaction construction and execution.
40
+ *
41
+ * @param params - Repay parameters.
42
+ * @returns Deep-frozen transaction.
43
+ */
44
+ export declare const marketV1Repay: ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }: MarketV1RepayParams) => Readonly<Transaction<MarketV1RepayAction>>;