@morpho-org/morpho-sdk 1.0.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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +496 -0
  3. package/lib/actions/index.d.ts +4 -0
  4. package/lib/actions/index.js +20 -0
  5. package/lib/actions/marketV1/borrow.d.ts +34 -0
  6. package/lib/actions/marketV1/borrow.js +62 -0
  7. package/lib/actions/marketV1/buildReallocationActions.d.ts +17 -0
  8. package/lib/actions/marketV1/buildReallocationActions.js +36 -0
  9. package/lib/actions/marketV1/index.d.ts +6 -0
  10. package/lib/actions/marketV1/index.js +22 -0
  11. package/lib/actions/marketV1/repay.d.ts +44 -0
  12. package/lib/actions/marketV1/repay.js +93 -0
  13. package/lib/actions/marketV1/repayWithdrawCollateral.d.ts +51 -0
  14. package/lib/actions/marketV1/repayWithdrawCollateral.js +108 -0
  15. package/lib/actions/marketV1/supplyCollateral.d.ts +28 -0
  16. package/lib/actions/marketV1/supplyCollateral.js +85 -0
  17. package/lib/actions/marketV1/supplyCollateralBorrow.d.ts +37 -0
  18. package/lib/actions/marketV1/supplyCollateralBorrow.js +109 -0
  19. package/lib/actions/marketV1/withdrawCollateral.d.ts +28 -0
  20. package/lib/actions/marketV1/withdrawCollateral.js +51 -0
  21. package/lib/actions/requirements/encode/encodeErc20Approval.d.ts +10 -0
  22. package/lib/actions/requirements/encode/encodeErc20Approval.js +25 -0
  23. package/lib/actions/requirements/encode/encodeErc20Permit.d.ts +13 -0
  24. package/lib/actions/requirements/encode/encodeErc20Permit.js +70 -0
  25. package/lib/actions/requirements/encode/encodeErc20Permit2.d.ts +11 -0
  26. package/lib/actions/requirements/encode/encodeErc20Permit2.js +70 -0
  27. package/lib/actions/requirements/encode/index.d.ts +3 -0
  28. package/lib/actions/requirements/encode/index.js +19 -0
  29. package/lib/actions/requirements/getMorphoAuthorizationRequirement.d.ts +21 -0
  30. package/lib/actions/requirements/getMorphoAuthorizationRequirement.js +55 -0
  31. package/lib/actions/requirements/getRequirements.d.ts +42 -0
  32. package/lib/actions/requirements/getRequirements.js +80 -0
  33. package/lib/actions/requirements/getRequirementsAction.d.ts +17 -0
  34. package/lib/actions/requirements/getRequirementsAction.js +64 -0
  35. package/lib/actions/requirements/getRequirementsApproval.d.ts +31 -0
  36. package/lib/actions/requirements/getRequirementsApproval.js +51 -0
  37. package/lib/actions/requirements/getRequirementsPermit.d.ts +28 -0
  38. package/lib/actions/requirements/getRequirementsPermit.js +40 -0
  39. package/lib/actions/requirements/getRequirementsPermit2.d.ts +37 -0
  40. package/lib/actions/requirements/getRequirementsPermit2.js +59 -0
  41. package/lib/actions/requirements/index.d.ts +6 -0
  42. package/lib/actions/requirements/index.js +22 -0
  43. package/lib/actions/vaultV1/deposit.d.ts +41 -0
  44. package/lib/actions/vaultV1/deposit.js +116 -0
  45. package/lib/actions/vaultV1/index.d.ts +4 -0
  46. package/lib/actions/vaultV1/index.js +20 -0
  47. package/lib/actions/vaultV1/migrateToV2.d.ts +50 -0
  48. package/lib/actions/vaultV1/migrateToV2.js +108 -0
  49. package/lib/actions/vaultV1/redeem.d.ts +29 -0
  50. package/lib/actions/vaultV1/redeem.js +48 -0
  51. package/lib/actions/vaultV1/withdraw.d.ts +29 -0
  52. package/lib/actions/vaultV1/withdraw.js +48 -0
  53. package/lib/actions/vaultV2/deposit.d.ts +41 -0
  54. package/lib/actions/vaultV2/deposit.js +116 -0
  55. package/lib/actions/vaultV2/forceRedeem.d.ts +48 -0
  56. package/lib/actions/vaultV2/forceRedeem.js +85 -0
  57. package/lib/actions/vaultV2/forceWithdraw.d.ts +40 -0
  58. package/lib/actions/vaultV2/forceWithdraw.js +85 -0
  59. package/lib/actions/vaultV2/index.d.ts +5 -0
  60. package/lib/actions/vaultV2/index.js +21 -0
  61. package/lib/actions/vaultV2/redeem.d.ts +32 -0
  62. package/lib/actions/vaultV2/redeem.js +51 -0
  63. package/lib/actions/vaultV2/withdraw.d.ts +32 -0
  64. package/lib/actions/vaultV2/withdraw.js +51 -0
  65. package/lib/client/index.d.ts +2 -0
  66. package/lib/client/index.js +18 -0
  67. package/lib/client/morphoClient.d.ts +25 -0
  68. package/lib/client/morphoClient.js +28 -0
  69. package/lib/client/morphoViemExtension.d.ts +39 -0
  70. package/lib/client/morphoViemExtension.js +40 -0
  71. package/lib/entities/index.d.ts +3 -0
  72. package/lib/entities/index.js +19 -0
  73. package/lib/entities/marketV1/index.d.ts +1 -0
  74. package/lib/entities/marketV1/index.js +17 -0
  75. package/lib/entities/marketV1/marketV1.d.ts +290 -0
  76. package/lib/entities/marketV1/marketV1.js +531 -0
  77. package/lib/entities/vaultV1/index.d.ts +1 -0
  78. package/lib/entities/vaultV1/index.js +17 -0
  79. package/lib/entities/vaultV1/vaultV1.d.ts +133 -0
  80. package/lib/entities/vaultV1/vaultV1.js +186 -0
  81. package/lib/entities/vaultV2/index.d.ts +1 -0
  82. package/lib/entities/vaultV2/index.js +17 -0
  83. package/lib/entities/vaultV2/vaultV2.d.ts +180 -0
  84. package/lib/entities/vaultV2/vaultV2.js +167 -0
  85. package/lib/helpers/computeReallocations.d.ts +23 -0
  86. package/lib/helpers/computeReallocations.js +98 -0
  87. package/lib/helpers/constant.d.ts +6 -0
  88. package/lib/helpers/constant.js +10 -0
  89. package/lib/helpers/encodeDeallocation.d.ts +10 -0
  90. package/lib/helpers/encodeDeallocation.js +37 -0
  91. package/lib/helpers/index.d.ts +4 -0
  92. package/lib/helpers/index.js +22 -0
  93. package/lib/helpers/metadata.d.ts +33 -0
  94. package/lib/helpers/metadata.js +49 -0
  95. package/lib/helpers/slippage.d.ts +46 -0
  96. package/lib/helpers/slippage.js +73 -0
  97. package/lib/helpers/validate.d.ts +156 -0
  98. package/lib/helpers/validate.js +287 -0
  99. package/lib/index.d.ts +5 -0
  100. package/lib/index.js +21 -0
  101. package/lib/types/action.d.ts +216 -0
  102. package/lib/types/action.js +26 -0
  103. package/lib/types/client.d.ts +15 -0
  104. package/lib/types/client.js +2 -0
  105. package/lib/types/data.d.ts +2 -0
  106. package/lib/types/data.js +2 -0
  107. package/lib/types/deallocation.d.ts +15 -0
  108. package/lib/types/deallocation.js +2 -0
  109. package/lib/types/entity.d.ts +5 -0
  110. package/lib/types/entity.js +2 -0
  111. package/lib/types/error.d.ts +166 -0
  112. package/lib/types/error.js +285 -0
  113. package/lib/types/index.d.ts +7 -0
  114. package/lib/types/index.js +23 -0
  115. package/lib/types/metadata.d.ts +4 -0
  116. package/lib/types/metadata.js +2 -0
  117. package/lib/types/sharedLiquidity.d.ts +41 -0
  118. package/lib/types/sharedLiquidity.js +2 -0
  119. package/package.json +81 -0
  120. package/src/index.ts +5 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Morpho Association
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,496 @@
1
+ # @morpho-org/morpho-sdk
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@morpho-org/morpho-sdk.svg)](https://www.npmjs.com/package/@morpho-org/morpho-sdk)
4
+ [![TypeScript](https://img.shields.io/badge/TypeScript-strict-blue.svg)](https://www.typescriptlang.org/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE)
6
+ [![CI](https://github.com/morpho-org/morpho-sdk/actions/workflows/ci.yml/badge.svg)](https://github.com/morpho-org/morpho-sdk/actions/workflows/ci.yml)
7
+
8
+ > **The abstraction layer that simplifies Morpho protocol**
9
+
10
+ Build transactions for **VaultV1** (MetaMorpho), **VaultV2**, and **MarketV1** (Morpho Blue) on EVM-compatible chains.
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add @morpho-org/morpho-sdk
16
+ ```
17
+
18
+ ## Entities & Actions
19
+
20
+ | Entity | Action | Route | Why |
21
+ | ------------ | ------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------- |
22
+ | **VaultV2** | `deposit` | Bundler (general adapter) | Enforces `maxSharePrice` — inflation attack prevention. Supports native token wrapping. |
23
+ | | `withdraw` | Direct vault call | No attack surface, no bundler overhead needed |
24
+ | | `redeem` | Direct vault call | No attack surface, no bundler overhead needed |
25
+ | | `forceWithdraw` | Vault `multicall` | N `forceDeallocate` + 1 `withdraw` in a single tx |
26
+ | | `forceRedeem` | Vault `multicall` | N `forceDeallocate` + 1 `redeem` in a single tx |
27
+ | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
28
+ | | `withdraw` | Direct vault call | No attack surface |
29
+ | | `redeem` | Direct vault call | No attack surface |
30
+ | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
31
+ | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
32
+ | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
33
+ | | `repay` | Bundler (general adapter) | `erc20TransferFrom` + `morphoRepay` with `maxSharePrice` protection. Supports partial or full. |
34
+ | | `withdrawCollateral` | Direct Morpho call | No bundler overhead. Validates position health after withdrawal. |
35
+ | | `repayWithdrawCollateral` | Bundler (general adapter) | Atomic repay + withdraw. Bundle order matters: repay first, then withdraw. |
36
+
37
+ ## The `getRequirements` flow
38
+
39
+ Every action that touches a user's tokens or positions returns two things:
40
+
41
+ - `buildTx(signature?)` — builds the final viem `Transaction` object.
42
+ - `getRequirements()` — returns the list of on-chain pre-requisites that must be satisfied first.
43
+
44
+ Typical requirements:
45
+
46
+ - **ERC-20 approval** — the user must approve the bundler (or Morpho directly) to pull tokens. Returned as a standard `approve` transaction the consumer sends first.
47
+ - **Permit / Permit2 signature** — off-chain approvals that go into `buildTx` as a `signature` argument, avoiding the extra approval tx. Enabled via `MorphoClient({ supportSignature: true })`.
48
+ - **Morpho authorization** — `borrow`, `supplyCollateralBorrow`, and `repayWithdrawCollateral` require the user to authorize `GeneralAdapter1` on the Morpho contract once (`setAuthorization`). The SDK returns this as an extra transaction if it's missing.
49
+
50
+ Usage pattern:
51
+
52
+ ```typescript
53
+ const { buildTx, getRequirements } = await vault.deposit({
54
+ /* ... */
55
+ });
56
+
57
+ const requirements = await getRequirements();
58
+ // → [{ type: "approval", tx: {...} }, { type: "permit", sign: async () => {...} }]
59
+
60
+ // Consumer satisfies each requirement (send tx / sign permit), collects the signature,
61
+ // then calls buildTx to get the final transaction:
62
+ const tx = buildTx(permitSignature);
63
+ ```
64
+
65
+ ## Integration invariant — builder = signer
66
+
67
+ **`userAddress` MUST equal the connected account on the viem client used to build the tx, and that same client MUST sign it.** Enforced by `validateUserAddress` (throws `MissingClientPropertyError` / `AddressMismatchError`); critical for `repayWithdrawCollateral`, whose bundle mixes explicit `onBehalf` (repay) with implicit `msg.sender` (transfer-from + withdraw) — see [BUNDLER3.md](./BUNDLER3.md#other-pitfalls).
68
+
69
+ | Entity | Action | Route | Why |
70
+ | ------------ | ------------------------ | ------------------------- | --------------------------------------------------------------------------------------------------- |
71
+ | **VaultV2** | `deposit` | Bundler (general adapter) | Enforces `maxSharePrice` — inflation attack prevention. Supports native token wrapping. |
72
+ | | `withdraw` | Direct vault call | No attack surface, no bundler overhead needed |
73
+ | | `redeem` | Direct vault call | No attack surface, no bundler overhead needed |
74
+ | | `forceWithdraw` | Vault `multicall` | N `forceDeallocate` + 1 `withdraw` in a single tx |
75
+ | | `forceRedeem` | Vault `multicall` | N `forceDeallocate` + 1 `redeem` in a single tx |
76
+ | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
77
+ | | `withdraw` | Direct vault call | No attack surface |
78
+ | | `redeem` | Direct vault call | No attack surface |
79
+ | | `migrateToV2` | Bundler (general adapter) | Atomic V1 → V2 migration: redeem V1 shares + deposit into V2 in one tx. Slippage-protected. |
80
+ | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
81
+ | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
82
+ | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
83
+
84
+ ## VaultV2
85
+
86
+ ```typescript
87
+ import { MorphoClient } from "@morpho-org/morpho-sdk";
88
+ import { createPublicClient, http } from "viem";
89
+ import { mainnet } from "viem/chains";
90
+
91
+ const viemClient = createPublicClient({ chain: mainnet, transport: http() });
92
+ const morpho = new MorphoClient(viemClient);
93
+
94
+ const vault = morpho.vaultV2("0xVault...", 1);
95
+ ```
96
+
97
+ ### Deposit
98
+
99
+ ```typescript
100
+ const { buildTx, getRequirements } = await vault.deposit({
101
+ amount: 1000000000000000000n,
102
+ userAddress: "0xUser...",
103
+ });
104
+
105
+ const requirements = await getRequirements();
106
+ const tx = buildTx(requirementSignature);
107
+ ```
108
+
109
+ #### Deposit with native token wrapping
110
+
111
+ For vaults whose underlying asset is wNative, you can deposit native token that will be automatically wrapped:
112
+
113
+ ```typescript
114
+ // Native ETH only — wraps 1 ETH to WETH and deposits
115
+ const { buildTx, getRequirements } = await vault.deposit({
116
+ nativeAmount: 1000000000000000000n,
117
+ userAddress: "0xUser...",
118
+ });
119
+
120
+ // Mixed — 0.5 WETH (ERC-20) + 0.5 native ETH wrapped to WETH
121
+ const { buildTx, getRequirements } = await vault.deposit({
122
+ amount: 500000000000000000n,
123
+ nativeAmount: 500000000000000000n,
124
+ userAddress: "0xUser...",
125
+ });
126
+ ```
127
+
128
+ 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`.
129
+
130
+ ### Withdraw
131
+
132
+ ```typescript
133
+ const { buildTx } = vault.withdraw({
134
+ amount: 500000000000000000n,
135
+ userAddress: "0xUser...",
136
+ });
137
+
138
+ const tx = buildTx();
139
+ ```
140
+
141
+ ### Redeem
142
+
143
+ ```typescript
144
+ const { buildTx } = vault.redeem({
145
+ shares: 1000000000000000000n,
146
+ userAddress: "0xUser...",
147
+ });
148
+
149
+ const tx = buildTx();
150
+ ```
151
+
152
+ ### Force Withdraw
153
+
154
+ ```typescript
155
+ const { buildTx } = vault.forceWithdraw({
156
+ deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
157
+ withdraw: { amount: 500000000000000000n },
158
+ userAddress: "0xUser...",
159
+ });
160
+
161
+ const tx = buildTx();
162
+ ```
163
+
164
+ ### Force Redeem
165
+
166
+ ```typescript
167
+ const { buildTx } = vault.forceRedeem({
168
+ deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
169
+ redeem: { shares: 1000000000000000000n },
170
+ userAddress: "0xUser...",
171
+ });
172
+
173
+ const tx = buildTx();
174
+ ```
175
+
176
+ ## VaultV1
177
+
178
+ ```typescript
179
+ const vault = morpho.vaultV1("0xVault...", 1);
180
+ ```
181
+
182
+ ### Deposit
183
+
184
+ ```typescript
185
+ const { buildTx, getRequirements } = await vault.deposit({
186
+ amount: 1000000000000000000n,
187
+ userAddress: "0xUser...",
188
+ });
189
+
190
+ const requirements = await getRequirements();
191
+ const tx = buildTx(requirementSignature);
192
+ ```
193
+
194
+ ### Withdraw
195
+
196
+ ```typescript
197
+ const { buildTx } = vault.withdraw({
198
+ amount: 500000000000000000n,
199
+ userAddress: "0xUser...",
200
+ });
201
+
202
+ const tx = buildTx();
203
+ ```
204
+
205
+ ### Redeem
206
+
207
+ ```typescript
208
+ const { buildTx } = vault.redeem({
209
+ shares: 1000000000000000000n,
210
+ userAddress: "0xUser...",
211
+ });
212
+
213
+ const tx = buildTx();
214
+ ```
215
+
216
+ ### Migrate to V2
217
+
218
+ Atomically migrate a full position from a VaultV1 (MetaMorpho) vault into a VaultV2 vault. The bundler redeems the V1 shares and deposits the resulting assets into V2 in a single transaction. Both vaults must share the same underlying asset.
219
+
220
+ ```typescript
221
+ const sourceVault = morpho.vaultV1("0xV1Vault...", 1);
222
+ const targetVault = morpho.vaultV2("0xV2Vault...", 1);
223
+
224
+ const { buildTx, getRequirements } = sourceVault.migrateToV2({
225
+ userAddress: "0xUser...",
226
+ sourceVault: await sourceVault.getData(),
227
+ targetVault: await targetVault.getData(),
228
+ shares: 1000000000000000000n,
229
+ });
230
+
231
+ const requirements = await getRequirements();
232
+ const tx = buildTx(requirementSignature);
233
+ ```
234
+
235
+ ## MarketV1
236
+
237
+ ```typescript
238
+ const market = morpho.marketV1(
239
+ {
240
+ loanToken: "0xLoan...",
241
+ collateralToken: "0xCollateral...",
242
+ oracle: "0xOracle...",
243
+ irm: "0xIrm...",
244
+ lltv: 860000000000000000n,
245
+ },
246
+ 1
247
+ );
248
+ ```
249
+
250
+ ### Supply Collateral
251
+
252
+ ```typescript
253
+ const { buildTx, getRequirements } = market.supplyCollateral({
254
+ amount: 1000000000000000000n,
255
+ userAddress: "0xUser...",
256
+ });
257
+
258
+ const requirements = await getRequirements();
259
+ const tx = buildTx(requirementSignature);
260
+ ```
261
+
262
+ ### Borrow
263
+
264
+ ```typescript
265
+ const positionData = await market.getPositionData("0xUser...");
266
+
267
+ const { buildTx, getRequirements } = market.borrow({
268
+ amount: 500000000000000000n,
269
+ userAddress: "0xUser...",
270
+ positionData,
271
+ });
272
+
273
+ const requirements = await getRequirements();
274
+ const tx = buildTx();
275
+ ```
276
+
277
+ ### Supply Collateral & Borrow
278
+
279
+ ```typescript
280
+ const positionData = await market.getPositionData("0xUser...");
281
+
282
+ const { buildTx, getRequirements } = market.supplyCollateralBorrow({
283
+ amount: 1000000000000000000n,
284
+ borrowAmount: 500000000000000000n,
285
+ userAddress: "0xUser...",
286
+ positionData,
287
+ });
288
+
289
+ const requirements = await getRequirements();
290
+ const tx = buildTx(requirementSignature);
291
+ ```
292
+
293
+ ### Repay
294
+
295
+ Two modes depending on whether the caller specifies `assets` (partial repay) or `shares` (full repay, immune to interest accrual between quote and inclusion):
296
+
297
+ ```typescript
298
+ const positionData = await market.getPositionData("0xUser...");
299
+
300
+ // Partial repay — by assets
301
+ const { buildTx, getRequirements } = market.repay({
302
+ assets: 250000000000000000n,
303
+ userAddress: "0xUser...",
304
+ positionData,
305
+ });
306
+
307
+ // Full repay — by shares (recommended to clear the full debt atomically)
308
+ const { buildTx, getRequirements } = market.repay({
309
+ shares: positionData.borrowShares,
310
+ userAddress: "0xUser...",
311
+ positionData,
312
+ });
313
+
314
+ const requirements = await getRequirements();
315
+ const tx = buildTx(requirementSignature);
316
+ ```
317
+
318
+ Repay does **not** require Morpho authorization (it only requires a loan token approval for `GeneralAdapter1`).
319
+
320
+ ### Withdraw Collateral
321
+
322
+ ```typescript
323
+ const positionData = await market.getPositionData("0xUser...");
324
+
325
+ const { buildTx } = market.withdrawCollateral({
326
+ amount: 500000000000000000n,
327
+ userAddress: "0xUser...",
328
+ positionData,
329
+ });
330
+
331
+ const tx = buildTx();
332
+ ```
333
+
334
+ Direct call to `morpho.withdrawCollateral()` — no bundler, no `GeneralAdapter1` authorization needed. The SDK validates position health after withdrawal against the LLTV buffer to prevent instant liquidation.
335
+
336
+ ### Repay & Withdraw Collateral
337
+
338
+ ```typescript
339
+ const positionData = await market.getPositionData("0xUser...");
340
+
341
+ const { buildTx, getRequirements } = market.repayWithdrawCollateral({
342
+ assets: 250000000000000000n, // or shares: ...
343
+ withdrawAmount: 500000000000000000n,
344
+ userAddress: "0xUser...",
345
+ positionData,
346
+ });
347
+
348
+ const requirements = await getRequirements();
349
+ const tx = buildTx(requirementSignature);
350
+ ```
351
+
352
+ Atomically bundles repay → withdraw collateral via bundler3. Bundle order is critical: repay runs first to reduce debt, then withdraw. Requires both a loan token approval (for repay) and a Morpho authorization (for withdraw). The SDK validates combined position health by simulating the repay before checking withdrawal safety.
353
+
354
+ ### Borrow with Shared Liquidity (Reallocations)
355
+
356
+ When a market lacks sufficient liquidity, you can reallocate liquidity from other markets managed by MetaMorpho Vaults via the **PublicAllocator** contract:
357
+
358
+ ```typescript
359
+ import type { VaultReallocation } from "@morpho-org/morpho-sdk";
360
+
361
+ const reallocations: VaultReallocation[] = [
362
+ {
363
+ vault: "0xVault...", // MetaMorpho vault to reallocate from
364
+ fee: 0n, // PublicAllocator fee in native token (can be 0)
365
+ withdrawals: [
366
+ {
367
+ marketParams: sourceMarketParams, // Source market to withdraw from
368
+ amount: 2000000000n, // Amount to withdraw
369
+ },
370
+ ],
371
+ },
372
+ ];
373
+
374
+ const positionData = await market.getPositionData("0xUser...");
375
+
376
+ // Borrow with reallocations
377
+ const { buildTx, getRequirements } = market.borrow({
378
+ amount: 500000000000000000n,
379
+ userAddress: "0xUser...",
380
+ positionData,
381
+ reallocations,
382
+ });
383
+
384
+ const requirements = await getRequirements();
385
+ const tx = buildTx();
386
+ // tx.value includes the sum of all reallocation fees
387
+ ```
388
+
389
+ Reallocations also work with `supplyCollateralBorrow`:
390
+
391
+ ```typescript
392
+ const { buildTx, getRequirements } = market.supplyCollateralBorrow({
393
+ amount: 1000000000000000000n,
394
+ borrowAmount: 500000000000000000n,
395
+ userAddress: "0xUser...",
396
+ positionData,
397
+ reallocations,
398
+ });
399
+ ```
400
+
401
+ ## Architecture
402
+
403
+ ```mermaid
404
+ graph LR
405
+ MC[MorphoClient]
406
+
407
+ MC -->|.vaultV1| MV1
408
+ MC -->|.vaultV2| MV2
409
+ MC -->|.marketV1| MM1
410
+
411
+ subgraph VaultV1 Flow
412
+ MV1[MorphoVaultV1]
413
+ MV1 --> V1D[vaultV1Deposit]
414
+ MV1 --> V1W[vaultV1Withdraw]
415
+ MV1 --> V1R[vaultV1Redeem]
416
+ MV1 --> V1M[vaultV1MigrateToV2]
417
+
418
+ V1D -->|nativeTransfer + wrapNative + erc4626Deposit| B1[Bundler3]
419
+ V1W -->|direct call| MM[MetaMorpho]
420
+ V1R -->|direct call| MM
421
+ V1M -->|erc20TransferFrom + erc4626Redeem + erc4626Deposit| B1
422
+ end
423
+
424
+ subgraph VaultV2 Flow
425
+ MV2[MorphoVaultV2]
426
+ MV2 --> V2D[vaultV2Deposit]
427
+ MV2 --> V2W[vaultV2Withdraw]
428
+ MV2 --> V2R[vaultV2Redeem]
429
+ MV2 --> V2FW[vaultV2ForceWithdraw]
430
+ MV2 --> V2FR[vaultV2ForceRedeem]
431
+
432
+ V2D -->|nativeTransfer + wrapNative + erc4626Deposit| B2[Bundler3]
433
+ V2W -->|direct call| V2C[VaultV2 Contract]
434
+ V2R -->|direct call| V2C
435
+ V2FW -->|multicall| V2C
436
+ V2FR -->|multicall| V2C
437
+ end
438
+
439
+ subgraph MarketV1 Flow
440
+ MM1[MorphoMarketV1]
441
+ MM1 --> M1SC[marketV1SupplyCollateral]
442
+ MM1 --> M1B[marketV1Borrow]
443
+ MM1 --> M1SCB[marketV1SupplyCollateralBorrow]
444
+
445
+ M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3[Bundler3]
446
+ M1B -->|reallocateTo? + morphoBorrow| B3
447
+ M1SCB -->|transfer + supplyCollateral + reallocateTo? + borrow| B3
448
+
449
+ B3 -.->|reallocateTo| PA[PublicAllocator]
450
+ end
451
+
452
+
453
+ subgraph Shared
454
+ REQ[getRequirements]
455
+ end
456
+
457
+ MV1 -.->|approval / permit| REQ
458
+ MV2 -.->|approval / permit| REQ
459
+ MM1 -.->|approval / permit / authorization| REQ
460
+
461
+ style B1 fill:#e8f5e9,stroke:#4caf50
462
+ style B2 fill:#e8f5e9,stroke:#4caf50
463
+ style B3 fill:#e8f5e9,stroke:#4caf50
464
+ style MM fill:#fff3e0,stroke:#ff9800
465
+ style V2C fill:#e3f2fd,stroke:#2196f3
466
+ style REQ fill:#f3e5f5,stroke:#9c27b0
467
+ style PA fill:#fff9c4,stroke:#f9a825
468
+ ```
469
+
470
+ ## Local Development
471
+
472
+ Link this package to your app for local debugging:
473
+
474
+ ```bash
475
+ # In this morpho-sdk project
476
+ pnpm run build:link
477
+ ```
478
+
479
+ In your other project:
480
+
481
+ ```bash
482
+ # Link the local package
483
+ pnpm link @morpho-org/morpho-sdk
484
+ ```
485
+
486
+ ## Contributing
487
+
488
+ Contributions are welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) for development setup, code style, and the PR workflow.
489
+
490
+ ## Security
491
+
492
+ To report a vulnerability, see [SECURITY.md](./SECURITY.md). **Please do not open a public issue for security reports.**
493
+
494
+ ## License
495
+
496
+ MIT — see [LICENSE](./LICENSE).
@@ -0,0 +1,4 @@
1
+ export * from "./marketV1";
2
+ export * from "./requirements";
3
+ export * from "./vaultV1";
4
+ export * from "./vaultV2";
@@ -0,0 +1,20 @@
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("./marketV1"), exports);
18
+ __exportStar(require("./requirements"), exports);
19
+ __exportStar(require("./vaultV1"), exports);
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
+ };