@morpho-org/morpho-sdk 5.4.1 → 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 (140) hide show
  1. package/README.md +23 -7
  2. package/lib/cjs/abis.d.ts +314 -1
  3. package/lib/cjs/abis.js +169 -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/encode/encodeErc20Approval.d.ts +1 -1
  17. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +9 -2
  18. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  19. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +131 -0
  20. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  21. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  22. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +3 -2
  23. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -3
  24. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  25. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +91 -0
  26. package/lib/cjs/actions/signatures/index.d.ts +1 -0
  27. package/lib/cjs/actions/signatures/index.js +1 -0
  28. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +54 -0
  29. package/lib/cjs/actions/vaultV1/inKindRedeem.js +96 -0
  30. package/lib/cjs/actions/vaultV1/index.d.ts +1 -0
  31. package/lib/cjs/actions/vaultV1/index.js +1 -0
  32. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +56 -0
  33. package/lib/cjs/actions/vaultV2/inKindRedeem.js +97 -0
  34. package/lib/cjs/actions/vaultV2/index.d.ts +1 -0
  35. package/lib/cjs/actions/vaultV2/index.js +1 -0
  36. package/lib/cjs/bundler/actions.d.ts +118 -2
  37. package/lib/cjs/bundler/actions.js +212 -6
  38. package/lib/cjs/bundler/types.d.ts +20 -0
  39. package/lib/cjs/constants.d.ts +1 -1
  40. package/lib/cjs/constants.js +3 -1
  41. package/lib/cjs/entities/blue/blue.d.ts +365 -76
  42. package/lib/cjs/entities/blue/blue.js +285 -52
  43. package/lib/cjs/entities/index.d.ts +2 -1
  44. package/lib/cjs/entities/index.js +6 -3
  45. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +82 -4
  46. package/lib/cjs/entities/vaultV1/vaultV1.js +164 -0
  47. package/lib/cjs/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  48. package/lib/cjs/entities/{reallocationData.js → vaultV1ReallocationData.js} +30 -18
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +89 -3
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +181 -0
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +511 -0
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1311 -0
  53. package/lib/{esm/helpers/computeReallocations.d.ts → cjs/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  54. package/lib/cjs/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +27 -13
  55. package/lib/cjs/helpers/constant.d.ts +5 -3
  56. package/lib/cjs/helpers/constant.js +6 -4
  57. package/lib/cjs/helpers/index.d.ts +3 -2
  58. package/lib/cjs/helpers/index.js +8 -3
  59. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  60. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +73 -0
  61. package/lib/cjs/helpers/validate.d.ts +31 -15
  62. package/lib/cjs/helpers/validate.js +140 -27
  63. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  64. package/lib/cjs/helpers/validateRequirementSpender.js +2 -1
  65. package/lib/cjs/types/action.d.ts +33 -1
  66. package/lib/cjs/types/error.d.ts +363 -5
  67. package/lib/cjs/types/error.js +455 -6
  68. package/lib/cjs/types/sharedLiquidity.d.ts +72 -8
  69. package/lib/cjs/utils.d.ts +2 -2
  70. package/lib/cjs/utils.js +6 -4
  71. package/lib/esm/abis.d.ts +314 -1
  72. package/lib/esm/abis.js +167 -1
  73. package/lib/esm/actions/blue/borrow.d.ts +21 -15
  74. package/lib/esm/actions/blue/borrow.js +26 -19
  75. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +1 -1
  76. package/lib/esm/actions/blue/buildAssetFundingActions.js +1 -1
  77. package/lib/esm/actions/blue/buildReallocationActions.d.ts +62 -19
  78. package/lib/esm/actions/blue/buildReallocationActions.js +119 -25
  79. package/lib/esm/actions/blue/refinance.d.ts +14 -7
  80. package/lib/esm/actions/blue/refinance.js +19 -11
  81. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  82. package/lib/esm/actions/blue/supplyCollateralBorrow.js +40 -24
  83. package/lib/esm/actions/blue/withdraw.d.ts +20 -13
  84. package/lib/esm/actions/blue/withdraw.js +24 -19
  85. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  86. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -2
  87. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  88. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +127 -0
  89. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  90. package/lib/esm/actions/requirements/encode/index.js +1 -0
  91. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +3 -2
  92. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -3
  93. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  94. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +87 -0
  95. package/lib/esm/actions/signatures/index.d.ts +1 -0
  96. package/lib/esm/actions/signatures/index.js +1 -0
  97. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +54 -0
  98. package/lib/esm/actions/vaultV1/inKindRedeem.js +92 -0
  99. package/lib/esm/actions/vaultV1/index.d.ts +1 -0
  100. package/lib/esm/actions/vaultV1/index.js +1 -0
  101. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +56 -0
  102. package/lib/esm/actions/vaultV2/inKindRedeem.js +93 -0
  103. package/lib/esm/actions/vaultV2/index.d.ts +1 -0
  104. package/lib/esm/actions/vaultV2/index.js +1 -0
  105. package/lib/esm/bundler/actions.d.ts +118 -2
  106. package/lib/esm/bundler/actions.js +215 -9
  107. package/lib/esm/bundler/types.d.ts +20 -0
  108. package/lib/esm/constants.d.ts +1 -1
  109. package/lib/esm/constants.js +1 -1
  110. package/lib/esm/entities/blue/blue.d.ts +362 -73
  111. package/lib/esm/entities/blue/blue.js +288 -55
  112. package/lib/esm/entities/index.d.ts +2 -1
  113. package/lib/esm/entities/index.js +2 -1
  114. package/lib/esm/entities/vaultV1/vaultV1.d.ts +80 -2
  115. package/lib/esm/entities/vaultV1/vaultV1.js +170 -6
  116. package/lib/esm/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  117. package/lib/esm/entities/{reallocationData.js → vaultV1ReallocationData.js} +33 -16
  118. package/lib/esm/entities/vaultV2/vaultV2.d.ts +88 -2
  119. package/lib/esm/entities/vaultV2/vaultV2.js +187 -6
  120. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +511 -0
  121. package/lib/esm/entities/vaultV2BlueReallocationData.js +1307 -0
  122. package/lib/{cjs/helpers/computeReallocations.d.ts → esm/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  123. package/lib/esm/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +25 -11
  124. package/lib/esm/helpers/constant.d.ts +5 -3
  125. package/lib/esm/helpers/constant.js +5 -3
  126. package/lib/esm/helpers/index.d.ts +3 -2
  127. package/lib/esm/helpers/index.js +3 -2
  128. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  129. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +70 -0
  130. package/lib/esm/helpers/validate.d.ts +31 -15
  131. package/lib/esm/helpers/validate.js +141 -30
  132. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  133. package/lib/esm/helpers/validateRequirementSpender.js +2 -1
  134. package/lib/esm/types/action.d.ts +33 -1
  135. package/lib/esm/types/error.d.ts +363 -5
  136. package/lib/esm/types/error.js +428 -4
  137. package/lib/esm/types/sharedLiquidity.d.ts +72 -8
  138. package/lib/esm/utils.d.ts +2 -2
  139. package/lib/esm/utils.js +2 -2
  140. package/package.json +9 -11
@@ -14,17 +14,18 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
14
14
  * `onBehalf`. Uses `minSharePrice` to protect against share price manipulation between
15
15
  * transaction construction and execution.
16
16
  *
17
- * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
18
- * liquidity from other markets via the PublicAllocator before borrowing. Reallocation fees
19
- * accumulate in `tx.value`.
17
+ * A `reallocations` plan contains either PublicAllocator V1 entries or Vault V2
18
+ * BluePublicAllocator entries, never both. The calls run before the borrow.
19
+ * V1 fees accumulate in `tx.value`; V2 penalties are paid in the target loan
20
+ * token and donated directly to each vault.
20
21
  *
21
22
  * @param params.market.chainId - The chain the market lives on.
22
23
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
23
24
  * @param params.args.amount - Loan asset amount to borrow, in the loan token's smallest unit.
24
25
  * @param params.args.receiver - Address that receives the borrowed assets.
25
26
  * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
26
- * @param params.args.reallocations - Optional vault reallocations to execute before borrowing,
27
- * computed by the entity layer.
27
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
28
+ * execute before borrowing.
28
29
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
29
30
  * a `setAuthorizationWithSig` call is prepended to the bundle.
30
31
  * @param params.metadata - Optional analytics metadata attached to the bundle.
@@ -32,13 +33,18 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
32
33
  * typed `action` discriminator the simulation layer consumes.
33
34
  * @throws {NonPositiveInputError} when `amount <= 0n` or any reallocation withdrawal amount
34
35
  * is non-positive.
35
- * @throws {NegativeInputError} when `minSharePrice < 0n` or any reallocation fee is negative.
36
- * @throws {EmptyReallocationWithdrawalsError} from `buildReallocationActions` when any
37
- * `reallocation.withdrawals` is empty.
38
- * @throws {ReallocationWithdrawalOnTargetMarketError} from `buildReallocationActions` when any
39
- * reallocation withdrawal references the target market.
40
- * @throws {UnsortedReallocationWithdrawalsError} from `buildReallocationActions` when
41
- * reallocation withdrawals are not strictly sorted by market id.
36
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
37
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
38
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
39
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
40
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
41
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
42
+ * @throws {NegativeInputError} when `minSharePrice < 0n`, a V1 fee, or a V2 penalty is negative.
43
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
44
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
45
+ * the target market.
46
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
47
+ * sorted by market id.
42
48
  * @example
43
49
  * ```ts
44
50
  * import { blueBorrow } from "@morpho-org/morpho-sdk";
@@ -62,15 +68,15 @@ const blueBorrow = ({ market: { chainId, marketParams }, args: { amount, receive
62
68
  throw new index_js_3.NegativeInputError("minSharePrice", minSharePrice);
63
69
  }
64
70
  const actions = [];
65
- let reallocationFee = 0n;
66
71
  if (authorizationSignature) {
67
72
  actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
68
73
  }
69
- if (reallocations && reallocations.length > 0) {
70
- const result = (0, buildReallocationActions_js_1.buildReallocationActions)(reallocations, marketParams);
71
- actions.push(...result.actions);
72
- reallocationFee = result.fee;
73
- }
74
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
75
+ chainId,
76
+ reallocations,
77
+ targetMarketParams: marketParams,
78
+ });
79
+ actions.push(...reallocationActions);
74
80
  actions.push({
75
81
  type: "morphoBorrow",
76
82
  args: [marketParams, amount, 0n, minSharePrice, receiver, false],
@@ -89,6 +95,7 @@ const blueBorrow = ({ market: { chainId, marketParams }, args: { amount, receive
89
95
  receiver,
90
96
  minSharePrice,
91
97
  reallocationFee,
98
+ reallocationPenaltyAssets,
92
99
  },
93
100
  },
94
101
  });
@@ -20,7 +20,7 @@ export interface BuildAssetFundingActionsParams {
20
20
  * `blueSupplyCollateral`, `blueSupplyCollateralBorrow`, `blueRepay`, `blueRepayWithdrawCollateral`).
21
21
  *
22
22
  * Encode-only and synchronous: returns a fresh `Action[]` (never mutates its inputs, mirroring
23
- * `buildReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
23
+ * `buildVaultV2BlueReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
24
24
  * `asset` is the chain's wNative and emits `nativeTransfer → wrapNative`. When `erc20Amount > 0n`,
25
25
  * pulls the ERC-20 via a signed permit/permit2 (`requirementSignature`) or a plain
26
26
  * `erc20TransferFrom` — `getTokenRequirementActions` emits the latter itself when no signature is
@@ -10,7 +10,7 @@ const getTokenRequirementActions_js_1 = require("../signatures/getTokenRequireme
10
10
  * `blueSupplyCollateral`, `blueSupplyCollateralBorrow`, `blueRepay`, `blueRepayWithdrawCollateral`).
11
11
  *
12
12
  * Encode-only and synchronous: returns a fresh `Action[]` (never mutates its inputs, mirroring
13
- * `buildReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
13
+ * `buildVaultV2BlueReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
14
14
  * `asset` is the chain's wNative and emits `nativeTransfer → wrapNative`. When `erc20Amount > 0n`,
15
15
  * pulls the ERC-20 via a signed permit/permit2 (`requirementSignature`) or a plain
16
16
  * `erc20TransferFrom` — `getTokenRequirementActions` emits the latter itself when no signature is
@@ -1,26 +1,69 @@
1
- import type { MarketParams } from "@morpho-org/blue-sdk";
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Action } from "../../bundler/index.js";
3
- import type { VaultReallocation } from "../../types/index.js";
3
+ import type { BlueReallocationPlan, VaultV1Reallocation, VaultV2BlueReallocation } from "../../types/index.js";
4
4
  /**
5
- * Builds reallocation bundler actions and computes the total fee.
5
+ * Builds PublicAllocator V1 reallocation actions for a Morpho Blue target market.
6
6
  *
7
- * Validates the reallocations, then encodes each as a `reallocateTo` action against the target
8
- * market. Returns `{ actions: [], fee: 0n }` for an empty input — callers gate on
9
- * `reallocations.length > 0` and skip the call entirely in that case. Internal helper —
10
- * consumed by the Blue actions that accept reallocations; not re-exported on the public surface.
7
+ * Preserves the supplied reallocation order and aggregates each allocator call's native fee.
11
8
  *
12
- * @param reallocations - The vault reallocations to encode.
13
- * @param targetMarketParams - The target market params the freed liquidity is destined for.
14
- * @returns The encoded `reallocateTo` actions and the summed reallocation fee in native tokens.
15
- * @throws {NegativeInputError} when any reallocation fee is negative.
16
- * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
17
- * @throws {NonPositiveInputError} when any withdrawal amount is non-positive.
18
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a withdrawal references the target market.
19
- * @throws {UnsortedReallocationWithdrawalsError} when withdrawals within a reallocation are not
20
- * strictly sorted by market id.
9
+ * @param params.reallocations - Validated Vault V1 reallocations to execute.
10
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
11
+ * @returns The reallocation actions and aggregate native fee, with zero V2 penalty assets.
21
12
  * @internal
22
13
  */
23
- export declare const buildReallocationActions: (reallocations: readonly VaultReallocation[], targetMarketParams: MarketParams) => {
24
- readonly actions: Action[];
25
- readonly fee: bigint;
14
+ export declare const buildVaultV1ReallocationActions: ({ reallocations, targetMarketParams, }: {
15
+ readonly reallocations: readonly VaultV1Reallocation[];
16
+ readonly targetMarketParams: MarketParams;
17
+ }) => {
18
+ actions: Action[];
19
+ fee: bigint;
20
+ penaltyAssets: bigint;
21
+ };
22
+ /**
23
+ * Builds BluePublicAllocator reallocation actions for a Morpho Blue target market.
24
+ *
25
+ * Prepends one aggregate loan-token funding action when penalties are non-zero, then builds one
26
+ * allocator action per validated Vault V2 reallocation.
27
+ *
28
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
29
+ * @param params.reallocations - Validated Vault V2 Blue reallocations to execute.
30
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
31
+ * @param params.penaltyFundingSource - Optional source of penalty assets. Defaults to the
32
+ * transaction initiator.
33
+ * @returns The funding and reallocation actions and aggregate penalty assets, with zero native fee.
34
+ * @internal
35
+ */
36
+ export declare const buildVaultV2BlueReallocationActions: ({ chainId, reallocations, targetMarketParams, penaltyFundingSource, }: {
37
+ readonly chainId: number;
38
+ readonly reallocations: readonly VaultV2BlueReallocation[];
39
+ readonly targetMarketParams: MarketParams;
40
+ readonly penaltyFundingSource?: "initiator" | "generalAdapter1";
41
+ }) => {
42
+ actions: Action[];
43
+ fee: bigint;
44
+ penaltyAssets: bigint;
45
+ };
46
+ /**
47
+ * Validates a homogeneous Blue reallocation plan and builds its Bundler actions.
48
+ *
49
+ * Dispatches Vault V1 and Vault V2 plans to their version-specific builders. V1 plans aggregate
50
+ * native fees, while V2 plans aggregate loan-token penalties using the selected funding source.
51
+ *
52
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
53
+ * @param params.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocation plan.
54
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
55
+ * @param params.penaltyFundingSource - Optional source of V2 penalty assets. Defaults to the
56
+ * transaction initiator.
57
+ * @returns The reallocation actions, aggregate V1 native fee, and aggregate V2 penalty assets.
58
+ * @internal
59
+ */
60
+ export declare const buildBlueReallocationActions: ({ chainId, reallocations, targetMarketParams, penaltyFundingSource, }: {
61
+ readonly chainId: number;
62
+ readonly reallocations: BlueReallocationPlan | undefined;
63
+ readonly targetMarketParams: MarketParams;
64
+ readonly penaltyFundingSource?: "initiator" | "generalAdapter1";
65
+ }) => {
66
+ actions: Action[];
67
+ fee: bigint;
68
+ penaltyAssets: bigint;
26
69
  };
@@ -1,45 +1,141 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildReallocationActions = void 0;
4
- const index_js_1 = require("../../helpers/index.js");
3
+ exports.buildBlueReallocationActions = exports.buildVaultV2BlueReallocationActions = exports.buildVaultV1ReallocationActions = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const validate_js_1 = require("../../helpers/validate.js");
5
6
  /**
6
- * Builds reallocation bundler actions and computes the total fee.
7
+ * Builds PublicAllocator V1 reallocation actions for a Morpho Blue target market.
7
8
  *
8
- * Validates the reallocations, then encodes each as a `reallocateTo` action against the target
9
- * market. Returns `{ actions: [], fee: 0n }` for an empty input — callers gate on
10
- * `reallocations.length > 0` and skip the call entirely in that case. Internal helper —
11
- * consumed by the Blue actions that accept reallocations; not re-exported on the public surface.
9
+ * Preserves the supplied reallocation order and aggregates each allocator call's native fee.
12
10
  *
13
- * @param reallocations - The vault reallocations to encode.
14
- * @param targetMarketParams - The target market params the freed liquidity is destined for.
15
- * @returns The encoded `reallocateTo` actions and the summed reallocation fee in native tokens.
16
- * @throws {NegativeInputError} when any reallocation fee is negative.
17
- * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
18
- * @throws {NonPositiveInputError} when any withdrawal amount is non-positive.
19
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a withdrawal references the target market.
20
- * @throws {UnsortedReallocationWithdrawalsError} when withdrawals within a reallocation are not
21
- * strictly sorted by market id.
11
+ * @param params.reallocations - Validated Vault V1 reallocations to execute.
12
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
13
+ * @returns The reallocation actions and aggregate native fee, with zero V2 penalty assets.
22
14
  * @internal
23
15
  */
24
- const buildReallocationActions = (reallocations, targetMarketParams) => {
25
- (0, index_js_1.validateReallocations)(reallocations, targetMarketParams.id);
26
- const fee = reallocations.reduce((sum, r) => sum + r.fee, 0n);
16
+ const buildVaultV1ReallocationActions = ({ reallocations, targetMarketParams, }) => {
17
+ let fee = 0n;
27
18
  const actions = [];
28
- for (const r of reallocations) {
19
+ for (const reallocation of reallocations) {
29
20
  actions.push({
30
21
  type: "reallocateTo",
31
22
  args: [
32
- r.vault,
33
- r.fee,
34
- r.withdrawals.map((w) => ({
35
- marketParams: w.marketParams,
36
- amount: w.amount,
23
+ reallocation.vault,
24
+ reallocation.fee,
25
+ reallocation.withdrawals.map((withdrawal) => ({
26
+ marketParams: withdrawal.marketParams,
27
+ amount: withdrawal.amount,
37
28
  })),
38
29
  targetMarketParams,
39
30
  false,
40
31
  ],
41
32
  });
33
+ fee += reallocation.fee;
42
34
  }
43
- return { actions, fee };
35
+ return { actions, fee, penaltyAssets: 0n };
44
36
  };
45
- exports.buildReallocationActions = buildReallocationActions;
37
+ exports.buildVaultV1ReallocationActions = buildVaultV1ReallocationActions;
38
+ /**
39
+ * Builds BluePublicAllocator reallocation actions for a Morpho Blue target market.
40
+ *
41
+ * Prepends one aggregate loan-token funding action when penalties are non-zero, then builds one
42
+ * allocator action per validated Vault V2 reallocation.
43
+ *
44
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
45
+ * @param params.reallocations - Validated Vault V2 Blue reallocations to execute.
46
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
47
+ * @param params.penaltyFundingSource - Optional source of penalty assets. Defaults to the
48
+ * transaction initiator.
49
+ * @returns The funding and reallocation actions and aggregate penalty assets, with zero native fee.
50
+ * @internal
51
+ */
52
+ const buildVaultV2BlueReallocationActions = ({ chainId, reallocations, targetMarketParams, penaltyFundingSource = "initiator", }) => {
53
+ const actions = [];
54
+ const penaltyAssets = reallocations.reduce((total, reallocation) => total +
55
+ blue_sdk_1.VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
56
+ if (penaltyAssets > 0n) {
57
+ const { bundler3: { bundler3, generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
58
+ actions.push(penaltyFundingSource === "generalAdapter1"
59
+ ? {
60
+ type: "erc20Transfer",
61
+ args: [
62
+ targetMarketParams.loanToken,
63
+ bundler3,
64
+ penaltyAssets,
65
+ generalAdapter1,
66
+ false,
67
+ ],
68
+ }
69
+ : {
70
+ type: "erc20TransferFrom",
71
+ args: [
72
+ targetMarketParams.loanToken,
73
+ penaltyAssets,
74
+ bundler3,
75
+ false,
76
+ ],
77
+ });
78
+ }
79
+ for (const reallocation of reallocations) {
80
+ actions.push(reallocation.from.type === "market"
81
+ ? {
82
+ type: "vaultV2BluePublicAllocatorReallocate",
83
+ args: [
84
+ reallocation.vault,
85
+ reallocation.from.adapter,
86
+ reallocation.from.marketParams,
87
+ reallocation.to.adapter,
88
+ targetMarketParams,
89
+ reallocation.assets,
90
+ reallocation.penalty,
91
+ false,
92
+ ],
93
+ }
94
+ : {
95
+ type: "vaultV2BluePublicAllocatorAllocateFromIdle",
96
+ args: [
97
+ reallocation.vault,
98
+ reallocation.to.adapter,
99
+ targetMarketParams,
100
+ reallocation.assets,
101
+ reallocation.penalty,
102
+ false,
103
+ ],
104
+ });
105
+ }
106
+ return { actions, fee: 0n, penaltyAssets };
107
+ };
108
+ exports.buildVaultV2BlueReallocationActions = buildVaultV2BlueReallocationActions;
109
+ /**
110
+ * Validates a homogeneous Blue reallocation plan and builds its Bundler actions.
111
+ *
112
+ * Dispatches Vault V1 and Vault V2 plans to their version-specific builders. V1 plans aggregate
113
+ * native fees, while V2 plans aggregate loan-token penalties using the selected funding source.
114
+ *
115
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
116
+ * @param params.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocation plan.
117
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
118
+ * @param params.penaltyFundingSource - Optional source of V2 penalty assets. Defaults to the
119
+ * transaction initiator.
120
+ * @returns The reallocation actions, aggregate V1 native fee, and aggregate V2 penalty assets.
121
+ * @internal
122
+ */
123
+ const buildBlueReallocationActions = ({ chainId, reallocations, targetMarketParams, penaltyFundingSource, }) => {
124
+ const reallocationPlan = (0, validate_js_1.validateAndNormalizeReallocations)({
125
+ reallocations,
126
+ targetMarketId: targetMarketParams.id,
127
+ chainId,
128
+ });
129
+ return reallocationPlan.type === "vaultV1"
130
+ ? (0, exports.buildVaultV1ReallocationActions)({
131
+ reallocations: reallocationPlan.reallocations,
132
+ targetMarketParams,
133
+ })
134
+ : (0, exports.buildVaultV2BlueReallocationActions)({
135
+ chainId,
136
+ reallocations: reallocationPlan.reallocations,
137
+ targetMarketParams,
138
+ penaltyFundingSource,
139
+ });
140
+ };
141
+ exports.buildBlueReallocationActions = buildBlueReallocationActions;
@@ -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.
@@ -20,8 +20,8 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
20
20
  * Bundle shape (callback contents depend on borrow mode):
21
21
  *
22
22
  * ```text
23
- * // optional: one reallocateTo per targetReallocations entry, run first
24
- * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
23
+ * // optional targetReallocations run first:
24
+ * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
25
25
  *
26
26
  * morphoSupplyCollateral(target, collateralAmount, user, [
27
27
  * // omitted in collat-only mode
@@ -55,7 +55,8 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
55
55
  * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
56
56
  * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
57
57
  * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
58
- * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
58
+ * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
59
+ * target, run before the supply leg. V1 fees add to `tx.value`; V2 penalties are paid in the target loan token.
59
60
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
60
61
  * a `setAuthorizationWithSig` call is prepended to the bundle.
61
62
  * @param params.metadata - Optional analytics metadata appended to `tx.data`.
@@ -64,8 +65,14 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
64
65
  * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
65
66
  * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
66
67
  * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
68
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
69
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
70
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
71
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
72
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
73
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
67
74
  * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
68
- * `maxRepaySharePrice`, or any reallocation fee is negative.
75
+ * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
69
76
  * @throws {RefinanceSameMarketError} when source and target market ids are equal.
70
77
  * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
71
78
  * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
@@ -182,15 +189,15 @@ const blueRefinance = ({ source: { chainId, marketParams: sourceParams }, target
182
189
  args: [sourceParams, collateralAmount, generalAdapter1, false],
183
190
  });
184
191
  const actions = [];
185
- let reallocationFee = 0n;
186
192
  if (authorizationSignature) {
187
193
  actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
188
194
  }
189
- if (targetReallocations && targetReallocations.length > 0) {
190
- const result = (0, buildReallocationActions_js_1.buildReallocationActions)(targetReallocations, targetParams);
191
- actions.push(...result.actions);
192
- reallocationFee = result.fee;
193
- }
195
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
196
+ chainId,
197
+ reallocations: targetReallocations,
198
+ targetMarketParams: targetParams,
199
+ });
200
+ actions.push(...reallocationActions);
194
201
  actions.push({
195
202
  type: "morphoSupplyCollateral",
196
203
  args: [targetParams, collateralAmount, user, callback, false],
@@ -213,6 +220,7 @@ const blueRefinance = ({ source: { chainId, marketParams: sourceParams }, target
213
220
  maxRepaySharePrice,
214
221
  user,
215
222
  reallocationFee,
223
+ reallocationPenaltyAssets,
216
224
  },
217
225
  },
218
226
  });
@@ -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";