@morpho-org/morpho-sdk 5.5.0 → 5.6.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 (90) hide show
  1. package/README.md +8 -6
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +3 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +21 -15
  5. package/lib/cjs/actions/blue/borrow.js +25 -18
  6. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +1 -1
  7. package/lib/cjs/actions/blue/buildAssetFundingActions.js +1 -1
  8. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +62 -19
  9. package/lib/cjs/actions/blue/buildReallocationActions.js +123 -27
  10. package/lib/cjs/actions/blue/refinance.d.ts +14 -7
  11. package/lib/cjs/actions/blue/refinance.js +18 -10
  12. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  13. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +39 -23
  14. package/lib/cjs/actions/blue/withdraw.d.ts +20 -13
  15. package/lib/cjs/actions/blue/withdraw.js +23 -18
  16. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -1
  17. package/lib/cjs/bundler/actions.d.ts +117 -0
  18. package/lib/cjs/bundler/actions.js +211 -4
  19. package/lib/cjs/bundler/types.d.ts +20 -0
  20. package/lib/cjs/constants.d.ts +1 -1
  21. package/lib/cjs/constants.js +3 -1
  22. package/lib/cjs/entities/blue/blue.d.ts +360 -71
  23. package/lib/cjs/entities/blue/blue.js +285 -52
  24. package/lib/cjs/entities/index.d.ts +2 -1
  25. package/lib/cjs/entities/index.js +6 -3
  26. package/lib/cjs/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +40 -15
  27. package/lib/cjs/entities/{reallocationData.js → vaultV1ReallocationData.js} +29 -16
  28. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +1 -1
  29. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -1
  30. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +511 -0
  31. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1311 -0
  32. package/lib/{esm/helpers/computeReallocations.d.ts → cjs/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  33. package/lib/cjs/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +27 -13
  34. package/lib/cjs/helpers/constant.d.ts +5 -3
  35. package/lib/cjs/helpers/constant.js +6 -4
  36. package/lib/cjs/helpers/index.d.ts +2 -2
  37. package/lib/cjs/helpers/index.js +6 -3
  38. package/lib/cjs/helpers/validate.d.ts +30 -14
  39. package/lib/cjs/helpers/validate.js +140 -27
  40. package/lib/cjs/types/action.d.ts +12 -0
  41. package/lib/cjs/types/error.d.ts +224 -5
  42. package/lib/cjs/types/error.js +269 -7
  43. package/lib/cjs/types/sharedLiquidity.d.ts +72 -8
  44. package/lib/cjs/utils.d.ts +2 -2
  45. package/lib/cjs/utils.js +6 -4
  46. package/lib/esm/abis.d.ts +1 -1
  47. package/lib/esm/abis.js +1 -1
  48. package/lib/esm/actions/blue/borrow.d.ts +21 -15
  49. package/lib/esm/actions/blue/borrow.js +26 -19
  50. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +1 -1
  51. package/lib/esm/actions/blue/buildAssetFundingActions.js +1 -1
  52. package/lib/esm/actions/blue/buildReallocationActions.d.ts +62 -19
  53. package/lib/esm/actions/blue/buildReallocationActions.js +119 -25
  54. package/lib/esm/actions/blue/refinance.d.ts +14 -7
  55. package/lib/esm/actions/blue/refinance.js +19 -11
  56. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  57. package/lib/esm/actions/blue/supplyCollateralBorrow.js +40 -24
  58. package/lib/esm/actions/blue/withdraw.d.ts +20 -13
  59. package/lib/esm/actions/blue/withdraw.js +24 -19
  60. package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -1
  61. package/lib/esm/bundler/actions.d.ts +117 -0
  62. package/lib/esm/bundler/actions.js +214 -7
  63. package/lib/esm/bundler/types.d.ts +20 -0
  64. package/lib/esm/constants.d.ts +1 -1
  65. package/lib/esm/constants.js +1 -1
  66. package/lib/esm/entities/blue/blue.d.ts +360 -71
  67. package/lib/esm/entities/blue/blue.js +288 -55
  68. package/lib/esm/entities/index.d.ts +2 -1
  69. package/lib/esm/entities/index.js +2 -1
  70. package/lib/esm/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +40 -15
  71. package/lib/esm/entities/{reallocationData.js → vaultV1ReallocationData.js} +32 -14
  72. package/lib/esm/entities/vaultV2/vaultV2.d.ts +1 -1
  73. package/lib/esm/entities/vaultV2/vaultV2.js +1 -1
  74. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +511 -0
  75. package/lib/esm/entities/vaultV2BlueReallocationData.js +1307 -0
  76. package/lib/{cjs/helpers/computeReallocations.d.ts → esm/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  77. package/lib/esm/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +25 -11
  78. package/lib/esm/helpers/constant.d.ts +5 -3
  79. package/lib/esm/helpers/constant.js +5 -3
  80. package/lib/esm/helpers/index.d.ts +2 -2
  81. package/lib/esm/helpers/index.js +2 -2
  82. package/lib/esm/helpers/validate.d.ts +30 -14
  83. package/lib/esm/helpers/validate.js +141 -30
  84. package/lib/esm/types/action.d.ts +12 -0
  85. package/lib/esm/types/error.d.ts +224 -5
  86. package/lib/esm/types/error.js +253 -4
  87. package/lib/esm/types/sharedLiquidity.d.ts +72 -8
  88. package/lib/esm/utils.d.ts +2 -2
  89. package/lib/esm/utils.js +2 -2
  90. package/package.json +5 -5
@@ -1,6 +1,6 @@
1
1
  import { type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueRefinanceAction, type Metadata, type Transaction, type VaultReallocation } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueReallocationPlan, type BlueRefinanceAction, type Metadata, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRefinance}. */
5
5
  export interface BlueRefinanceParams {
6
6
  source: {
@@ -27,8 +27,8 @@ export interface BlueRefinanceParams {
27
27
  minBorrowSharePrice: bigint;
28
28
  /** Maximum repay share price on the source market (in ray); must be > 0 when a repay leg exists. */
29
29
  maxRepaySharePrice: bigint;
30
- /** PublicAllocator reallocations into the target market, run before the bundle. Fees add to `tx.value`. */
31
- targetReallocations?: readonly VaultReallocation[];
30
+ /** Homogeneous Vault V1 or Vault V2 reallocations into the target market. */
31
+ targetReallocations?: BlueReallocationPlan;
32
32
  /**
33
33
  * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
34
34
  * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
@@ -49,8 +49,8 @@ export interface BlueRefinanceParams {
49
49
  * Bundle shape (callback contents depend on borrow mode):
50
50
  *
51
51
  * ```text
52
- * // optional: one reallocateTo per targetReallocations entry, run first
53
- * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
52
+ * // optional targetReallocations run first:
53
+ * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
54
54
  *
55
55
  * morphoSupplyCollateral(target, collateralAmount, user, [
56
56
  * // omitted in collat-only mode
@@ -84,7 +84,8 @@ export interface BlueRefinanceParams {
84
84
  * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
85
85
  * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
86
86
  * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
87
- * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
87
+ * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
88
+ * target, run before the supply leg. V1 fees add to `tx.value`; V2 penalties are paid in the target loan token.
88
89
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
89
90
  * a `setAuthorizationWithSig` call is prepended to the bundle.
90
91
  * @param params.metadata - Optional analytics metadata appended to `tx.data`.
@@ -93,8 +94,14 @@ export interface BlueRefinanceParams {
93
94
  * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
94
95
  * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
95
96
  * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
97
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
98
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
99
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
100
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
101
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
102
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
96
103
  * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
97
- * `maxRepaySharePrice`, or any reallocation fee is negative.
104
+ * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
98
105
  * @throws {RefinanceSameMarketError} when source and target market ids are equal.
99
106
  * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
100
107
  * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
@@ -5,7 +5,7 @@ import { BundlerAction } from "../../bundler/index.js";
5
5
  import { addTransactionMetadata } from "../../helpers/index.js";
6
6
  import { NegativeInputError, NonPositiveInputError, RefinanceSameMarketError, RefinanceSharesMissingBorrowAssetsError, RefinanceTokenMismatchError, } from "../../types/index.js";
7
7
  import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
8
- import { buildReallocationActions } from "./buildReallocationActions.js";
8
+ import { buildBlueReallocationActions } from "./buildReallocationActions.js";
9
9
  /**
10
10
  * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
11
11
  * chain that shares the same loan and collateral tokens.
@@ -17,8 +17,8 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
17
17
  * Bundle shape (callback contents depend on borrow mode):
18
18
  *
19
19
  * ```text
20
- * // optional: one reallocateTo per targetReallocations entry, run first
21
- * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
20
+ * // optional targetReallocations run first:
21
+ * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
22
22
  *
23
23
  * morphoSupplyCollateral(target, collateralAmount, user, [
24
24
  * // omitted in collat-only mode
@@ -52,7 +52,8 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
52
52
  * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
53
53
  * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
54
54
  * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
55
- * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
55
+ * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
56
+ * target, run before the supply leg. V1 fees add to `tx.value`; V2 penalties are paid in the target loan token.
56
57
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
57
58
  * a `setAuthorizationWithSig` call is prepended to the bundle.
58
59
  * @param params.metadata - Optional analytics metadata appended to `tx.data`.
@@ -61,8 +62,14 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
61
62
  * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
62
63
  * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
63
64
  * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
65
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
66
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
67
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
68
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
69
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
70
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
64
71
  * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
65
- * `maxRepaySharePrice`, or any reallocation fee is negative.
72
+ * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
66
73
  * @throws {RefinanceSameMarketError} when source and target market ids are equal.
67
74
  * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
68
75
  * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
@@ -179,15 +186,15 @@ export const blueRefinance = ({ source: { chainId, marketParams: sourceParams },
179
186
  args: [sourceParams, collateralAmount, generalAdapter1, false],
180
187
  });
181
188
  const actions = [];
182
- let reallocationFee = 0n;
183
189
  if (authorizationSignature) {
184
190
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
185
191
  }
186
- if (targetReallocations && targetReallocations.length > 0) {
187
- const result = buildReallocationActions(targetReallocations, targetParams);
188
- actions.push(...result.actions);
189
- reallocationFee = result.fee;
190
- }
192
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = buildBlueReallocationActions({
193
+ chainId,
194
+ reallocations: targetReallocations,
195
+ targetMarketParams: targetParams,
196
+ });
197
+ actions.push(...reallocationActions);
191
198
  actions.push({
192
199
  type: "morphoSupplyCollateral",
193
200
  args: [targetParams, collateralAmount, user, callback, false],
@@ -210,6 +217,7 @@ export const blueRefinance = ({ source: { chainId, marketParams: sourceParams },
210
217
  maxRepaySharePrice,
211
218
  user,
212
219
  reallocationFee,
220
+ reallocationPenaltyAssets,
213
221
  },
214
222
  },
215
223
  });
@@ -1,6 +1,6 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
- import type { Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueSupplyCollateralBorrowAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
2
+ import { type Address } from "viem";
3
+ import { type AuthorizationRequirementSignature, type BlueReallocationPlan, type BlueSupplyCollateralBorrowAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupplyCollateralBorrow}. */
5
5
  export interface BlueSupplyCollateralBorrowParams {
6
6
  market: {
@@ -18,8 +18,8 @@ export interface BlueSupplyCollateralBorrowParams {
18
18
  minSharePrice: bigint;
19
19
  /** Optional pre-signed permit/permit2 approval for the collateral transfer. */
20
20
  requirementSignature?: PermitRequirementSignature;
21
- /** Vault reallocations to execute before borrowing (computed by entity). */
22
- reallocations?: readonly VaultReallocation[];
21
+ /** Homogeneous Vault V1 or Vault V2 reallocations to execute before borrowing. */
22
+ reallocations?: BlueReallocationPlan;
23
23
  /**
24
24
  * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
25
25
  * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
@@ -32,9 +32,13 @@ export interface BlueSupplyCollateralBorrowParams {
32
32
  /**
33
33
  * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
34
34
  *
35
- * Routed through bundler3: collateral transfer → `morphoSupplyCollateral` → optional
36
- * `reallocateTo` calls → `morphoBorrow`. When `nativeAmount > 0`, native ETH is wrapped via
37
- * `GeneralAdapter1.wrapNative()` before the supply leg.
35
+ * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
36
+ * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
37
+ * never both. When `nativeAmount > 0`, native ETH is wrapped via
38
+ * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
39
+ * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
40
+ * collateral and loan tokens match, one combined pull funds both collateral and penalties through
41
+ * `GeneralAdapter1`.
38
42
  *
39
43
  * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
40
44
  * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
@@ -51,35 +55,40 @@ export interface BlueSupplyCollateralBorrowParams {
51
55
  * @param params.args.receiver - Address that receives the borrowed assets.
52
56
  * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
53
57
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
54
- * collateral transfer.
58
+ * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
55
59
  * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
56
60
  * collateral supply. Requires the collateral token to be the chain's wNative.
57
- * @param params.args.reallocations - Optional vault reallocations to execute between the supply
58
- * and borrow legs, computed by the entity layer.
61
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
62
+ * execute between the supply and borrow legs.
59
63
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
60
64
  * a `setAuthorizationWithSig` call is prepended to the bundle.
61
65
  * @param params.metadata - Optional analytics metadata attached to the bundle.
62
66
  * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
63
67
  * `data`, and the typed `action` discriminator the simulation layer consumes.
64
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, or any reallocation
65
- * fee is negative.
68
+ * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
69
+ * penalty is negative.
66
70
  * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
67
71
  * zero, or any reallocation withdrawal amount is non-positive.
72
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
73
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
74
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
75
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
76
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
77
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
68
78
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
69
79
  * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
70
80
  * token is not the chain's wNative.
71
81
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
72
82
  * is provided and the signed asset differs from `marketParams.collateralToken`.
73
83
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
74
- * is provided and the signed amount differs from `args.amount`.
84
+ * is provided and the signed amount differs from the total ERC-20 funding amount.
75
85
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
76
86
  * signature is missing its expiration.
77
- * @throws {EmptyReallocationWithdrawalsError} from `buildReallocationActions` when any
78
- * `reallocation.withdrawals` is empty.
79
- * @throws {ReallocationWithdrawalOnTargetMarketError} from `buildReallocationActions` when any
80
- * reallocation withdrawal references the target market.
81
- * @throws {UnsortedReallocationWithdrawalsError} from `buildReallocationActions` when
82
- * reallocation withdrawals are not strictly sorted by market id.
87
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
88
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
89
+ * the target market.
90
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
91
+ * sorted by market id.
83
92
  * @example
84
93
  * ```ts
85
94
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
@@ -1,16 +1,21 @@
1
1
  import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ import { isAddressEqual } from "viem";
2
3
  import { BundlerAction } from "../../bundler/index.js";
3
4
  import { addTransactionMetadata } from "../../helpers/index.js";
4
5
  import { NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
5
6
  import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
6
7
  import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
7
- import { buildReallocationActions } from "./buildReallocationActions.js";
8
+ import { buildBlueReallocationActions } from "./buildReallocationActions.js";
8
9
  /**
9
10
  * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
10
11
  *
11
- * Routed through bundler3: collateral transfer → `morphoSupplyCollateral` → optional
12
- * `reallocateTo` calls → `morphoBorrow`. When `nativeAmount > 0`, native ETH is wrapped via
13
- * `GeneralAdapter1.wrapNative()` before the supply leg.
12
+ * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
13
+ * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
14
+ * never both. When `nativeAmount > 0`, native ETH is wrapped via
15
+ * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
16
+ * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
17
+ * collateral and loan tokens match, one combined pull funds both collateral and penalties through
18
+ * `GeneralAdapter1`.
14
19
  *
15
20
  * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
16
21
  * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
@@ -27,35 +32,40 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
27
32
  * @param params.args.receiver - Address that receives the borrowed assets.
28
33
  * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
29
34
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
30
- * collateral transfer.
35
+ * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
31
36
  * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
32
37
  * collateral supply. Requires the collateral token to be the chain's wNative.
33
- * @param params.args.reallocations - Optional vault reallocations to execute between the supply
34
- * and borrow legs, computed by the entity layer.
38
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
39
+ * execute between the supply and borrow legs.
35
40
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
36
41
  * a `setAuthorizationWithSig` call is prepended to the bundle.
37
42
  * @param params.metadata - Optional analytics metadata attached to the bundle.
38
43
  * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
39
44
  * `data`, and the typed `action` discriminator the simulation layer consumes.
40
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, or any reallocation
41
- * fee is negative.
45
+ * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
46
+ * penalty is negative.
42
47
  * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
43
48
  * zero, or any reallocation withdrawal amount is non-positive.
49
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
50
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
51
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
52
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
53
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
54
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
44
55
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
45
56
  * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
46
57
  * token is not the chain's wNative.
47
58
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
48
59
  * is provided and the signed asset differs from `marketParams.collateralToken`.
49
60
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
50
- * is provided and the signed amount differs from `args.amount`.
61
+ * is provided and the signed amount differs from the total ERC-20 funding amount.
51
62
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
52
63
  * signature is missing its expiration.
53
- * @throws {EmptyReallocationWithdrawalsError} from `buildReallocationActions` when any
54
- * `reallocation.withdrawals` is empty.
55
- * @throws {ReallocationWithdrawalOnTargetMarketError} from `buildReallocationActions` when any
56
- * reallocation withdrawal references the target market.
57
- * @throws {UnsortedReallocationWithdrawalsError} from `buildReallocationActions` when
58
- * reallocation withdrawals are not strictly sorted by market id.
64
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
65
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
66
+ * the target market.
67
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
68
+ * sorted by market id.
59
69
  * @example
60
70
  * ```ts
61
71
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
@@ -90,6 +100,16 @@ export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams },
90
100
  if (totalCollateral === 0n) {
91
101
  throw new NonPositiveInputError("totalCollateral", totalCollateral);
92
102
  }
103
+ const usesSharedFundingToken = isAddressEqual(marketParams.collateralToken, marketParams.loanToken);
104
+ const reallocationResult = buildBlueReallocationActions({
105
+ chainId,
106
+ reallocations,
107
+ targetMarketParams: marketParams,
108
+ penaltyFundingSource: usesSharedFundingToken
109
+ ? "generalAdapter1"
110
+ : "initiator",
111
+ });
112
+ const erc20FundingAmount = amount + (usesSharedFundingToken ? reallocationResult.penaltyAssets : 0n);
93
113
  const actions = [];
94
114
  if (authorizationSignature) {
95
115
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
@@ -97,7 +117,7 @@ export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams },
97
117
  actions.push(...buildAssetFundingActions({
98
118
  chainId,
99
119
  asset: marketParams.collateralToken,
100
- erc20Amount: amount,
120
+ erc20Amount: erc20FundingAmount,
101
121
  nativeAmount: nativeAmount ?? 0n,
102
122
  requirementSignature,
103
123
  }));
@@ -105,12 +125,7 @@ export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams },
105
125
  type: "morphoSupplyCollateral",
106
126
  args: [marketParams, totalCollateral, onBehalf, [], false],
107
127
  });
108
- let reallocationFee = 0n;
109
- if (reallocations && reallocations.length > 0) {
110
- const result = buildReallocationActions(reallocations, marketParams);
111
- actions.push(...result.actions);
112
- reallocationFee = result.fee;
113
- }
128
+ actions.push(...reallocationResult.actions);
114
129
  actions.push({
115
130
  type: "morphoBorrow",
116
131
  args: [marketParams, borrowAmount, 0n, minSharePrice, receiver, false],
@@ -131,7 +146,8 @@ export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams },
131
146
  onBehalf,
132
147
  receiver,
133
148
  nativeAmount,
134
- reallocationFee,
149
+ reallocationFee: reallocationResult.fee,
150
+ reallocationPenaltyAssets: reallocationResult.penaltyAssets,
135
151
  },
136
152
  },
137
153
  });
@@ -1,6 +1,6 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueWithdrawAction, type Metadata, type Transaction, type VaultReallocation } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueReallocationPlan, type BlueWithdrawAction, type Metadata, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueWithdraw}. */
5
5
  export interface BlueWithdrawParams {
6
6
  market: {
@@ -17,11 +17,11 @@ export interface BlueWithdrawParams {
17
17
  /** Minimum withdraw share price (in ray). Slippage protection. */
18
18
  minSharePrice: bigint;
19
19
  /**
20
- * Vault reallocations to execute before withdrawing. Compute via
21
- * `MorphoBlue.getReallocations({ operation: "withdraw", amount })` or directly via
22
- * `computeReallocations({ operation: "withdraw", amount, ... })`.
20
+ * Homogeneous Vault V1 or Vault V2 reallocations to execute before withdrawing. V1 entries can be
21
+ * computed via `MorphoBlue.getVaultV1Reallocations({ operation: "withdraw", amount })` or directly
22
+ * via `computeVaultV1Reallocations({ operation: "withdraw", amount, ... })`.
23
23
  */
24
- reallocations?: readonly VaultReallocation[];
24
+ reallocations?: BlueReallocationPlan;
25
25
  /**
26
26
  * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
27
27
  * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
@@ -40,10 +40,11 @@ export interface BlueWithdrawParams {
40
40
  * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
41
41
  * supplier position close; immune to interest accrual between tx construction and execution).
42
42
  *
43
- * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
44
- * liquidity from other markets into this one via the PublicAllocator before withdrawing.
45
- * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
46
- * computed on-chain directly to `receiver`; no skim is required.
43
+ * A `reallocations` plan contains either V1 entries or V2 market/idle entries,
44
+ * never both. The calls run before the withdraw. V1
45
+ * fees accumulate in `tx.value`; V2 penalties are paid in the target loan
46
+ * token and donated to the vaults. The on-chain `morphoWithdraw` sends the
47
+ * assets computed on-chain directly to `receiver`; no skim is required.
47
48
  *
48
49
  * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
49
50
  * separate `onBehalf` field; mirror `blueBorrow`. The entity layer keeps `receiver` aligned
@@ -57,17 +58,23 @@ export interface BlueWithdrawParams {
57
58
  * @param params.args.receiver - Address that receives the withdrawn assets.
58
59
  * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
59
60
  * protection.
60
- * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
61
- * computed by the entity layer.
61
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
62
+ * execute before withdrawing.
62
63
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
63
64
  * a `setAuthorizationWithSig` call is prepended to the bundle.
64
65
  * @param params.metadata - Optional analytics metadata attached to the bundle.
65
66
  * @returns A deep-frozen `Transaction<BlueWithdrawAction>` with `to`, `value`, `data`, and
66
67
  * the typed `action` discriminator the simulation layer consumes.
67
- * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, or any reallocation fee
68
- * is negative.
68
+ * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, a V1 fee, or a V2
69
+ * penalty is negative.
69
70
  * @throws {NonPositiveInputError} when both `assets` and `shares` are zero or any reallocation
70
71
  * withdrawal amount is non-positive.
72
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
73
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
74
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
75
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
76
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
77
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
71
78
  * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
72
79
  * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
73
80
  * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references
@@ -3,7 +3,7 @@ import { BundlerAction } from "../../bundler/index.js";
3
3
  import { addTransactionMetadata } from "../../helpers/index.js";
4
4
  import { MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
5
5
  import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
6
- import { buildReallocationActions } from "./buildReallocationActions.js";
6
+ import { buildBlueReallocationActions } from "./buildReallocationActions.js";
7
7
  /**
8
8
  * Prepares a loan-asset withdraw transaction for a Morpho Blue market.
9
9
  *
@@ -13,10 +13,11 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
13
13
  * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
14
14
  * supplier position close; immune to interest accrual between tx construction and execution).
15
15
  *
16
- * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
17
- * liquidity from other markets into this one via the PublicAllocator before withdrawing.
18
- * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
19
- * computed on-chain directly to `receiver`; no skim is required.
16
+ * A `reallocations` plan contains either V1 entries or V2 market/idle entries,
17
+ * never both. The calls run before the withdraw. V1
18
+ * fees accumulate in `tx.value`; V2 penalties are paid in the target loan
19
+ * token and donated to the vaults. The on-chain `morphoWithdraw` sends the
20
+ * assets computed on-chain directly to `receiver`; no skim is required.
20
21
  *
21
22
  * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
22
23
  * separate `onBehalf` field; mirror `blueBorrow`. The entity layer keeps `receiver` aligned
@@ -30,17 +31,23 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
30
31
  * @param params.args.receiver - Address that receives the withdrawn assets.
31
32
  * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
32
33
  * protection.
33
- * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
34
- * computed by the entity layer.
34
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
35
+ * execute before withdrawing.
35
36
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
36
37
  * a `setAuthorizationWithSig` call is prepended to the bundle.
37
38
  * @param params.metadata - Optional analytics metadata attached to the bundle.
38
39
  * @returns A deep-frozen `Transaction<BlueWithdrawAction>` with `to`, `value`, `data`, and
39
40
  * the typed `action` discriminator the simulation layer consumes.
40
- * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, or any reallocation fee
41
- * is negative.
41
+ * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, a V1 fee, or a V2
42
+ * penalty is negative.
42
43
  * @throws {NonPositiveInputError} when both `assets` and `shares` are zero or any reallocation
43
44
  * withdrawal amount is non-positive.
45
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
46
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
47
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
48
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
49
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
50
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
44
51
  * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
45
52
  * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
46
53
  * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references
@@ -83,23 +90,20 @@ export const blueWithdraw = ({ market: { chainId, marketParams }, args: { assets
83
90
  throw new NegativeInputError("minSharePrice", minSharePrice);
84
91
  }
85
92
  const actions = [];
86
- let reallocationFee = 0n;
87
93
  if (authorizationSignature) {
88
94
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
89
95
  }
90
- if (reallocations && reallocations.length > 0) {
91
- const result = buildReallocationActions(reallocations, marketParams);
92
- actions.push(...result.actions);
93
- reallocationFee = result.fee;
94
- }
96
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = buildBlueReallocationActions({
97
+ chainId,
98
+ reallocations,
99
+ targetMarketParams: marketParams,
100
+ });
101
+ actions.push(...reallocationActions);
95
102
  actions.push({
96
103
  type: "morphoWithdraw",
97
104
  args: [marketParams, assets, shares, minSharePrice, receiver, false],
98
105
  });
99
- let tx = {
100
- ...BundlerAction.encodeBundle(chainId, actions),
101
- value: reallocationFee,
102
- };
106
+ let tx = BundlerAction.encodeBundle(chainId, actions);
103
107
  if (metadata) {
104
108
  tx = addTransactionMetadata(tx, metadata);
105
109
  }
@@ -114,6 +118,7 @@ export const blueWithdraw = ({ market: { chainId, marketParams }, args: { assets
114
118
  receiver,
115
119
  minSharePrice,
116
120
  reallocationFee,
121
+ reallocationPenaltyAssets,
117
122
  },
118
123
  },
119
124
  });
@@ -1,3 +1,4 @@
1
+ import { isAddressEqual } from "viem";
1
2
  import { APPROVE_ONLY_ONCE_TOKENS } from "../../helpers/constant.js";
2
3
  import { ApprovalAmountLessThanSpendAmountError, } from "../../types/index.js";
3
4
  import { encodeErc20Approval } from "./encode/encodeErc20Approval.js";
@@ -47,7 +48,7 @@ export const getRequirementsApproval = (params) => {
47
48
  }
48
49
  const approvals = [];
49
50
  if (allowances < spendAmount) {
50
- if (APPROVE_ONLY_ONCE_TOKENS[chainId]?.includes(address) &&
51
+ if (APPROVE_ONLY_ONCE_TOKENS[chainId]?.some((token) => isAddressEqual(token, address)) &&
51
52
  allowances > 0n) {
52
53
  approvals.push(encodeErc20Approval({
53
54
  token: address,