@morpho-org/morpho-sdk 3.0.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +69 -3
  2. package/lib/cjs/actions/marketV1/index.d.ts +2 -0
  3. package/lib/cjs/actions/marketV1/index.js +2 -0
  4. package/lib/cjs/actions/marketV1/supply.d.ts +69 -0
  5. package/lib/cjs/actions/marketV1/supply.js +128 -0
  6. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +1 -1
  7. package/lib/cjs/actions/marketV1/supplyCollateral.js +2 -2
  8. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  9. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +2 -2
  10. package/lib/cjs/actions/marketV1/withdraw.d.ts +83 -0
  11. package/lib/cjs/actions/marketV1/withdraw.js +110 -0
  12. package/lib/cjs/bundler/actions.d.ts +86 -4
  13. package/lib/cjs/bundler/actions.js +143 -8
  14. package/lib/cjs/bundler/types.d.ts +23 -4
  15. package/lib/cjs/entities/marketV1/marketV1.d.ts +121 -18
  16. package/lib/cjs/entities/marketV1/marketV1.js +144 -12
  17. package/lib/cjs/entities/reallocationData.js +3 -0
  18. package/lib/cjs/helpers/computeReallocations.d.ts +17 -6
  19. package/lib/cjs/helpers/computeReallocations.js +44 -11
  20. package/lib/cjs/helpers/index.d.ts +2 -2
  21. package/lib/cjs/helpers/index.js +6 -2
  22. package/lib/cjs/helpers/slippage.d.ts +57 -0
  23. package/lib/cjs/helpers/slippage.js +82 -0
  24. package/lib/cjs/helpers/validate.d.ts +38 -7
  25. package/lib/cjs/helpers/validate.js +54 -11
  26. package/lib/cjs/types/action.d.ts +27 -6
  27. package/lib/cjs/types/error.d.ts +68 -6
  28. package/lib/cjs/types/error.js +85 -12
  29. package/lib/cjs/utils.d.ts +1 -1
  30. package/lib/cjs/utils.js +2 -2
  31. package/lib/esm/actions/marketV1/index.d.ts +2 -0
  32. package/lib/esm/actions/marketV1/index.js +2 -0
  33. package/lib/esm/actions/marketV1/supply.d.ts +69 -0
  34. package/lib/esm/actions/marketV1/supply.js +124 -0
  35. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +1 -1
  36. package/lib/esm/actions/marketV1/supplyCollateral.js +3 -3
  37. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +1 -1
  38. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +3 -3
  39. package/lib/esm/actions/marketV1/withdraw.d.ts +83 -0
  40. package/lib/esm/actions/marketV1/withdraw.js +106 -0
  41. package/lib/esm/bundler/actions.d.ts +86 -4
  42. package/lib/esm/bundler/actions.js +143 -8
  43. package/lib/esm/bundler/types.d.ts +23 -4
  44. package/lib/esm/entities/marketV1/marketV1.d.ts +121 -18
  45. package/lib/esm/entities/marketV1/marketV1.js +147 -15
  46. package/lib/esm/entities/reallocationData.js +3 -0
  47. package/lib/esm/helpers/computeReallocations.d.ts +17 -6
  48. package/lib/esm/helpers/computeReallocations.js +45 -12
  49. package/lib/esm/helpers/index.d.ts +2 -2
  50. package/lib/esm/helpers/index.js +2 -2
  51. package/lib/esm/helpers/slippage.d.ts +57 -0
  52. package/lib/esm/helpers/slippage.js +80 -0
  53. package/lib/esm/helpers/validate.d.ts +38 -7
  54. package/lib/esm/helpers/validate.js +51 -10
  55. package/lib/esm/types/action.d.ts +27 -6
  56. package/lib/esm/types/error.d.ts +68 -6
  57. package/lib/esm/types/error.js +73 -9
  58. package/lib/esm/utils.d.ts +1 -1
  59. package/lib/esm/utils.js +1 -1
  60. package/package.json +14 -10
