@morpho-org/morpho-sdk 5.3.3 → 5.4.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.
package/README.md CHANGED
@@ -5,11 +5,9 @@
5
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](./LICENSE)
6
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
7
 
8
- ## Overview
8
+ > 📖 **Full documentation → [docs.morpho.org/developers/sdks/morpho-sdk](https://docs.morpho.org/developers/sdks/morpho-sdk/)**
9
9
 
10
- > **The abstraction layer that simplifies Morpho protocol**
11
-
12
- Build transactions for **VaultV1** (MetaMorpho), **VaultV2**, **Blue** (Morpho Blue), and **Midnight** fixed-rate markets on EVM-compatible chains.
10
+ Build transactions for Morpho's **VaultV1** (MetaMorpho), **VaultV2**, **Blue**, and **Midnight** fixed-rate markets on every chain where Morpho is deployed. Custom deployments can be added with `registerCustomAddresses` from `@morpho-org/blue-sdk`.
13
11
 
14
12
  ## Installation
15
13
 
@@ -17,266 +15,101 @@ Build transactions for **VaultV1** (MetaMorpho), **VaultV2**, **Blue** (Morpho B
17
15
  pnpm add @morpho-org/morpho-sdk
18
16
  ```
19
17
 
20
- ## Usage
18
+ ## Actions
21
19
 
22
- ### Entities & Actions
23
-
24
- | Entity | Action | Route | Why |
25
- | ------------ | ------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------- |
26
- | **VaultV2** | `deposit` | Bundler (general adapter) | Enforces `maxSharePrice` — inflation attack prevention. Supports native token wrapping. |
27
- | | `withdraw` | Direct vault call | No attack surface, no bundler overhead needed |
28
- | | `redeem` | Direct vault call | No attack surface, no bundler overhead needed |
29
- | | `forceWithdraw` | Vault `multicall` | N `forceDeallocate` + 1 `withdraw` in a single tx |
30
- | | `forceRedeem` | Vault `multicall` | N `forceDeallocate` + 1 `redeem` in a single tx |
31
- | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
32
- | | `withdraw` | Direct vault call | No attack surface |
33
- | | `redeem` | Direct vault call | No attack surface |
34
- | | `migrateToV2` | Bundler (general adapter) | Atomic V1 → V2 migration: redeem V1 shares + deposit into V2 in one tx. Slippage-protected. |
35
- | **Blue** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
36
- | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
37
- | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
38
- | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
39
- | | `repay` | Bundler (general adapter) | `erc20TransferFrom` + `morphoRepay` with `maxSharePrice` protection. Supports partial or full. |
40
- | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
41
- | | `withdrawCollateral` | Direct Morpho call | No bundler overhead. Validates position health after withdrawal. |
42
- | | `repayWithdrawCollateral` | Bundler (general adapter) | Atomic repay + withdraw. Bundle order matters: repay first, then withdraw. |
43
- | | `refinance` | Bundler (general adapter) | Atomic position migration to another market with the same loan + collateral tokens. Flash-collateral via the target's `onMorphoSupplyCollateral` callback: borrow target → repay source → withdraw source collateral. Requires GA1 auth. Supports target reallocations. |
44
- | **Midnight** | `takeLend` / `takeBorrow` | MidnightBundles | Takes fixed-rate offers with ordered approval and authorization requirements. |
45
- | | `supplyCollateralTakeBorrow` | MidnightBundles | Atomically supplies collateral and takes fixed-rate borrow liquidity. |
46
- | | `makeLend` / `makeBorrow` | Midnight mempool | Builds, validates, signs or ratifies, and submits maker offer trees. |
47
- | | `supplyCollateral` / `redeem` / `cancelOffer` | Direct Midnight call | Encodes direct collateral, credit, and offer-management operations. |
48
- | | `repayWithdrawCollateral` | MidnightBundles | Atomically repays credit and withdraws collateral. |
49
-
50
- ### The `getRequirements` flow
51
-
52
- Every action that touches a user's tokens or positions returns two things:
53
-
54
- - `buildTx(signatures?)` — builds the final viem `Transaction` object. Takes the collected signature results required by the flow, including permit / Permit2, Morpho authorization, or a Midnight offer-root signature.
55
- - `getRequirements()` — returns the list of on-chain pre-requisites that must be satisfied first.
56
-
57
- Typical requirements:
58
-
59
- - **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.
60
- - **Permit / Permit2 signature** — off-chain approvals that go into `buildTx` in the `signatures` array, avoiding the extra approval tx. Enabled via `morphoViemExtension({ supportSignature: true })`.
61
- - **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.
62
- - **Midnight authorization or ratification** — Midnight flows return the required operator authorization, Ecrecover offer-root signature, or SetterRatifier transaction before the final take or mempool submission.
63
-
64
- Usage pattern:
20
+ Each entity exposes a set of actions. Bundled actions route through bundler3 (via `GeneralAdapter1`); the rest are direct contract calls.
65
21
 
66
- ```typescript
67
- const { buildTx, getRequirements } = await vault.deposit({
68
- /* ... */
69
- });
22
+ | Entity | Actions | Route |
23
+ | --- | --- | --- |
24
+ | **VaultV1** (MetaMorpho) | `deposit`, `migrateToV2` | Bundler |
25
+ | | `withdraw`, `redeem` | Direct call |
26
+ | **VaultV2** | `deposit` | Bundler |
27
+ | | `withdraw`, `redeem` | Direct call |
28
+ | | `forceWithdraw`, `forceRedeem` | Vault multicall |
29
+ | **Blue** | `supply`, `supplyCollateral`, `borrow`, `supplyCollateralBorrow`, `repay`, `withdraw`, `repayWithdrawCollateral`, `refinance` | Bundler |
30
+ | | `withdrawCollateral` | Direct call |
31
+ | **Midnight** | `takeLend`, `takeBorrow`, `supplyCollateralTakeBorrow`, `repayWithdrawCollateral` | Midnight Bundles |
32
+ | | `makeLend`, `makeBorrow` | Midnight mempool |
33
+ | | `supplyCollateral`, `redeem`, `cancelOffer` | Direct call |
70
34
 
71
- const requirements = await getRequirements();
72
- // → [{ type: "approval", tx: {...} }, { type: "permit", sign: async () => {...} }]
35
+ ## How it works
73
36
 
74
- // Consumer satisfies each requirement (send tx / sign permit), collects the signature,
75
- // then calls buildTx to get the final transaction:
76
- const tx = buildTx([permitSignature]);
77
- ```
37
+ Actions that pull tokens or touch a position return `{ buildTx, getRequirements }`. Direct calls — vault `withdraw` / `redeem`, `forceWithdraw` / `forceRedeem`, and Blue `withdrawCollateral` — have no prerequisites and return only `{ buildTx }`.
78
38
 
79
- ### Integration invariant — builder = signer
80
-
81
- **`userAddress` MUST equal the account that ends up signing/executing the tx.** Critical for `repayWithdrawCollateral`, whose bundle mixes explicit `onBehalf` (repay) with implicit `msg.sender` (transfer-from + withdraw) — see [BUNDLER3.md](./BUNDLER3.md#other-pitfalls). Transaction builders do not validate this at build time, so callers MUST keep `userAddress` aligned with the signing account themselves. The signature requirements (`encodeErc20Permit` / `encodeErc20Permit2Approve`) take a `WalletClient` and enforce the invariant at `sign()` time via `validateUserAddress`, rejecting any `sign(client, userAddress)` where `client.account.address !== userAddress` with `MissingClientPropertyError` / `AddressMismatchError`.
82
-
83
- | Entity | Action | Route | Why |
84
- | ------------ | ------------------------ | ------------------------- | --------------------------------------------------------------------------------------------------- |
85
- | **VaultV2** | `deposit` | Bundler (general adapter) | Enforces `maxSharePrice` — inflation attack prevention. Supports native token wrapping. |
86
- | | `withdraw` | Direct vault call | No attack surface, no bundler overhead needed |
87
- | | `redeem` | Direct vault call | No attack surface, no bundler overhead needed |
88
- | | `forceWithdraw` | Vault `multicall` | N `forceDeallocate` + 1 `withdraw` in a single tx |
89
- | | `forceRedeem` | Vault `multicall` | N `forceDeallocate` + 1 `redeem` in a single tx |
90
- | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
91
- | | `withdraw` | Direct vault call | No attack surface |
92
- | | `redeem` | Direct vault call | No attack surface |
93
- | | `migrateToV2` | Bundler (general adapter) | Atomic V1 → V2 migration: redeem V1 shares + deposit into V2 in one tx. Slippage-protected. |
94
- | **Blue** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
95
- | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
96
- | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
97
- | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
98
- | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
99
- | | `refinance` | Bundler (general adapter) | Atomic position migration to another market sharing the same loan + collateral tokens. Requires GA1 auth. Supports reallocations. |
100
- | **Midnight** | `takeLend` / `takeBorrow` | MidnightBundles | Takes fixed-rate offers with ordered approval and authorization requirements. |
101
- | | `makeLend` / `makeBorrow` | Midnight mempool | Builds and submits validated maker offer trees. |
102
- | | `supplyCollateral` / `redeem` / `cancelOffer` | Direct Midnight call | Encodes direct Midnight operations. |
103
- | | `repayWithdrawCollateral` | MidnightBundles | Atomically repays credit and withdraws collateral. |
104
-
105
- ### VaultV2
39
+ - **`getRequirements()`** — async; the on-chain prerequisites to satisfy first: ERC-20 approvals, permit / Permit2 signatures, Morpho authorization, or (for Midnight) operator authorization and offer-root signatures.
40
+ - **`buildTx(signatures?)`** — synchronous; the final, deep-frozen viem transaction. Pass any signatures collected from the requirements.
106
41
 
107
42
  ```typescript
108
- import { morphoViemExtension } from "@morpho-org/morpho-sdk";
109
- import { createPublicClient, http } from "viem";
110
- import { mainnet } from "viem/chains";
111
-
112
- const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
113
- morphoViemExtension(),
114
- );
115
-
116
- const vault = client.morpho.vaultV2("0xVault...", 1);
117
- ```
118
-
119
- #### Deposit
120
-
121
- ```typescript
122
- const { buildTx, getRequirements } = await vault.deposit({
123
- amount: 1000000000000000000n,
124
- userAddress: "0xUser...",
125
- });
43
+ const { buildTx, getRequirements } = await vault.deposit({ amount, userAddress });
126
44
 
127
45
  const requirements = await getRequirements();
128
- const tx = buildTx([requirementSignature]);
129
- ```
130
-
131
- ##### Deposit with native token wrapping
132
-
133
- For vaults whose underlying asset is wNative, you can deposit native token that will be automatically wrapped:
134
-
135
- ```typescript
136
- // Native ETH only — wraps 1 ETH to WETH and deposits
137
- const { buildTx, getRequirements } = await vault.deposit({
138
- nativeAmount: 1000000000000000000n,
139
- userAddress: "0xUser...",
140
- });
141
-
142
- // Mixed — 0.5 WETH (ERC-20) + 0.5 native ETH wrapped to WETH
143
- const { buildTx, getRequirements } = await vault.deposit({
144
- amount: 500000000000000000n,
145
- nativeAmount: 500000000000000000n,
146
- userAddress: "0xUser...",
147
- });
46
+ // Send each approval tx and collect each signature, then:
47
+ const tx = buildTx([permitSignature]);
148
48
  ```
149
49
 
150
- 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`.
50
+ Enable off-chain approvals (permit / Permit2) with `morphoViemExtension({ supportSignature: true })`.
151
51
 
152
- #### Withdraw
153
-
154
- ```typescript
155
- const { buildTx } = vault.withdraw({
156
- amount: 500000000000000000n,
157
- userAddress: "0xUser...",
158
- });
52
+ ### `userAddress` must be the signer
159
53
 
160
- const tx = buildTx();
161
- ```
54
+ `userAddress` must be the account that signs and sends the transaction. Builders don't enforce this, but the signature helpers do — `sign()` throws `AddressMismatchError` when the wallet's account differs. It matters most for `repayWithdrawCollateral`; see [BUNDLER3.md](./BUNDLER3.md#other-pitfalls).
162
55
 
163
- #### Redeem
56
+ ## Usage
164
57
 
165
58
  ```typescript
166
- const { buildTx } = vault.redeem({
167
- shares: 1000000000000000000n,
168
- userAddress: "0xUser...",
169
- });
170
-
171
- const tx = buildTx();
172
- ```
59
+ import {
60
+ morphoViemExtension,
61
+ isRequirementSignature,
62
+ } from "@morpho-org/morpho-sdk";
63
+ import { createPublicClient, createWalletClient, custom, http } from "viem";
64
+ import { mainnet } from "viem/chains";
173
65
 
174
- #### Force Withdraw
66
+ // Reads on-chain state, extended with the `morpho` namespace.
67
+ const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
68
+ morphoViemExtension(),
69
+ );
175
70
 
176
- ```typescript
177
- const { buildTx } = vault.forceWithdraw({
178
- deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
179
- withdraw: { amount: 500000000000000000n },
180
- userAddress: "0xUser...",
71
+ // Signs permits and sends the approval / authorization transactions.
72
+ const walletClient = createWalletClient({
73
+ account: "0xUser...",
74
+ chain: mainnet,
75
+ transport: custom(window.ethereum), // any EIP-1193 provider
181
76
  });
182
-
183
- const tx = buildTx();
184
77
  ```
185
78
 
186
- #### Force Redeem
79
+ Create an entity — every factory takes a chain ID as its last argument:
187
80
 
188
- ```typescript
189
- const { buildTx } = vault.forceRedeem({
190
- deallocations: [{ adapter: "0xAdapter...", amount: 100n }],
191
- redeem: { shares: 1000000000000000000n },
192
- userAddress: "0xUser...",
193
- });
81
+ - `client.morpho.vaultV1(address, chainId)` / `client.morpho.vaultV2(address, chainId)`
82
+ - `client.morpho.blue(marketParams, chainId)`
83
+ - `client.morpho.midnight(chainId)`
194
84
 
195
- const tx = buildTx();
196
- ```
85
+ ### Vault deposit / withdraw
197
86
 
198
- ### VaultV1
87
+ Deposit routes through the bundler and may require an approval or permit:
199
88
 
200
89
  ```typescript
201
- const vault = client.morpho.vaultV1("0xVault...", 1);
202
- ```
203
-
204
- #### Deposit
90
+ const vault = client.morpho.vaultV2("0xVault...", 1);
205
91
 
206
- ```typescript
207
92
  const { buildTx, getRequirements } = await vault.deposit({
208
93
  amount: 1000000000000000000n,
209
94
  userAddress: "0xUser...",
210
95
  });
211
-
212
96
  const requirements = await getRequirements();
213
- const tx = buildTx([requirementSignature]);
97
+ const tx = buildTx([permitSignature]);
214
98
  ```
215
99
 
216
- #### Withdraw
100
+ Withdraw is a direct vault call with no requirements:
217
101
 
218
102
  ```typescript
219
103
  const { buildTx } = vault.withdraw({
220
104
  amount: 500000000000000000n,
221
105
  userAddress: "0xUser...",
222
106
  });
223
-
224
107
  const tx = buildTx();
225
108
  ```
226
109
 
227
- #### Redeem
110
+ For wNative vaults, pass `nativeAmount` instead of `amount` to deposit native ETH (wrapped automatically).
228
111
 
229
- ```typescript
230
- const { buildTx } = vault.redeem({
231
- shares: 1000000000000000000n,
232
- userAddress: "0xUser...",
233
- });
234
-
235
- const tx = buildTx();
236
- ```
237
-
238
- #### Migrate to V2
239
-
240
- Atomically migrate a full position from a VaultV1 (MetaMorpho) vault into a VaultV2 vault. In a single bundler transaction, the user's V1 shares are pulled into `GeneralAdapter1`, redeemed for the underlying asset, and re-deposited into the V2 vault on the user's behalf. Guarantees:
241
-
242
- - **Atomic** — redeem V1 + deposit V2 happen in one transaction; the user is never left holding loose assets between the two legs.
243
- - **Slippage-protected on both legs** — the entity derives a `minSharePriceVaultV1` (V1 redeem floor) and a `maxSharePriceVaultV2` (V2 deposit ceiling, which doubles as the ERC-4626 inflation-attack guard) from live vault state plus your `slippageTolerance`.
244
- - **Same-asset only** — both vaults must share the same underlying asset. A mismatch throws `VaultAssetMismatchError`; a `sourceVault` whose address doesn't match the entity throws `VaultAddressMismatchError`.
245
-
246
- `sourceVault` / `targetVault` are the accrual snapshots returned by each entity's `getData()`.
247
-
248
- ```typescript
249
- const sourceVault = client.morpho.vaultV1("0xV1Vault...", 1);
250
- const targetVault = client.morpho.vaultV2("0xV2Vault...", 1);
251
-
252
- const { buildTx, getRequirements } = sourceVault.migrateToV2({
253
- userAddress: "0xUser...",
254
- sourceVault: await sourceVault.getData(),
255
- targetVault: await targetVault.getData(),
256
- shares: 1000000000000000000n, // full V1 position, in V1 shares
257
- slippageTolerance: 300000000000000n, // optional, WAD (0.03%); defaults to DEFAULT_SLIPPAGE_TOLERANCE, capped at 10%
258
- });
259
-
260
- // GeneralAdapter1 must be allowed to pull the V1 shares. Because V1 shares
261
- // implement EIP-2612, this is returned either as an ERC-20 approval tx or as a
262
- // signable permit requirement (when the extension was created with `supportSignature: true`).
263
- const requirements = await getRequirements();
264
- const signatures = [];
265
- for (const requirement of requirements) {
266
- if (isRequirementApproval(requirement)) {
267
- await walletClient.sendTransaction(requirement); // approve GA1 to pull V1 shares
268
- } else if (isRequirementSignature(requirement)) {
269
- signatures.push(await requirement.sign(walletClient, "0xUser..."));
270
- }
271
- }
272
-
273
- const tx = buildTx(signatures);
274
- ```
275
-
276
- ### Blue
277
-
278
- Blue (Morpho Blue) is Morpho's immutable, variable-rate lending primitive: isolated markets whose
279
- borrow rate floats with utilization. Each market is identified by its `MarketParams`.
112
+ ### Blue: supply collateral & borrow
280
113
 
281
114
  ```typescript
282
115
  const market = client.morpho.blue(
@@ -287,271 +120,41 @@ const market = client.morpho.blue(
287
120
  irm: "0xIrm...",
288
121
  lltv: 860000000000000000n,
289
122
  },
290
- 1
123
+ 1,
291
124
  );
292
- ```
293
-
294
- #### Supply (loan asset)
295
-
296
- Supply the loan asset to earn yield on the market.
297
-
298
- ```typescript
299
- const marketData = await market.getMarketData();
300
-
301
- const { buildTx, getRequirements } = market.supply({
302
- amount: 1000000000n,
303
- userAddress: "0xUser...",
304
- marketData,
305
- });
306
-
307
- const requirements = await getRequirements();
308
- const tx = buildTx([requirementSignature]);
309
- ```
310
-
311
- ##### Supply with native token wrapping
312
-
313
- If the market's `loanToken` is the chain's wNative, you can supply native token that will be wrapped automatically:
314
-
315
- ```typescript
316
- const { buildTx, getRequirements } = market.supply({
317
- nativeAmount: 1000000000000000000n,
318
- userAddress: "0xUser...",
319
- marketData,
320
- });
321
- ```
322
-
323
- The bundle routes through `GeneralAdapter1` with `maxSharePrice` slippage protection (anti-inflation guard).
324
-
325
- #### Supply Collateral
326
-
327
- ```typescript
328
- const { buildTx, getRequirements } = market.supplyCollateral({
329
- amount: 1000000000000000000n,
330
- userAddress: "0xUser...",
331
- });
332
-
333
- const requirements = await getRequirements();
334
- const tx = buildTx([requirementSignature]);
335
- ```
336
-
337
- #### Borrow
338
-
339
- ```typescript
340
- const positionData = await market.getPositionData("0xUser...");
341
125
 
342
- const { buildTx, getRequirements } = market.borrow({
343
- amount: 500000000000000000n,
344
- userAddress: "0xUser...",
345
- positionData,
346
- });
347
-
348
- const requirements = await getRequirements();
349
- const tx = buildTx();
350
- ```
351
-
352
- #### Supply Collateral & Borrow
353
-
354
- ```typescript
355
126
  const positionData = await market.getPositionData("0xUser...");
356
127
 
357
128
  const { buildTx, getRequirements } = market.supplyCollateralBorrow({
358
- amount: 1000000000000000000n,
359
- borrowAmount: 500000000000000000n,
360
- userAddress: "0xUser...",
361
- positionData,
362
- });
363
-
364
- const requirements = await getRequirements();
365
- const tx = buildTx([requirementSignature]);
366
- ```
367
-
368
- #### Repay
369
-
370
- Two modes depending on whether the caller specifies `amount` (partial repay) or `shares` (full repay, immune to interest accrual between quote and inclusion). Optionally attach `nativeAmount` to fund the repay by wrapping native ETH (loan token must be the chain's wNative):
371
-
372
- ```typescript
373
- const positionData = await market.getPositionData("0xUser...");
374
-
375
- // Partial repay — by amount
376
- const { buildTx, getRequirements } = market.repay({
377
- amount: 250000000000000000n,
378
- userAddress: "0xUser...",
379
- positionData,
380
- });
381
-
382
- // Full repay — by shares (recommended to clear the full debt atomically)
383
- const { buildTx, getRequirements } = market.repay({
384
- shares: positionData.borrowShares,
385
- userAddress: "0xUser...",
386
- positionData,
387
- });
388
-
389
- const requirements = await getRequirements();
390
- const tx = buildTx([requirementSignature]);
391
- ```
392
-
393
- Repay does **not** require Morpho authorization (it only requires a loan token approval for `GeneralAdapter1`).
394
-
395
- #### Withdraw (loan asset)
396
-
397
- 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`).
398
-
399
- ```typescript
400
- const positionData = await market.getPositionData("0xUser...");
401
-
402
- // Withdraw an exact amount of loan asset
403
- const { buildTx, getRequirements } = market.withdraw({
404
- assets: 500000000n,
405
- userAddress: "0xUser...",
406
- positionData,
407
- });
408
-
409
- // Or close the full supply position by shares
410
- const { buildTx, getRequirements } = market.withdraw({
411
- shares: positionData.supplyShares,
412
- userAddress: "0xUser...",
413
- positionData,
414
- });
415
-
416
- const requirements = await getRequirements();
417
- const tx = buildTx();
418
- ```
419
-
420
- Loan-asset withdraw requires Morpho authorization for `GeneralAdapter1` (returned by `getRequirements` when missing). It does **not** require a token approval.
421
-
422
- #### Withdraw Collateral
423
-
424
- ```typescript
425
- const positionData = await market.getPositionData("0xUser...");
426
-
427
- const { buildTx } = market.withdrawCollateral({
428
- amount: 500000000000000000n,
429
- userAddress: "0xUser...",
430
- positionData,
431
- });
432
-
433
- const tx = buildTx();
434
- ```
435
-
436
- 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.
437
-
438
- #### Repay & Withdraw Collateral
439
-
440
- ```typescript
441
- const positionData = await market.getPositionData("0xUser...");
442
-
443
- const { buildTx, getRequirements } = market.repayWithdrawCollateral({
444
- amount: 250000000000000000n, // or shares: ...
445
- withdrawAmount: 500000000000000000n,
129
+ amount: 1000000000000000000n, // collateral
130
+ borrowAmount: 500000000000000000n, // loan asset
446
131
  userAddress: "0xUser...",
447
132
  positionData,
448
133
  });
449
134
 
450
- const requirements = await getRequirements();
451
- const tx = buildTx([requirementSignature]);
452
- ```
453
-
454
- 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.
455
-
456
- #### Refinance
457
-
458
- Atomically migrate a position from this market to another Morpho Blue market that shares the **same loan and collateral tokens** on the same chain — no flash loan, no upfront capital. The bundle flash-collateralizes the target via its `onMorphoSupplyCollateral` callback: inside the callback `GeneralAdapter1` borrows on the target, repays the source debt, then withdraws the source collateral to settle the deferred transfer.
459
-
460
- ```typescript
461
- const source = client.morpho.blue(sourceMarketParams, 1);
462
- const target = client.morpho.blue(targetMarketParams, 1);
463
-
464
- const positionData = await source.getPositionData("0xUser...");
465
- const targetPositionData = await target.getPositionData("0xUser...");
466
-
467
- // Refinance by assets — exact-asset borrow and repay, no GA1 dust
468
- const { buildTx, getRequirements } = source.refinance({
469
- userAddress: "0xUser...",
470
- positionData,
471
- target: { marketParams: targetMarketParams, positionData: targetPositionData },
472
- collateralAmount: 1000000000000000000n,
473
- borrowAssets: 500000000000000000n,
474
- });
475
-
476
- // Or migrate the full debt by shares (immune to interest accrual between quote and inclusion)
477
- const { buildTx, getRequirements } = source.refinance({
478
- userAddress: "0xUser...",
479
- positionData,
480
- target: { marketParams: targetMarketParams, positionData: targetPositionData },
481
- collateralAmount: 1000000000000000000n,
482
- borrowShares: positionData.borrowShares,
483
- });
484
-
485
- // Collateral-only migration — omit both borrow fields
486
- const { buildTx, getRequirements } = source.refinance({
487
- userAddress: "0xUser...",
488
- positionData,
489
- target: { marketParams: targetMarketParams, positionData: targetPositionData },
490
- collateralAmount: 1000000000000000000n,
491
- });
492
-
493
- const requirements = await getRequirements();
494
- const tx = buildTx();
495
- ```
496
-
497
- The SDK validates ownership, token/id match, and that amounts do not exceed the source position. Health is checked against `LLTV − buffer` where it can degrade: the residual source position is validated whenever debt remains after the repay, and the aggregate target position is validated whenever a borrow leg is migrated. Collateral-only migrations (both borrow fields omitted) skip the target health check — they can't degrade target health and would otherwise fail on missing-oracle target markets. Both markets are forward-accrued to `now`; in shares mode the target borrow overshoots by `slippageTolerance` and the callback sweeps the residual back into the target debt (or skims it to the user). `getRequirements` returns the `setAuthorization(generalAdapter1, true)` transaction when GA1 is not yet authorized — a single global authorization covers both markets. Optional `targetReallocations` top up target-market liquidity via the **PublicAllocator** (same mechanism as `borrow`); their fees add to `tx.value`.
498
-
499
- #### Borrow with Shared Liquidity (Reallocations)
500
-
501
- When a market lacks sufficient liquidity, you can reallocate liquidity from other markets managed by MetaMorpho Vaults via the **PublicAllocator** contract:
502
-
503
- ```typescript
504
- import type { VaultReallocation } from "@morpho-org/morpho-sdk";
505
-
506
- const reallocations: VaultReallocation[] = [
507
- {
508
- vault: "0xVault...", // MetaMorpho vault to reallocate from
509
- fee: 0n, // PublicAllocator fee in native token (can be 0)
510
- withdrawals: [
511
- {
512
- marketParams: sourceMarketParams, // Source market to withdraw from
513
- amount: 2000000000n, // Amount to withdraw
514
- },
515
- ],
516
- },
517
- ];
518
-
519
- const positionData = await market.getPositionData("0xUser...");
520
-
521
- // Borrow with reallocations
522
- const { buildTx, getRequirements } = market.borrow({
523
- amount: 500000000000000000n,
524
- userAddress: "0xUser...",
525
- positionData,
526
- reallocations,
527
- });
528
-
529
- const requirements = await getRequirements();
530
- const tx = buildTx();
531
- // tx.value includes the sum of all reallocation fees
532
- ```
533
-
534
- Reallocations also work with `supplyCollateralBorrow`:
135
+ // This flow can return more than one requirement — a collateral approval/permit
136
+ // and a one-time Morpho authorization for GeneralAdapter1. Satisfy each and pass
137
+ // every collected signature to buildTx.
138
+ const signatures = [];
139
+ for (const requirement of await getRequirements()) {
140
+ if (isRequirementSignature(requirement)) {
141
+ signatures.push(await requirement.sign(walletClient, "0xUser..."));
142
+ } else {
143
+ await walletClient.sendTransaction(requirement); // approval / authorization tx
144
+ }
145
+ }
535
146
 
536
- ```typescript
537
- const { buildTx, getRequirements } = market.supplyCollateralBorrow({
538
- amount: 1000000000000000000n,
539
- borrowAmount: 500000000000000000n,
540
- userAddress: "0xUser...",
541
- positionData,
542
- reallocations,
543
- });
147
+ const tx = buildTx(signatures);
544
148
  ```
545
149
 
546
- ### Midnight
150
+ The LLTV buffer guards against instant liquidation.
547
151
 
548
- Midnight exposes fixed-rate market flows through a chain-scoped entity. Fetch market or
549
- position state when required, resolve the ordered prerequisites, then build the final
550
- transaction synchronously.
152
+ ### Midnight: take a fixed-rate offer
551
153
 
552
154
  ```typescript
553
155
  const midnight = client.morpho.midnight(8453);
554
156
  const marketData = await midnight.getMarketData(marketId);
157
+
555
158
  const output = midnight.takeLend({
556
159
  accountAddress: lender,
557
160
  marketData,
@@ -565,7 +168,9 @@ const requirements = await output.getRequirements();
565
168
  const tx = output.buildTx();
566
169
  ```
567
170
 
568
- ### Architecture
171
+ See the [documentation](https://docs.morpho.org/developers/sdks/morpho-sdk/) for the full API: native wrapping, PublicAllocator reallocations, V1 → V2 migration, refinance, force withdraw/redeem, and Midnight maker flows.
172
+
173
+ ## Architecture
569
174
 
570
175
  ```mermaid
571
176
  graph LR
@@ -661,10 +266,8 @@ Link this package to your app for local debugging:
661
266
  pnpm run build:link
662
267
  ```
663
268
 
664
- In your other project:
665
-
666
269
  ```bash
667
- # Link the local package
270
+ # In your other project
668
271
  pnpm link @morpho-org/morpho-sdk
669
272
  ```
670
273
 
@@ -6,13 +6,19 @@ export declare const DEFAULT_LLTV_BUFFER: bigint;
6
6
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
7
7
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
8
8
  /**
9
- * The default maximum utilization allowed to reach when withdrawing shared liquidity.
9
+ * The default maximum utilization a source market may reach when withdrawing
10
+ * shared liquidity, scaled by WAD. Still overridable through the deprecated
11
+ * `maxWithdrawalUtilization` / `defaultMaxWithdrawalUtilization` options until
12
+ * the next major.
10
13
  */
11
- export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
14
+ export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 900000000000000000n;
12
15
  /**
13
- * The default target utilization above which shared liquidity reallocations are triggered.
16
+ * The default target utilization above which shared liquidity reallocations are
17
+ * triggered (and the level the target market is brought back to), scaled by WAD.
18
+ * Still overridable through the deprecated `supplyTargetUtilization` /
19
+ * `defaultSupplyTargetUtilization` options until the next major.
14
20
  */
15
- export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
21
+ export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 900000000000000000n;
16
22
  /**
17
23
  * Tokens that require setting allowance from zero before changing approval.
18
24
  */
@@ -10,13 +10,19 @@ exports.DEFAULT_LLTV_BUFFER = blue_sdk_1.MathLib.WAD / 200n;
10
10
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
11
11
  exports.MAX_ABSOLUTE_SHARE_PRICE = 100n * blue_sdk_1.MathLib.RAY;
12
12
  /**
13
- * The default maximum utilization allowed to reach when withdrawing shared liquidity.
13
+ * The default maximum utilization a source market may reach when withdrawing
14
+ * shared liquidity, scaled by WAD. Still overridable through the deprecated
15
+ * `maxWithdrawalUtilization` / `defaultMaxWithdrawalUtilization` options until
16
+ * the next major.
14
17
  */
15
- exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
18
+ exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 900000000000000000n;
16
19
  /**
17
- * The default target utilization above which shared liquidity reallocations are triggered.
20
+ * The default target utilization above which shared liquidity reallocations are
21
+ * triggered (and the level the target market is brought back to), scaled by WAD.
22
+ * Still overridable through the deprecated `supplyTargetUtilization` /
23
+ * `defaultSupplyTargetUtilization` options until the next major.
18
24
  */
19
- exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
25
+ exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = 900000000000000000n;
20
26
  /**
21
27
  * Tokens that require setting allowance from zero before changing approval.
22
28
  */
@@ -19,12 +19,20 @@ export interface PublicAllocatorOptions {
19
19
  /**
20
20
  * The maximum utilization each source market may reach when withdrawing
21
21
  * shared liquidity, scaled by WAD.
22
+ *
23
+ * @deprecated The source-market withdrawal ceiling is fixed at 90%
24
+ * ({@link DEFAULT_WITHDRAWAL_TARGET_UTILIZATION}) and will stop being
25
+ * configurable in the next major. Per-market overrides are still honored for now.
22
26
  */
23
27
  readonly maxWithdrawalUtilization?: Readonly<Record<MarketId, bigint | undefined>>;
24
28
  /**
25
29
  * The default maximum utilization source markets may reach when withdrawing
26
30
  * shared liquidity, scaled by WAD.
27
- * @default 92% (920000000000000000n)
31
+ *
32
+ * @default 90% (900000000000000000n)
33
+ * @deprecated The source-market withdrawal ceiling is fixed at 90%
34
+ * ({@link DEFAULT_WITHDRAWAL_TARGET_UTILIZATION}) and will stop being
35
+ * configurable in the next major. Overrides are still honored for now.
28
36
  */
29
37
  readonly defaultMaxWithdrawalUtilization?: bigint;
30
38
  }
@@ -70,12 +78,20 @@ export interface ReallocationComputeOptions extends PublicAllocatorOptions {
70
78
  * Per-market target utilization above which the shared liquidity algorithm
71
79
  * is triggered (scaled by WAD). Overrides `defaultSupplyTargetUtilization`
72
80
  * for the specified market.
81
+ *
82
+ * @deprecated The supply-target trigger is fixed at 90%
83
+ * ({@link DEFAULT_SUPPLY_TARGET_UTILIZATION}) and will stop being configurable
84
+ * in the next major. Per-market overrides are still honored for now.
73
85
  */
74
86
  readonly supplyTargetUtilization?: Readonly<Record<MarketId, bigint | undefined>>;
75
87
  /**
76
88
  * The default target utilization above which the shared liquidity algorithm
77
89
  * is triggered (scaled by WAD).
78
- * @default 90.5% (905000000000000000n)
90
+ *
91
+ * @default 90% (900000000000000000n)
92
+ * @deprecated The supply-target trigger is fixed at 90%
93
+ * ({@link DEFAULT_SUPPLY_TARGET_UTILIZATION}) and will stop being configurable
94
+ * in the next major. Overrides are still honored for now.
79
95
  */
80
96
  readonly defaultSupplyTargetUtilization?: bigint;
81
97
  }
@@ -6,13 +6,19 @@ export declare const DEFAULT_LLTV_BUFFER: bigint;
6
6
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
7
7
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
8
8
  /**
9
- * The default maximum utilization allowed to reach when withdrawing shared liquidity.
9
+ * The default maximum utilization a source market may reach when withdrawing
10
+ * shared liquidity, scaled by WAD. Still overridable through the deprecated
11
+ * `maxWithdrawalUtilization` / `defaultMaxWithdrawalUtilization` options until
12
+ * the next major.
10
13
  */
11
- export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
14
+ export declare const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 900000000000000000n;
12
15
  /**
13
- * The default target utilization above which shared liquidity reallocations are triggered.
16
+ * The default target utilization above which shared liquidity reallocations are
17
+ * triggered (and the level the target market is brought back to), scaled by WAD.
18
+ * Still overridable through the deprecated `supplyTargetUtilization` /
19
+ * `defaultSupplyTargetUtilization` options until the next major.
14
20
  */
15
- export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
21
+ export declare const DEFAULT_SUPPLY_TARGET_UTILIZATION = 900000000000000000n;
16
22
  /**
17
23
  * Tokens that require setting allowance from zero before changing approval.
18
24
  */
@@ -7,13 +7,19 @@ export const DEFAULT_LLTV_BUFFER = MathLib.WAD / 200n;
7
7
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
8
8
  export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
9
9
  /**
10
- * The default maximum utilization allowed to reach when withdrawing shared liquidity.
10
+ * The default maximum utilization a source market may reach when withdrawing
11
+ * shared liquidity, scaled by WAD. Still overridable through the deprecated
12
+ * `maxWithdrawalUtilization` / `defaultMaxWithdrawalUtilization` options until
13
+ * the next major.
11
14
  */
12
- export const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 920000000000000000n;
15
+ export const DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = 900000000000000000n;
13
16
  /**
14
- * The default target utilization above which shared liquidity reallocations are triggered.
17
+ * The default target utilization above which shared liquidity reallocations are
18
+ * triggered (and the level the target market is brought back to), scaled by WAD.
19
+ * Still overridable through the deprecated `supplyTargetUtilization` /
20
+ * `defaultSupplyTargetUtilization` options until the next major.
15
21
  */
16
- export const DEFAULT_SUPPLY_TARGET_UTILIZATION = 905000000000000000n;
22
+ export const DEFAULT_SUPPLY_TARGET_UTILIZATION = 900000000000000000n;
17
23
  /**
18
24
  * Tokens that require setting allowance from zero before changing approval.
19
25
  */
@@ -19,12 +19,20 @@ export interface PublicAllocatorOptions {
19
19
  /**
20
20
  * The maximum utilization each source market may reach when withdrawing
21
21
  * shared liquidity, scaled by WAD.
22
+ *
23
+ * @deprecated The source-market withdrawal ceiling is fixed at 90%
24
+ * ({@link DEFAULT_WITHDRAWAL_TARGET_UTILIZATION}) and will stop being
25
+ * configurable in the next major. Per-market overrides are still honored for now.
22
26
  */
23
27
  readonly maxWithdrawalUtilization?: Readonly<Record<MarketId, bigint | undefined>>;
24
28
  /**
25
29
  * The default maximum utilization source markets may reach when withdrawing
26
30
  * shared liquidity, scaled by WAD.
27
- * @default 92% (920000000000000000n)
31
+ *
32
+ * @default 90% (900000000000000000n)
33
+ * @deprecated The source-market withdrawal ceiling is fixed at 90%
34
+ * ({@link DEFAULT_WITHDRAWAL_TARGET_UTILIZATION}) and will stop being
35
+ * configurable in the next major. Overrides are still honored for now.
28
36
  */
29
37
  readonly defaultMaxWithdrawalUtilization?: bigint;
30
38
  }
@@ -70,12 +78,20 @@ export interface ReallocationComputeOptions extends PublicAllocatorOptions {
70
78
  * Per-market target utilization above which the shared liquidity algorithm
71
79
  * is triggered (scaled by WAD). Overrides `defaultSupplyTargetUtilization`
72
80
  * for the specified market.
81
+ *
82
+ * @deprecated The supply-target trigger is fixed at 90%
83
+ * ({@link DEFAULT_SUPPLY_TARGET_UTILIZATION}) and will stop being configurable
84
+ * in the next major. Per-market overrides are still honored for now.
73
85
  */
74
86
  readonly supplyTargetUtilization?: Readonly<Record<MarketId, bigint | undefined>>;
75
87
  /**
76
88
  * The default target utilization above which the shared liquidity algorithm
77
89
  * is triggered (scaled by WAD).
78
- * @default 90.5% (905000000000000000n)
90
+ *
91
+ * @default 90% (900000000000000000n)
92
+ * @deprecated The supply-target trigger is fixed at 90%
93
+ * ({@link DEFAULT_SUPPLY_TARGET_UTILIZATION}) and will stop being configurable
94
+ * in the next major. Overrides are still honored for now.
79
95
  */
80
96
  readonly defaultSupplyTargetUtilization?: bigint;
81
97
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "5.3.3",
4
+ "version": "5.4.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "contributors": [
7
7
  "Foulks-Plb <https://x.com/FoulkPlb>"