@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
@@ -3,7 +3,7 @@ import { BundlerAction } from "../../bundler/index.js";
3
3
  import { addTransactionMetadata } from "../../helpers/index.js";
4
4
  import { 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 borrow transaction for a Morpho Blue market.
9
9
  *
@@ -11,17 +11,18 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
11
11
  * `onBehalf`. Uses `minSharePrice` to protect against share price manipulation between
12
12
  * transaction construction and execution.
13
13
  *
14
- * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
15
- * liquidity from other markets via the PublicAllocator before borrowing. Reallocation fees
16
- * accumulate in `tx.value`.
14
+ * A `reallocations` plan contains either PublicAllocator V1 entries or Vault V2
15
+ * BluePublicAllocator entries, never both. The calls run before the borrow.
16
+ * V1 fees accumulate in `tx.value`; V2 penalties are paid in the target loan
17
+ * token and donated directly to each vault.
17
18
  *
18
19
  * @param params.market.chainId - The chain the market lives on.
19
20
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
20
21
  * @param params.args.amount - Loan asset amount to borrow, in the loan token's smallest unit.
21
22
  * @param params.args.receiver - Address that receives the borrowed assets.
22
23
  * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
23
- * @param params.args.reallocations - Optional vault reallocations to execute before borrowing,
24
- * computed by the entity layer.
24
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
25
+ * execute before borrowing.
25
26
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
26
27
  * a `setAuthorizationWithSig` call is prepended to the bundle.
27
28
  * @param params.metadata - Optional analytics metadata attached to the bundle.
@@ -29,13 +30,18 @@ import { buildReallocationActions } from "./buildReallocationActions.js";
29
30
  * typed `action` discriminator the simulation layer consumes.
30
31
  * @throws {NonPositiveInputError} when `amount <= 0n` or any reallocation withdrawal amount
31
32
  * is non-positive.
32
- * @throws {NegativeInputError} when `minSharePrice < 0n` or any reallocation fee is negative.
33
- * @throws {EmptyReallocationWithdrawalsError} from `buildReallocationActions` when any
34
- * `reallocation.withdrawals` is empty.
35
- * @throws {ReallocationWithdrawalOnTargetMarketError} from `buildReallocationActions` when any
36
- * reallocation withdrawal references the target market.
37
- * @throws {UnsortedReallocationWithdrawalsError} from `buildReallocationActions` when
38
- * reallocation withdrawals are not strictly sorted by market id.
33
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
34
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
35
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
36
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
37
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
38
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
39
+ * @throws {NegativeInputError} when `minSharePrice < 0n`, a V1 fee, or a V2 penalty is negative.
40
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
41
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
42
+ * the target market.
43
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
44
+ * sorted by market id.
39
45
  * @example
40
46
  * ```ts
41
47
  * import { blueBorrow } from "@morpho-org/morpho-sdk";
@@ -59,15 +65,15 @@ export const blueBorrow = ({ market: { chainId, marketParams }, args: { amount,
59
65
  throw new NegativeInputError("minSharePrice", minSharePrice);
60
66
  }
61
67
  const actions = [];
62
- let reallocationFee = 0n;
63
68
  if (authorizationSignature) {
64
69
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
65
70
  }
66
- if (reallocations && reallocations.length > 0) {
67
- const result = buildReallocationActions(reallocations, marketParams);
68
- actions.push(...result.actions);
69
- reallocationFee = result.fee;
70
- }
71
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = buildBlueReallocationActions({
72
+ chainId,
73
+ reallocations,
74
+ targetMarketParams: marketParams,
75
+ });
76
+ actions.push(...reallocationActions);
71
77
  actions.push({
72
78
  type: "morphoBorrow",
73
79
  args: [marketParams, amount, 0n, minSharePrice, receiver, false],
@@ -86,6 +92,7 @@ export const blueBorrow = ({ market: { chainId, marketParams }, args: { amount,
86
92
  receiver,
87
93
  minSharePrice,
88
94
  reallocationFee,
95
+ reallocationPenaltyAssets,
89
96
  },
90
97
  },
91
98
  });
@@ -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
@@ -7,7 +7,7 @@ import { getTokenRequirementActions } from "../signatures/getTokenRequirementAct
7
7
  * `blueSupplyCollateral`, `blueSupplyCollateralBorrow`, `blueRepay`, `blueRepayWithdrawCollateral`).
8
8
  *
9
9
  * Encode-only and synchronous: returns a fresh `Action[]` (never mutates its inputs, mirroring
10
- * `buildReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
10
+ * `buildVaultV2BlueReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
11
11
  * `asset` is the chain's wNative and emits `nativeTransfer → wrapNative`. When `erc20Amount > 0n`,
12
12
  * pulls the ERC-20 via a signed permit/permit2 (`requirementSignature`) or a plain
13
13
  * `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,41 +1,135 @@
1
- import { validateReallocations } from "../../helpers/index.js";
1
+ import { getChainAddresses, VaultV2BluePublicAllocatorConfigUtils, } from "@morpho-org/blue-sdk";
2
+ import { validateAndNormalizeReallocations } from "../../helpers/validate.js";
2
3
  /**
3
- * Builds reallocation bundler actions and computes the total fee.
4
+ * Builds PublicAllocator V1 reallocation actions for a Morpho Blue target market.
4
5
  *
5
- * Validates the reallocations, then encodes each as a `reallocateTo` action against the target
6
- * market. Returns `{ actions: [], fee: 0n }` for an empty input — callers gate on
7
- * `reallocations.length > 0` and skip the call entirely in that case. Internal helper —
8
- * consumed by the Blue actions that accept reallocations; not re-exported on the public surface.
6
+ * Preserves the supplied reallocation order and aggregates each allocator call's native fee.
9
7
  *
10
- * @param reallocations - The vault reallocations to encode.
11
- * @param targetMarketParams - The target market params the freed liquidity is destined for.
12
- * @returns The encoded `reallocateTo` actions and the summed reallocation fee in native tokens.
13
- * @throws {NegativeInputError} when any reallocation fee is negative.
14
- * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
15
- * @throws {NonPositiveInputError} when any withdrawal amount is non-positive.
16
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a withdrawal references the target market.
17
- * @throws {UnsortedReallocationWithdrawalsError} when withdrawals within a reallocation are not
18
- * strictly sorted by market id.
8
+ * @param params.reallocations - Validated Vault V1 reallocations to execute.
9
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
10
+ * @returns The reallocation actions and aggregate native fee, with zero V2 penalty assets.
19
11
  * @internal
20
12
  */
21
- export const buildReallocationActions = (reallocations, targetMarketParams) => {
22
- validateReallocations(reallocations, targetMarketParams.id);
23
- const fee = reallocations.reduce((sum, r) => sum + r.fee, 0n);
13
+ export const buildVaultV1ReallocationActions = ({ reallocations, targetMarketParams, }) => {
14
+ let fee = 0n;
24
15
  const actions = [];
25
- for (const r of reallocations) {
16
+ for (const reallocation of reallocations) {
26
17
  actions.push({
27
18
  type: "reallocateTo",
28
19
  args: [
29
- r.vault,
30
- r.fee,
31
- r.withdrawals.map((w) => ({
32
- marketParams: w.marketParams,
33
- amount: w.amount,
20
+ reallocation.vault,
21
+ reallocation.fee,
22
+ reallocation.withdrawals.map((withdrawal) => ({
23
+ marketParams: withdrawal.marketParams,
24
+ amount: withdrawal.amount,
34
25
  })),
35
26
  targetMarketParams,
36
27
  false,
37
28
  ],
38
29
  });
30
+ fee += reallocation.fee;
39
31
  }
40
- return { actions, fee };
32
+ return { actions, fee, penaltyAssets: 0n };
33
+ };
34
+ /**
35
+ * Builds BluePublicAllocator reallocation actions for a Morpho Blue target market.
36
+ *
37
+ * Prepends one aggregate loan-token funding action when penalties are non-zero, then builds one
38
+ * allocator action per validated Vault V2 reallocation.
39
+ *
40
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
41
+ * @param params.reallocations - Validated Vault V2 Blue reallocations to execute.
42
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
43
+ * @param params.penaltyFundingSource - Optional source of penalty assets. Defaults to the
44
+ * transaction initiator.
45
+ * @returns The funding and reallocation actions and aggregate penalty assets, with zero native fee.
46
+ * @internal
47
+ */
48
+ export const buildVaultV2BlueReallocationActions = ({ chainId, reallocations, targetMarketParams, penaltyFundingSource = "initiator", }) => {
49
+ const actions = [];
50
+ const penaltyAssets = reallocations.reduce((total, reallocation) => total +
51
+ VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
52
+ if (penaltyAssets > 0n) {
53
+ const { bundler3: { bundler3, generalAdapter1 }, } = getChainAddresses(chainId);
54
+ actions.push(penaltyFundingSource === "generalAdapter1"
55
+ ? {
56
+ type: "erc20Transfer",
57
+ args: [
58
+ targetMarketParams.loanToken,
59
+ bundler3,
60
+ penaltyAssets,
61
+ generalAdapter1,
62
+ false,
63
+ ],
64
+ }
65
+ : {
66
+ type: "erc20TransferFrom",
67
+ args: [
68
+ targetMarketParams.loanToken,
69
+ penaltyAssets,
70
+ bundler3,
71
+ false,
72
+ ],
73
+ });
74
+ }
75
+ for (const reallocation of reallocations) {
76
+ actions.push(reallocation.from.type === "market"
77
+ ? {
78
+ type: "vaultV2BluePublicAllocatorReallocate",
79
+ args: [
80
+ reallocation.vault,
81
+ reallocation.from.adapter,
82
+ reallocation.from.marketParams,
83
+ reallocation.to.adapter,
84
+ targetMarketParams,
85
+ reallocation.assets,
86
+ reallocation.penalty,
87
+ false,
88
+ ],
89
+ }
90
+ : {
91
+ type: "vaultV2BluePublicAllocatorAllocateFromIdle",
92
+ args: [
93
+ reallocation.vault,
94
+ reallocation.to.adapter,
95
+ targetMarketParams,
96
+ reallocation.assets,
97
+ reallocation.penalty,
98
+ false,
99
+ ],
100
+ });
101
+ }
102
+ return { actions, fee: 0n, penaltyAssets };
103
+ };
104
+ /**
105
+ * Validates a homogeneous Blue reallocation plan and builds its Bundler actions.
106
+ *
107
+ * Dispatches Vault V1 and Vault V2 plans to their version-specific builders. V1 plans aggregate
108
+ * native fees, while V2 plans aggregate loan-token penalties using the selected funding source.
109
+ *
110
+ * @param params.chainId - Chain whose registered Bundler3 and allocator addresses are used.
111
+ * @param params.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocation plan.
112
+ * @param params.targetMarketParams - Morpho Blue market receiving the reallocated liquidity.
113
+ * @param params.penaltyFundingSource - Optional source of V2 penalty assets. Defaults to the
114
+ * transaction initiator.
115
+ * @returns The reallocation actions, aggregate V1 native fee, and aggregate V2 penalty assets.
116
+ * @internal
117
+ */
118
+ export const buildBlueReallocationActions = ({ chainId, reallocations, targetMarketParams, penaltyFundingSource, }) => {
119
+ const reallocationPlan = validateAndNormalizeReallocations({
120
+ reallocations,
121
+ targetMarketId: targetMarketParams.id,
122
+ chainId,
123
+ });
124
+ return reallocationPlan.type === "vaultV1"
125
+ ? buildVaultV1ReallocationActions({
126
+ reallocations: reallocationPlan.reallocations,
127
+ targetMarketParams,
128
+ })
129
+ : buildVaultV2BlueReallocationActions({
130
+ chainId,
131
+ reallocations: reallocationPlan.reallocations,
132
+ targetMarketParams,
133
+ penaltyFundingSource,
134
+ });
41
135
  };
@@ -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";