@@ -69,14 +69,16 @@ export declare const validatePositionHealth: (params: {
69
69
  */
70
70
  export declare const validateChainId: (clientChainId: number | undefined, expectedChainId: number) => void;
71
71
  /**
72
- * Validates that the given collateral token is the chain's wrapped native token.
73
- * Throws {@link ChainWNativeMissingError} if wNative is not configured for the chain.
74
- * Throws {@link NativeAmountOnNonWNativeCollateralError} if collateral is not wNative.
72
+ * Validates that the given asset is the chain's wrapped native token.
73
+ * Used by any action that may receive `nativeAmount` — the SDK wraps native
74
+ * into wNative, so the target asset must be wNative for the action to succeed.
75
75
  *
76
76
  * @param chainId - The chain to look up wNative on.
77
- * @param collateralToken - The market's collateral token address.
77
+ * @param asset - The asset address to check (collateral, loan, vault asset…).
78
+ * @throws {ChainWNativeMissingError} if wNative is not configured for the chain.
79
+ * @throws {NativeAmountOnNonWNativeAssetError} if the asset is not wNative.
78
80
  */
79
- export declare const validateNativeCollateral: (chainId: number, collateralToken: Address) => void;
81
+ export declare const validateNativeAsset: (chainId: number, asset: Address) => void;
80
82
  /**
81
83
  * Validates that the resulting position stays within the safe LTV threshold
82
84
  * (LLTV minus buffer) after withdrawing collateral.
@@ -144,11 +146,12 @@ export declare const validateRepayParams: (params: {
144
146
  * - `fee` must be non-negative.
145
147
  * - `withdrawals` must be non-empty.
146
148
  * - Every withdrawal `amount` must be strictly positive.
147
- * - No withdrawal may target `targetMarketId` (the borrow market).
149
+ * - No withdrawal may target `targetMarketId` (the operation's target market — the market being
150
+ * borrowed from for `borrow`, or being withdrawn from for `withdraw`).
148
151
  * - Withdrawal market IDs must be strictly ascending (required by `PublicAllocator.reallocateTo`).
149
152
  *
150
153
  * @param reallocations - The reallocations to validate.
151
- * @param targetMarketId - The ID of the market being borrowed from. No withdrawal may reference this market.
154
+ * @param targetMarketId - The ID of the operation's target market. No withdrawal may reference this market.
152
155
  */
153
156
  export declare const validateReallocations: (reallocations: readonly VaultReallocation[], targetMarketId: MarketId) => void;
154
157
  /**
@@ -160,3 +163,31 @@ export declare const validateReallocations: (reallocations: readonly VaultReallo
160
163
  * @param slippageTolerance - The slippage tolerance in WAD.
161
164
  */
162
165
  export declare const validateSlippageTolerance: (slippageTolerance: bigint) => void;
166
+ /**
167
+ * Validates that the withdraw assets do not exceed the user's supplied assets in the market.
168
+ *
169
+ * @param params - Validation parameters.
170
+ * @param params.positionData - The current accrual position.
171
+ * @param params.withdrawAssets - The amount of assets to withdraw.
172
+ * @param params.marketId - The market identifier (for error messages).
173
+ * @throws {WithdrawExceedsSupplyError} when `withdrawAssets > positionData.supplyAssets`.
174
+ */
175
+ export declare const validateWithdrawAmount: (params: {
176
+ positionData: AccrualPosition;
177
+ withdrawAssets: bigint;
178
+ marketId: MarketId;
179
+ }) => void;
180
+ /**
181
+ * Validates that the withdraw shares do not exceed the user's owned supply shares in the market.
182
+ *
183
+ * @param params - Validation parameters.
184
+ * @param params.positionData - The current accrual position.
185
+ * @param params.withdrawShares - The amount of shares to withdraw.
186
+ * @param params.marketId - The market identifier (for error messages).
187
+ * @throws {WithdrawSharesExceedSupplyError} when `withdrawShares > positionData.supplyShares`.
188
+ */
189
+ export declare const validateWithdrawShares: (params: {
190
+ positionData: AccrualPosition;
191
+ withdrawShares: bigint;
192
+ marketId: MarketId;
193
+ }) => void;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = exports.compareMarketIds = void 0;
3
+ exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeAsset = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = exports.compareMarketIds = void 0;
4
4
  exports.validateUserAddress = validateUserAddress;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
@@ -111,23 +111,25 @@ const validateChainId = (clientChainId, expectedChainId) => {
111
111
  };
112
112
  exports.validateChainId = validateChainId;
113
113
  /**
114
- * Validates that the given collateral token is the chain's wrapped native token.
115
- * Throws {@link ChainWNativeMissingError} if wNative is not configured for the chain.
116
- * Throws {@link NativeAmountOnNonWNativeCollateralError} if collateral is not wNative.
114
+ * Validates that the given asset is the chain's wrapped native token.
115
+ * Used by any action that may receive `nativeAmount` — the SDK wraps native
116
+ * into wNative, so the target asset must be wNative for the action to succeed.
117
117
  *
118
118
  * @param chainId - The chain to look up wNative on.
119
- * @param collateralToken - The market's collateral token address.
119
+ * @param asset - The asset address to check (collateral, loan, vault asset…).
120
+ * @throws {ChainWNativeMissingError} if wNative is not configured for the chain.
121
+ * @throws {NativeAmountOnNonWNativeAssetError} if the asset is not wNative.
120
122
  */
121
- const validateNativeCollateral = (chainId, collateralToken) => {
123
+ const validateNativeAsset = (chainId, asset) => {
122
124
  const { wNative } = (0, blue_sdk_1.getChainAddresses)(chainId);
123
125
  if (!(0, morpho_ts_1.isDefined)(wNative)) {
124
126
  throw new index_js_1.ChainWNativeMissingError(chainId);
125
127
  }
126
- if (!(0, viem_1.isAddressEqual)(collateralToken, wNative)) {
127
- throw new index_js_1.NativeAmountOnNonWNativeCollateralError(collateralToken, wNative);
128
+ if (!(0, viem_1.isAddressEqual)(asset, wNative)) {
129
+ throw new index_js_1.NativeAmountOnNonWNativeAssetError(asset, wNative);
128
130
  }
129
131
  };
130
- exports.validateNativeCollateral = validateNativeCollateral;
132
+ exports.validateNativeAsset = validateNativeAsset;
131
133
  /**
132
134
  * Validates that the resulting position stays within the safe LTV threshold
133
135
  * (LLTV minus buffer) after withdrawing collateral.
@@ -253,11 +255,12 @@ exports.validateRepayParams = validateRepayParams;
253
255
  * - `fee` must be non-negative.
254
256
  * - `withdrawals` must be non-empty.
255
257
  * - Every withdrawal `amount` must be strictly positive.
256
- * - No withdrawal may target `targetMarketId` (the borrow market).
258
+ * - No withdrawal may target `targetMarketId` (the operation's target market — the market being
259
+ * borrowed from for `borrow`, or being withdrawn from for `withdraw`).
257
260
  * - Withdrawal market IDs must be strictly ascending (required by `PublicAllocator.reallocateTo`).
258
261
  *
259
262
  * @param reallocations - The reallocations to validate.
260
- * @param targetMarketId - The ID of the market being borrowed from. No withdrawal may reference this market.
263
+ * @param targetMarketId - The ID of the operation's target market. No withdrawal may reference this market.
261
264
  */
262
265
  const validateReallocations = (reallocations, targetMarketId) => {
263
266
  for (const r of reallocations) {
@@ -301,3 +304,43 @@ const validateSlippageTolerance = (slippageTolerance) => {
301
304
  }
302
305
  };
303
306
  exports.validateSlippageTolerance = validateSlippageTolerance;
307
+ /**
308
+ * Validates that the withdraw assets do not exceed the user's supplied assets in the market.
309
+ *
310
+ * @param params - Validation parameters.
311
+ * @param params.positionData - The current accrual position.
312
+ * @param params.withdrawAssets - The amount of assets to withdraw.
313
+ * @param params.marketId - The market identifier (for error messages).
314
+ * @throws {WithdrawExceedsSupplyError} when `withdrawAssets > positionData.supplyAssets`.
315
+ */
316
+ const validateWithdrawAmount = (params) => {
317
+ const { positionData, withdrawAssets, marketId } = params;
318
+ if (withdrawAssets > positionData.supplyAssets) {
319
+ throw new index_js_1.WithdrawExceedsSupplyError({
320
+ withdrawAmount: withdrawAssets,
321
+ available: positionData.supplyAssets,
322
+ market: marketId,
323
+ });
324
+ }
325
+ };
326
+ exports.validateWithdrawAmount = validateWithdrawAmount;
327
+ /**
328
+ * Validates that the withdraw shares do not exceed the user's owned supply shares in the market.
329
+ *
330
+ * @param params - Validation parameters.
331
+ * @param params.positionData - The current accrual position.
332
+ * @param params.withdrawShares - The amount of shares to withdraw.
333
+ * @param params.marketId - The market identifier (for error messages).
334
+ * @throws {WithdrawSharesExceedSupplyError} when `withdrawShares > positionData.supplyShares`.
335
+ */
336
+ const validateWithdrawShares = (params) => {
337
+ const { positionData, withdrawShares, marketId } = params;
338
+ if (withdrawShares > positionData.supplyShares) {
339
+ throw new index_js_1.WithdrawSharesExceedSupplyError({
340
+ withdrawShares,
341
+ supplyShares: positionData.supplyShares,
342
+ market: marketId,
343
+ });
344
+ }
345
+ };
346
+ exports.validateWithdrawShares = validateWithdrawShares;
@@ -81,6 +81,23 @@ export interface VaultV1MigrateToV2Action extends BaseAction<"vaultV1MigrateToV2
81
81
  recipient: Address;
82
82
  }> {
83
83
  }
84
+ export interface MarketV1SupplyAction extends BaseAction<"marketV1Supply", {
85
+ market: Hex;
86
+ amount: bigint;
87
+ onBehalf: Address;
88
+ maxSharePrice: bigint;
89
+ nativeAmount?: bigint;
90
+ }> {
91
+ }
92
+ export interface MarketV1WithdrawAction extends BaseAction<"marketV1Withdraw", {
93
+ market: Hex;
94
+ assets: bigint;
95
+ shares: bigint;
96
+ receiver: Address;
97
+ minSharePrice: bigint;
98
+ reallocationFee: bigint;
99
+ }> {
100
+ }
84
101
  export interface MarketV1SupplyCollateralAction extends BaseAction<"marketV1SupplyCollateral", {
85
102
  market: Hex;
86
103
  amount: bigint;
@@ -136,23 +153,27 @@ export interface MarketV1RepayWithdrawCollateralAction extends BaseAction<"marke
136
153
  }> {
137
154
  }
138
155
  /**
139
- * Enforces that exactly one repay amount source is provided.
156
+ * Enforces that exactly one of `assets` / `shares` is provided.
157
+ *
158
+ * - `assets`: operate on an exact asset amount.
159
+ * - `shares`: operate on an exact share count (typical for full position closes,
160
+ * immune to interest accrual between tx construction and execution).
140
161
  *
141
- * - `assets`: partial repay by exact asset amount.
142
- * - `shares`: full repay by exact share count (guarantees full debt repayment
143
- * regardless of interest accrued between tx construction and execution).
162
+ * Used by repay (asserts on borrow side) and withdraw (asserts on supply side).
144
163
  */
145
- export type RepayAmountArgs = {
164
+ export type AssetsOrSharesArgs = {
146
165
  assets: bigint;
147
166
  } | {
148
167
  shares: bigint;
149
168
  };
169
+ /** @deprecated Use {@link AssetsOrSharesArgs}. Kept as an alias for back-compat. */
170
+ export type RepayAmountArgs = AssetsOrSharesArgs;
150
171
  export interface MorphoAuthorizationAction extends BaseAction<"morphoAuthorization", {
151
172
  authorized: Address;
152
173
  isAuthorized: boolean;
153
174
  }> {
154
175
  }
155
- export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1MigrateToV2Action | MarketV1SupplyCollateralAction | MarketV1BorrowAction | MarketV1SupplyCollateralBorrowAction | MarketV1RepayAction | MarketV1WithdrawCollateralAction | MarketV1RepayWithdrawCollateralAction | MorphoAuthorizationAction;
176
+ export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1MigrateToV2Action | MarketV1SupplyAction | MarketV1WithdrawAction | MarketV1SupplyCollateralAction | MarketV1BorrowAction | MarketV1SupplyCollateralBorrowAction | MarketV1RepayAction | MarketV1WithdrawCollateralAction | MarketV1RepayWithdrawCollateralAction | MorphoAuthorizationAction;
156
177
  export interface Transaction<TAction extends BaseAction = TransactionAction> {
157
178
  readonly to: Address;
158
179
  readonly value: bigint;
@@ -128,10 +128,13 @@ export declare class NonPositiveBorrowAmountError extends Error {
128
128
  export declare class ZeroCollateralAmountError extends Error {
129
129
  constructor(market: string);
130
130
  }
131
- /** Thrown when a collateral supply uses `nativeAmount` but the collateral token is not the chain's wNative. */
132
- export declare class NativeAmountOnNonWNativeCollateralError extends Error {
133
- constructor(collateralToken: Address, wNative: Address);
131
+ /** Thrown when an action uses `nativeAmount` but the target asset is not the chain's wNative. */
132
+ export declare class NativeAmountOnNonWNativeAssetError extends Error {
133
+ constructor(asset: Address, wNative: Address);
134
134
  }
135
+ /** @deprecated Use {@link NativeAmountOnNonWNativeAssetError}. */
136
+ export declare const NativeAmountOnNonWNativeCollateralError: typeof NativeAmountOnNonWNativeAssetError;
137
+ export type NativeAmountOnNonWNativeCollateralError = NativeAmountOnNonWNativeAssetError;
135
138
  /** Thrown when a borrow exceeds the LLTV-buffered safe maximum for the position. */
136
139
  export declare class BorrowExceedsSafeLtvError extends Error {
137
140
  constructor(borrowAmount: bigint, maxSafeBorrow: bigint);
@@ -160,7 +163,7 @@ export declare class EmptyReallocationWithdrawalsError extends Error {
160
163
  export declare class NonPositiveReallocationAmountError extends Error {
161
164
  constructor(vault: string, market: string);
162
165
  }
163
- /** Thrown when a reallocation withdrawal references the borrow target market (which would be a no-op or self-deal). */
166
+ /** Thrown when a reallocation withdrawal references the operation's target market (which would be a no-op or self-deal). */
164
167
  export declare class ReallocationWithdrawalOnTargetMarketError extends Error {
165
168
  constructor(vault: string, marketId: string);
166
169
  }
@@ -248,8 +251,8 @@ export declare class DisabledReallocationMarketError extends Error {
248
251
  }
249
252
  /**
250
253
  * Thrown when shared liquidity selected by `computeReallocations` cannot cover
251
- * the absolute borrow shortfall on the target market — the resulting
252
- * `morphoBorrow` would still revert onchain.
254
+ * the operation's absolute shortfall on the target market — the resulting
255
+ * `morphoBorrow` or `morphoWithdraw` would still revert onchain.
253
256
  *
254
257
  * Pattern-match on the class and inspect `params` to surface the gap to users.
255
258
  */
@@ -305,6 +308,65 @@ export declare class UnknownReallocationPositionError extends UnknownDataError {
305
308
  export declare class NonPositiveMinBorrowSharePriceError extends Error {
306
309
  constructor(market: string);
307
310
  }
311
+ /** Thrown when a market loan-asset supply amount is negative. */
312
+ export declare class NegativeSupplyAmountError extends Error {
313
+ constructor(market: string);
314
+ }
315
+ /** Thrown when a market loan-asset supply's `maxSharePrice` slippage bound is negative. */
316
+ export declare class NegativeSupplyMaxSharePriceError extends Error {
317
+ constructor(market: string);
318
+ }
319
+ /** Thrown when both `amount` and `nativeAmount` resolve to zero on a market loan-asset supply. */
320
+ export declare class ZeroSupplyAmountError extends Error {
321
+ constructor(market: string);
322
+ }
323
+ /** Thrown when a market loan-asset withdraw has both `assets` and `shares` zero, or either negative. */
324
+ export declare class NonPositiveWithdrawAmountError extends Error {
325
+ constructor(market: string);
326
+ }
327
+ /** Thrown when a market loan-asset withdraw's `minSharePrice` slippage bound is negative. */
328
+ export declare class NegativeWithdrawMinSharePriceError extends Error {
329
+ constructor(market: string);
330
+ }
331
+ /** Thrown when a loan-asset withdraw specifies both `assets` and `shares` as non-zero (modes are mutually exclusive). */
332
+ export declare class MutuallyExclusiveWithdrawAmountsError extends Error {
333
+ constructor(market: string);
334
+ }
335
+ /** Thrown when a loan-asset withdraw in assets mode exceeds the user's supplied assets in the market. */
336
+ export declare class WithdrawExceedsSupplyError extends Error {
337
+ constructor(params: {
338
+ withdrawAmount: bigint;
339
+ available: bigint;
340
+ market: string;
341
+ });
342
+ }
343
+ /** Thrown when a loan-asset withdraw in shares mode exceeds the user's owned supply shares in the market. */
344
+ export declare class WithdrawSharesExceedSupplyError extends Error {
345
+ constructor(params: {
346
+ withdrawShares: bigint;
347
+ supplyShares: bigint;
348
+ market: string;
349
+ });
350
+ }
351
+ /**
352
+ * Thrown when `computeReallocations` is called with a withdraw `amount` greater
353
+ * than the target market's current `totalSupplyAssets` — the post-withdraw
354
+ * supply would be negative, making the on-chain `morphoWithdraw` revert
355
+ * regardless of any reallocation. Caught here so callers do not pay
356
+ * PublicAllocator fees on an unreachable operation.
357
+ */
358
+ export declare class ReallocationWithdrawExceedsMarketSupplyError extends Error {
359
+ readonly params: {
360
+ readonly marketId: MarketId;
361
+ readonly withdrawAmount: bigint;
362
+ readonly totalSupplyAssets: bigint;
363
+ };
364
+ constructor(params: {
365
+ readonly marketId: MarketId;
366
+ readonly withdrawAmount: bigint;
367
+ readonly totalSupplyAssets: bigint;
368
+ });
369
+ }
308
370
  /** Thrown when a vault migration's source vault asset differs from the target vault asset. */
309
371
  export declare class VaultAssetMismatchError extends Error {
310
372
  constructor(sourceAsset: Address, targetAsset: Address);
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnknownReallocationVaultMarketConfigError = exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.DisabledReallocationMarketError = exports.MissingPublicAllocatorConfigError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.ShareDivideByZeroError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.NonPositiveWithdrawCollateralAmountError = exports.NonPositiveRepayMaxSharePriceError = exports.NonPositiveRepayAmountError = exports.MutuallyExclusiveRepayAmountsError = exports.TransferAmountNotEqualToAssetsError = exports.NonPositiveTransferAmountError = exports.UnsortedReallocationWithdrawalsError = exports.ReallocationWithdrawalOnTargetMarketError = exports.NonPositiveReallocationAmountError = exports.EmptyReallocationWithdrawalsError = exports.NegativeReallocationFeeError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeCollateralError = exports.ZeroCollateralAmountError = exports.NonPositiveBorrowAmountError = exports.VaultAddressMismatchError = exports.ZeroDepositAmountError = exports.NegativeNativeAmountError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.Permit2ExpirationMissingError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.NegativeSlippageToleranceError = exports.ApprovalAmountLessThanSpendAmountError = exports.MissingClientPropertyError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.NonPositiveMaxSharePriceError = exports.NonPositiveSharesAmountError = exports.NonPositiveAssetAmountError = exports.BundlerErrors = void 0;
4
- exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.NonPositiveMinBorrowSharePriceError = exports.UnknownReallocationPositionError = void 0;
3
+ exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.DisabledReallocationMarketError = exports.MissingPublicAllocatorConfigError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.ShareDivideByZeroError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.NonPositiveWithdrawCollateralAmountError = exports.NonPositiveRepayMaxSharePriceError = exports.NonPositiveRepayAmountError = exports.MutuallyExclusiveRepayAmountsError = exports.TransferAmountNotEqualToAssetsError = exports.NonPositiveTransferAmountError = exports.UnsortedReallocationWithdrawalsError = exports.ReallocationWithdrawalOnTargetMarketError = exports.NonPositiveReallocationAmountError = exports.EmptyReallocationWithdrawalsError = exports.NegativeReallocationFeeError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeCollateralError = exports.NativeAmountOnNonWNativeAssetError = exports.ZeroCollateralAmountError = exports.NonPositiveBorrowAmountError = exports.VaultAddressMismatchError = exports.ZeroDepositAmountError = exports.NegativeNativeAmountError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.Permit2ExpirationMissingError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.NegativeSlippageToleranceError = exports.ApprovalAmountLessThanSpendAmountError = exports.MissingClientPropertyError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.NonPositiveMaxSharePriceError = exports.NonPositiveSharesAmountError = exports.NonPositiveAssetAmountError = exports.BundlerErrors = void 0;
4
+ exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.NegativeWithdrawMinSharePriceError = exports.NonPositiveWithdrawAmountError = exports.ZeroSupplyAmountError = exports.NegativeSupplyMaxSharePriceError = exports.NegativeSupplyAmountError = exports.NonPositiveMinBorrowSharePriceError = exports.UnknownReallocationPositionError = exports.UnknownReallocationVaultMarketConfigError = void 0;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  /**
7
7
  * Typed errors thrown while encoding supported Bundler3 actions.
@@ -201,13 +201,15 @@ class ZeroCollateralAmountError extends Error {
201
201
  }
202
202
  }
203
203
  exports.ZeroCollateralAmountError = ZeroCollateralAmountError;
204
- /** Thrown when a collateral supply uses `nativeAmount` but the collateral token is not the chain's wNative. */
205
- class NativeAmountOnNonWNativeCollateralError extends Error {
206
- constructor(collateralToken, wNative) {
207
- super(`Cannot use nativeAmount: collateral token ${collateralToken} is not the wrapped native token ${wNative}`);
204
+ /** Thrown when an action uses `nativeAmount` but the target asset is not the chain's wNative. */
205
+ class NativeAmountOnNonWNativeAssetError extends Error {
206
+ constructor(asset, wNative) {
207
+ super(`Cannot use nativeAmount: asset ${asset} is not the wrapped native token ${wNative}`);
208
208
  }
209
209
  }
210
- exports.NativeAmountOnNonWNativeCollateralError = NativeAmountOnNonWNativeCollateralError;
210
+ exports.NativeAmountOnNonWNativeAssetError = NativeAmountOnNonWNativeAssetError;
211
+ /** @deprecated Use {@link NativeAmountOnNonWNativeAssetError}. */
212
+ exports.NativeAmountOnNonWNativeCollateralError = NativeAmountOnNonWNativeAssetError;
211
213
  /** Thrown when a borrow exceeds the LLTV-buffered safe maximum for the position. */
212
214
  class BorrowExceedsSafeLtvError extends Error {
213
215
  constructor(borrowAmount, maxSafeBorrow) {
@@ -257,10 +259,10 @@ class NonPositiveReallocationAmountError extends Error {
257
259
  }
258
260
  }
259
261
  exports.NonPositiveReallocationAmountError = NonPositiveReallocationAmountError;
260
- /** Thrown when a reallocation withdrawal references the borrow target market (which would be a no-op or self-deal). */
262
+ /** Thrown when a reallocation withdrawal references the operation's target market (which would be a no-op or self-deal). */
261
263
  class ReallocationWithdrawalOnTargetMarketError extends Error {
262
264
  constructor(vault, marketId) {
263
- super(`Reallocation withdrawal cannot include the borrow target market ${marketId} for vault ${vault}.`);
265
+ super(`Reallocation withdrawal cannot include the target market ${marketId} for vault ${vault}.`);
264
266
  }
265
267
  }
266
268
  exports.ReallocationWithdrawalOnTargetMarketError = ReallocationWithdrawalOnTargetMarketError;
@@ -375,15 +377,15 @@ class DisabledReallocationMarketError extends Error {
375
377
  exports.DisabledReallocationMarketError = DisabledReallocationMarketError;
376
378
  /**
377
379
  * Thrown when shared liquidity selected by `computeReallocations` cannot cover
378
- * the absolute borrow shortfall on the target market — the resulting
379
- * `morphoBorrow` would still revert onchain.
380
+ * the operation's absolute shortfall on the target market — the resulting
381
+ * `morphoBorrow` or `morphoWithdraw` would still revert onchain.
380
382
  *
381
383
  * Pattern-match on the class and inspect `params` to surface the gap to users.
382
384
  */
383
385
  class InsufficientSharedLiquidityError extends Error {
384
386
  params;
385
387
  constructor(params) {
386
- super(`Shared liquidity is insufficient to cover the borrow on market ${params.marketId}: shortfall "${params.shortfall}", available "${params.available}". Reduce the borrow amount or wait for additional vault liquidity.`);
388
+ super(`Shared liquidity is insufficient on market ${params.marketId}: shortfall "${params.shortfall}", available "${params.available}". Reduce the operation amount or wait for additional vault liquidity.`);
387
389
  this.params = params;
388
390
  }
389
391
  }
@@ -449,6 +451,77 @@ class NonPositiveMinBorrowSharePriceError extends Error {
449
451
  }
450
452
  }
451
453
  exports.NonPositiveMinBorrowSharePriceError = NonPositiveMinBorrowSharePriceError;
454
+ /** Thrown when a market loan-asset supply amount is negative. */
455
+ class NegativeSupplyAmountError extends Error {
456
+ constructor(market) {
457
+ super(`Supply amount must be non-negative for market: ${market}`);
458
+ }
459
+ }
460
+ exports.NegativeSupplyAmountError = NegativeSupplyAmountError;
461
+ /** Thrown when a market loan-asset supply's `maxSharePrice` slippage bound is negative. */
462
+ class NegativeSupplyMaxSharePriceError extends Error {
463
+ constructor(market) {
464
+ super(`Max share price must be non-negative for market: ${market}`);
465
+ }
466
+ }
467
+ exports.NegativeSupplyMaxSharePriceError = NegativeSupplyMaxSharePriceError;
468
+ /** Thrown when both `amount` and `nativeAmount` resolve to zero on a market loan-asset supply. */
469
+ class ZeroSupplyAmountError extends Error {
470
+ constructor(market) {
471
+ super(`Total supply amount must be positive for market: ${market}. Both amount and nativeAmount are zero.`);
472
+ }
473
+ }
474
+ exports.ZeroSupplyAmountError = ZeroSupplyAmountError;
475
+ /** Thrown when a market loan-asset withdraw has both `assets` and `shares` zero, or either negative. */
476
+ class NonPositiveWithdrawAmountError extends Error {
477
+ constructor(market) {
478
+ super(`Withdraw amount must be positive for market: ${market}`);
479
+ }
480
+ }
481
+ exports.NonPositiveWithdrawAmountError = NonPositiveWithdrawAmountError;
482
+ /** Thrown when a market loan-asset withdraw's `minSharePrice` slippage bound is negative. */
483
+ class NegativeWithdrawMinSharePriceError extends Error {
484
+ constructor(market) {
485
+ super(`Min share price must be non-negative for market: ${market}`);
486
+ }
487
+ }
488
+ exports.NegativeWithdrawMinSharePriceError = NegativeWithdrawMinSharePriceError;
489
+ /** Thrown when a loan-asset withdraw specifies both `assets` and `shares` as non-zero (modes are mutually exclusive). */
490
+ class MutuallyExclusiveWithdrawAmountsError extends Error {
491
+ constructor(market) {
492
+ super(`Exactly one of assets or shares must be non-zero for market: ${market}. Both were provided.`);
493
+ }
494
+ }
495
+ exports.MutuallyExclusiveWithdrawAmountsError = MutuallyExclusiveWithdrawAmountsError;
496
+ /** Thrown when a loan-asset withdraw in assets mode exceeds the user's supplied assets in the market. */
497
+ class WithdrawExceedsSupplyError extends Error {
498
+ constructor(params) {
499
+ super(`Withdraw amount ${params.withdrawAmount} exceeds available supply ${params.available} for market: ${params.market}. Reduce withdraw amount.`);
500
+ }
501
+ }
502
+ exports.WithdrawExceedsSupplyError = WithdrawExceedsSupplyError;
503
+ /** Thrown when a loan-asset withdraw in shares mode exceeds the user's owned supply shares in the market. */
504
+ class WithdrawSharesExceedSupplyError extends Error {
505
+ constructor(params) {
506
+ super(`Withdraw shares ${params.withdrawShares} exceed owned supply shares ${params.supplyShares} for market: ${params.market}. Reduce withdraw shares.`);
507
+ }
508
+ }
509
+ exports.WithdrawSharesExceedSupplyError = WithdrawSharesExceedSupplyError;
510
+ /**
511
+ * Thrown when `computeReallocations` is called with a withdraw `amount` greater
512
+ * than the target market's current `totalSupplyAssets` — the post-withdraw
513
+ * supply would be negative, making the on-chain `morphoWithdraw` revert
514
+ * regardless of any reallocation. Caught here so callers do not pay
515
+ * PublicAllocator fees on an unreachable operation.
516
+ */
517
+ class ReallocationWithdrawExceedsMarketSupplyError extends Error {
518
+ params;
519
+ constructor(params) {
520
+ super(`Withdraw amount "${params.withdrawAmount}" exceeds market total supply "${params.totalSupplyAssets}" on market ${params.marketId}. Reduce the withdraw amount.`);
521
+ this.params = params;
522
+ }
523
+ }
524
+ exports.ReallocationWithdrawExceedsMarketSupplyError = ReallocationWithdrawExceedsMarketSupplyError;
452
525
  /** Thrown when a vault migration's source vault asset differs from the target vault asset. */
453
526
  class VaultAssetMismatchError extends Error {
454
527
  constructor(sourceAsset, targetAsset) {
@@ -6,4 +6,4 @@ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries,
6
6
  export { computeReallocations } from "./helpers/computeReallocations.js";
7
7
  export { addTransactionMetadata } from "./helpers/metadata.js";
8
8
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./helpers/slippage.js";
9
- export { validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
9
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
package/lib/cjs/utils.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeCollateral = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = exports.values = exports.transformValue = exports.Time = exports.retryPromiseLinearBackoff = exports.mergeEntries = exports.keys = exports.isNotUndefined = exports.isNotNull = exports.isDefined = exports.hasValue = exports.getValue = exports.getSubdomainBaseUrl = exports.getLastDefined = exports.getLast = exports.fromEntries = exports.filterDefined = exports.entries = exports.deepFreeze = exports.createHasValue = exports.createGetValue = exports.bigIntComparator = exports.safeParseUnits = exports.safeParseNumber = exports.safeGetAddress = exports.restructure = exports.readContractRestructured = exports.optionalBoolean = exports.getPermitTypedData = exports.getPermit2TransferFromTypedData = exports.getPermit2PermitTypedData = exports.getDaiPermitTypedData = exports.getAuthorizationTypedData = exports.decodeBytes32String = exports.VaultUtils = exports.SharesMath = exports.MathLib = exports.MarketUtils = exports.CapacityLimitReason = exports.AdaptiveCurveIrmLib = void 0;
3
+ exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = exports.values = exports.transformValue = exports.Time = exports.retryPromiseLinearBackoff = exports.mergeEntries = exports.keys = exports.isNotUndefined = exports.isNotNull = exports.isDefined = exports.hasValue = exports.getValue = exports.getSubdomainBaseUrl = exports.getLastDefined = exports.getLast = exports.fromEntries = exports.filterDefined = exports.entries = exports.deepFreeze = exports.createHasValue = exports.createGetValue = exports.bigIntComparator = exports.safeParseUnits = exports.safeParseNumber = exports.safeGetAddress = exports.restructure = exports.readContractRestructured = exports.optionalBoolean = exports.getPermitTypedData = exports.getPermit2TransferFromTypedData = exports.getPermit2PermitTypedData = exports.getDaiPermitTypedData = exports.getAuthorizationTypedData = exports.decodeBytes32String = exports.VaultUtils = exports.SharesMath = exports.MathLib = exports.MarketUtils = exports.CapacityLimitReason = exports.AdaptiveCurveIrmLib = void 0;
4
4
  exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayParams = void 0;
5
5
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  Object.defineProperty(exports, "AdaptiveCurveIrmLib", { enumerable: true, get: function () { return blue_sdk_1.AdaptiveCurveIrmLib; } });
@@ -54,7 +54,7 @@ Object.defineProperty(exports, "computeMinBorrowSharePrice", { enumerable: true,
54
54
  var validate_js_1 = require("./helpers/validate.js");
55
55
  Object.defineProperty(exports, "validateAccrualPosition", { enumerable: true, get: function () { return validate_js_1.validateAccrualPosition; } });
56
56
  Object.defineProperty(exports, "validateChainId", { enumerable: true, get: function () { return validate_js_1.validateChainId; } });
57
- Object.defineProperty(exports, "validateNativeCollateral", { enumerable: true, get: function () { return validate_js_1.validateNativeCollateral; } });
57
+ Object.defineProperty(exports, "validateNativeAsset", { enumerable: true, get: function () { return validate_js_1.validateNativeAsset; } });
58
58
  Object.defineProperty(exports, "validatePositionHealth", { enumerable: true, get: function () { return validate_js_1.validatePositionHealth; } });
59
59
  Object.defineProperty(exports, "validatePositionHealthAfterWithdraw", { enumerable: true, get: function () { return validate_js_1.validatePositionHealthAfterWithdraw; } });
60
60
  Object.defineProperty(exports, "validateReallocations", { enumerable: true, get: function () { return validate_js_1.validateReallocations; } });
@@ -1,6 +1,8 @@
1
1
  export * from "./borrow.js";
2
2
  export * from "./repay.js";
3
3
  export * from "./repayWithdrawCollateral.js";
4
+ export * from "./supply.js";
4
5
  export * from "./supplyCollateral.js";
5
6
  export * from "./supplyCollateralBorrow.js";
7
+ export * from "./withdraw.js";
6
8
  export * from "./withdrawCollateral.js";
@@ -1,6 +1,8 @@
1
1
  export * from "./borrow.js";
2
2
  export * from "./repay.js";
3
3
  export * from "./repayWithdrawCollateral.js";
4
+ export * from "./supply.js";
4
5
  export * from "./supplyCollateral.js";
5
6
  export * from "./supplyCollateralBorrow.js";
7
+ export * from "./withdraw.js";
6
8
  export * from "./withdrawCollateral.js";
@@ -0,0 +1,69 @@
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
+ import type { Address } from "viem";
3
+ import { type DepositAmountArgs, type MarketV1SupplyAction, type Metadata, type RequirementSignature, type Transaction } from "../../types/index.js";
4
+ /** Parameters for {@link marketV1Supply}. */
5
+ export interface MarketV1SupplyParams {
6
+ market: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ args: DepositAmountArgs & {
11
+ onBehalf: Address;
12
+ /** Maximum supply share price (in ray). Slippage protection against inflation attacks. */
13
+ maxSharePrice: bigint;
14
+ requirementSignature?: RequirementSignature;
15
+ };
16
+ metadata?: Metadata;
17
+ }
18
+ /**
19
+ * Prepares a loan-asset supply transaction for a Morpho Blue market.
20
+ *
21
+ * Routed through bundler3 via `GeneralAdapter1`. When `nativeAmount > 0`, native ETH is wrapped
22
+ * via `GeneralAdapter1.wrapNative()` before the supply; the loan token must be the chain's
23
+ * wNative for that path. Uses `maxSharePrice` to protect against share-price inflation between
24
+ * transaction construction and execution.
25
+ *
26
+ * Zero loss: all supplied assets reach Morpho. No dust left in bundler or adapter.
27
+ *
28
+ * @param params.market.chainId - The chain the market lives on.
29
+ * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
30
+ * @param params.args.amount - Amount of ERC-20 loan asset to supply. At least one of `amount` or
31
+ * `nativeAmount` must be positive. Defaults to `0n`.
32
+ * @param params.args.onBehalf - Address whose Morpho supply position is credited.
33
+ * @param params.args.maxSharePrice - Maximum acceptable supply share price (in ray). Slippage
34
+ * protection.
35
+ * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
36
+ * supply. Requires the loan token to be the chain's wNative.
37
+ * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval. When
38
+ * absent, the bundle uses a plain `erc20TransferFrom` and assumes the user has already
39
+ * approved `GeneralAdapter1`.
40
+ * @param params.metadata - Optional analytics metadata attached to the bundle.
41
+ * @returns A deep-frozen `Transaction<MarketV1SupplyAction>` with `to`, `value`, `data`, and the
42
+ * typed `action` discriminator the simulation layer consumes.
43
+ * @throws {NegativeSupplyAmountError} when `amount < 0n`.
44
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
45
+ * @throws {ZeroSupplyAmountError} when both `amount` and `nativeAmount` resolve to zero.
46
+ * @throws {NegativeSupplyMaxSharePriceError} when `maxSharePrice < 0n`.
47
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
48
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
49
+ * the chain's wNative.
50
+ * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
51
+ * is provided and the signed asset differs from `marketParams.loanToken`.
52
+ * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
53
+ * is provided and the signed amount differs from `args.amount`.
54
+ * @example
55
+ * ```ts
56
+ * import { marketV1Supply } from "@morpho-org/morpho-sdk";
57
+ *
58
+ * const tx = marketV1Supply({
59
+ * market: { chainId: 1, marketParams },
60
+ * args: {
61
+ * amount: 1_000_000_000n,
62
+ * onBehalf: supplier,
63
+ * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
64
+ * },
65
+ * });
66
+ * // tx satisfies Readonly<Transaction<MarketV1SupplyAction>>
67
+ * ```
68
+ */
69
+ export declare const marketV1Supply: ({ market: { chainId, marketParams }, args: { amount, onBehalf, maxSharePrice, requirementSignature, nativeAmount, }, metadata, }: MarketV1SupplyParams) => Readonly<Transaction<MarketV1SupplyAction>>;