@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
- 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";
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueSupplyCollateralBorrow = void 0;
4
4
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const viem_1 = require("viem");
5
6
  const index_js_1 = require("../../bundler/index.js");
6
7
  const index_js_2 = require("../../helpers/index.js");
7
8
  const index_js_3 = require("../../types/index.js");
@@ -11,9 +12,13 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
11
12
  /**
12
13
  * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
13
14
  *
14
- * Routed through bundler3: collateral transfer → `morphoSupplyCollateral` → optional
15
- * `reallocateTo` calls → `morphoBorrow`. When `nativeAmount > 0`, native ETH is wrapped via
16
- * `GeneralAdapter1.wrapNative()` before the supply leg.
15
+ * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
16
+ * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
17
+ * never both. When `nativeAmount > 0`, native ETH is wrapped via
18
+ * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
19
+ * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
20
+ * collateral and loan tokens match, one combined pull funds both collateral and penalties through
21
+ * `GeneralAdapter1`.
17
22
  *
18
23
  * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
19
24
  * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
@@ -30,35 +35,40 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
30
35
  * @param params.args.receiver - Address that receives the borrowed assets.
31
36
  * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
32
37
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
33
- * collateral transfer.
38
+ * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
34
39
  * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
35
40
  * collateral supply. Requires the collateral token to be the chain's wNative.
36
- * @param params.args.reallocations - Optional vault reallocations to execute between the supply
37
- * and borrow legs, computed by the entity layer.
41
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
42
+ * execute between the supply and borrow legs.
38
43
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
39
44
  * a `setAuthorizationWithSig` call is prepended to the bundle.
40
45
  * @param params.metadata - Optional analytics metadata attached to the bundle.
41
46
  * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
42
47
  * `data`, and the typed `action` discriminator the simulation layer consumes.
43
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, or any reallocation
44
- * fee is negative.
48
+ * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
49
+ * penalty is negative.
45
50
  * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
46
51
  * zero, or any reallocation withdrawal amount is non-positive.
52
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
53
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
54
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
55
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
56
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
57
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
47
58
  * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
48
59
  * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
49
60
  * token is not the chain's wNative.
50
61
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
51
62
  * is provided and the signed asset differs from `marketParams.collateralToken`.
52
63
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
53
- * is provided and the signed amount differs from `args.amount`.
64
+ * is provided and the signed amount differs from the total ERC-20 funding amount.
54
65
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
55
66
  * signature is missing its expiration.
56
- * @throws {EmptyReallocationWithdrawalsError} from `buildReallocationActions` when any
57
- * `reallocation.withdrawals` is empty.
58
- * @throws {ReallocationWithdrawalOnTargetMarketError} from `buildReallocationActions` when any
59
- * reallocation withdrawal references the target market.
60
- * @throws {UnsortedReallocationWithdrawalsError} from `buildReallocationActions` when
61
- * reallocation withdrawals are not strictly sorted by market id.
67
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
68
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
69
+ * the target market.
70
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
71
+ * sorted by market id.
62
72
  * @example
63
73
  * ```ts
64
74
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
@@ -93,6 +103,16 @@ const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: {
93
103
  if (totalCollateral === 0n) {
94
104
  throw new index_js_3.NonPositiveInputError("totalCollateral", totalCollateral);
95
105
  }
106
+ const usesSharedFundingToken = (0, viem_1.isAddressEqual)(marketParams.collateralToken, marketParams.loanToken);
107
+ const reallocationResult = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
108
+ chainId,
109
+ reallocations,
110
+ targetMarketParams: marketParams,
111
+ penaltyFundingSource: usesSharedFundingToken
112
+ ? "generalAdapter1"
113
+ : "initiator",
114
+ });
115
+ const erc20FundingAmount = amount + (usesSharedFundingToken ? reallocationResult.penaltyAssets : 0n);
96
116
  const actions = [];
97
117
  if (authorizationSignature) {
98
118
  actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
@@ -100,7 +120,7 @@ const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: {
100
120
  actions.push(...(0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
101
121
  chainId,
102
122
  asset: marketParams.collateralToken,
103
- erc20Amount: amount,
123
+ erc20Amount: erc20FundingAmount,
104
124
  nativeAmount: nativeAmount ?? 0n,
105
125
  requirementSignature,
106
126
  }));
@@ -108,12 +128,7 @@ const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: {
108
128
  type: "morphoSupplyCollateral",
109
129
  args: [marketParams, totalCollateral, onBehalf, [], false],
110
130
  });
111
- let reallocationFee = 0n;
112
- if (reallocations && reallocations.length > 0) {
113
- const result = (0, buildReallocationActions_js_1.buildReallocationActions)(reallocations, marketParams);
114
- actions.push(...result.actions);
115
- reallocationFee = result.fee;
116
- }
131
+ actions.push(...reallocationResult.actions);
117
132
  actions.push({
118
133
  type: "morphoBorrow",
119
134
  args: [marketParams, borrowAmount, 0n, minSharePrice, receiver, false],
@@ -134,7 +149,8 @@ const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: {
134
149
  onBehalf,
135
150
  receiver,
136
151
  nativeAmount,
137
- reallocationFee,
152
+ reallocationFee: reallocationResult.fee,
153
+ reallocationPenaltyAssets: reallocationResult.penaltyAssets,
138
154
  },
139
155
  },
140
156
  });
@@ -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
@@ -16,10 +16,11 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
16
16
  * - **By shares** (`assets = 0, shares > 0`): burns an exact share count (typical for a full
17
17
  * supplier position close; immune to interest accrual between tx construction and execution).
18
18
  *
19
- * When `reallocations` are provided, `reallocateTo` actions are prepended to the bundle, moving
20
- * liquidity from other markets into this one via the PublicAllocator before withdrawing.
21
- * Reallocation fees accumulate in `tx.value`. The on-chain `morphoWithdraw` sends the assets
22
- * computed on-chain directly to `receiver`; no skim is required.
19
+ * A `reallocations` plan contains either V1 entries or V2 market/idle entries,
20
+ * never both. The calls run before the withdraw. V1
21
+ * fees accumulate in `tx.value`; V2 penalties are paid in the target loan
22
+ * token and donated to the vaults. The on-chain `morphoWithdraw` sends the
23
+ * assets computed on-chain directly to `receiver`; no skim is required.
23
24
  *
24
25
  * The withdraw is performed on behalf of the transaction initiator (signer) — there is no
25
26
  * separate `onBehalf` field; mirror `blueBorrow`. The entity layer keeps `receiver` aligned
@@ -33,17 +34,23 @@ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
33
34
  * @param params.args.receiver - Address that receives the withdrawn assets.
34
35
  * @param params.args.minSharePrice - Minimum acceptable withdraw share price (in ray). Slippage
35
36
  * protection.
36
- * @param params.args.reallocations - Optional vault reallocations to execute before withdrawing,
37
- * computed by the entity layer.
37
+ * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
38
+ * execute before withdrawing.
38
39
  * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
39
40
  * a `setAuthorizationWithSig` call is prepended to the bundle.
40
41
  * @param params.metadata - Optional analytics metadata attached to the bundle.
41
42
  * @returns A deep-frozen `Transaction<BlueWithdrawAction>` with `to`, `value`, `data`, and
42
43
  * the typed `action` discriminator the simulation layer consumes.
43
- * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, or any reallocation fee
44
- * is negative.
44
+ * @throws {NegativeInputError} when `assets`, `shares`, `minSharePrice`, a V1 fee, or a V2
45
+ * penalty is negative.
45
46
  * @throws {NonPositiveInputError} when both `assets` and `shares` are zero or any reallocation
46
47
  * withdrawal amount is non-positive.
48
+ * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
49
+ * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
50
+ * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
51
+ * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
52
+ * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
53
+ * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
47
54
  * @throws {MutuallyExclusiveWithdrawAmountsError} when both `assets` and `shares` are non-zero.
48
55
  * @throws {EmptyReallocationWithdrawalsError} when any reallocation has no withdrawals.
49
56
  * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references
@@ -86,23 +93,20 @@ const blueWithdraw = ({ market: { chainId, marketParams }, args: { assets, share
86
93
  throw new index_js_3.NegativeInputError("minSharePrice", minSharePrice);
87
94
  }
88
95
  const actions = [];
89
- let reallocationFee = 0n;
90
96
  if (authorizationSignature) {
91
97
  actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
92
98
  }
93
- if (reallocations && reallocations.length > 0) {
94
- const result = (0, buildReallocationActions_js_1.buildReallocationActions)(reallocations, marketParams);
95
- actions.push(...result.actions);
96
- reallocationFee = result.fee;
97
- }
99
+ const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
100
+ chainId,
101
+ reallocations,
102
+ targetMarketParams: marketParams,
103
+ });
104
+ actions.push(...reallocationActions);
98
105
  actions.push({
99
106
  type: "morphoWithdraw",
100
107
  args: [marketParams, assets, shares, minSharePrice, receiver, false],
101
108
  });
102
- let tx = {
103
- ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
104
- value: reallocationFee,
105
- };
109
+ let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
106
110
  if (metadata) {
107
111
  tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
108
112
  }
@@ -117,6 +121,7 @@ const blueWithdraw = ({ market: { chainId, marketParams }, args: { assets, share
117
121
  receiver,
118
122
  minSharePrice,
119
123
  reallocationFee,
124
+ reallocationPenaltyAssets,
120
125
  },
121
126
  },
122
127
  });
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getRequirementsApproval = void 0;
4
+ const viem_1 = require("viem");
4
5
  const constant_js_1 = require("../../helpers/constant.js");
5
6
  const index_js_1 = require("../../types/index.js");
6
7
  const encodeErc20Approval_js_1 = require("./encode/encodeErc20Approval.js");
@@ -50,7 +51,7 @@ const getRequirementsApproval = (params) => {
50
51
  }
51
52
  const approvals = [];
52
53
  if (allowances < spendAmount) {
53
- if (constant_js_1.APPROVE_ONLY_ONCE_TOKENS[chainId]?.includes(address) &&
54
+ if (constant_js_1.APPROVE_ONLY_ONCE_TOKENS[chainId]?.some((token) => (0, viem_1.isAddressEqual)(token, address)) &&
54
55
  allowances > 0n) {
55
56
  approvals.push((0, encodeErc20Approval_js_1.encodeErc20Approval)({
56
57
  token: address,
@@ -650,6 +650,123 @@ export declare namespace BundlerAction {
650
650
  * ```
651
651
  */
652
652
  function publicAllocatorReallocateTo(chainId: number, vault: Address, fee: bigint, withdrawals: InputReallocation[], supplyMarketParams: InputMarketParams, skipRevert?: boolean): BundlerCall[];
653
+ /**
654
+ * Encodes a Vault V2 Blue Public Allocator market-to-market reallocation.
655
+ *
656
+ * @remarks Bundler3 must already hold the computed penalty assets. The
657
+ * high-level Blue builders add the corresponding GeneralAdapter1 transfer.
658
+ *
659
+ * @param chainId - Chain whose canonical Blue Public Allocator is called.
660
+ * @param vault - Vault whose liquidity is reallocated.
661
+ * @param deallocateAdapter - Vault V2 adapter supplying the source market.
662
+ * @param deallocateMarket - Source Morpho Blue market parameters.
663
+ * @param allocateAdapter - Vault V2 adapter supplying the target market.
664
+ * @param allocateMarket - Target Morpho Blue market parameters.
665
+ * @param assets - Assets to reallocate, bounded by `uint128` by the high-level action.
666
+ * @param penalty - Vault-configured proportional penalty, scaled by WAD.
667
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
668
+ * @returns A zero reset and exact approval when needed, then the allocator call.
669
+ * @throws {BundlerErrors.UnexpectedAction} when the chain has no Blue Public Allocator deployment.
670
+ * @throws {BundlerErrors.SkippableAllocatorPenalty} when `skipRevert` is true and a token approval is required.
671
+ * @example
672
+ * ```ts
673
+ * import { ChainId, type InputMarketParams } from "@morpho-org/blue-sdk";
674
+ * import {
675
+ * BundlerAction,
676
+ * type BundlerCall,
677
+ * } from "@morpho-org/morpho-sdk/bundler";
678
+ * import type { Address } from "viem";
679
+ *
680
+ * const keyrockUsdcVault =
681
+ * "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145" satisfies Address;
682
+ * const sourceAdapterFixture =
683
+ * "0x70997970C51812dc3A010C7d01b50e0d17dc79C8" satisfies Address;
684
+ * const targetAdapterFixture =
685
+ * "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" satisfies Address;
686
+ * const usdc = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" satisfies Address;
687
+ * const weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" satisfies Address;
688
+ * const wbtc = "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599" satisfies Address;
689
+ * const ethUsdOracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" satisfies Address;
690
+ * const adaptiveCurveIrm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC" satisfies Address;
691
+ * const sourceMarket = {
692
+ * loanToken: usdc,
693
+ * collateralToken: weth,
694
+ * oracle: ethUsdOracle,
695
+ * irm: adaptiveCurveIrm,
696
+ * lltv: 860_000_000_000_000_000n,
697
+ * } satisfies InputMarketParams;
698
+ * const targetMarket = {
699
+ * ...sourceMarket,
700
+ * collateralToken: wbtc,
701
+ * } satisfies InputMarketParams;
702
+ *
703
+ * const calls: BundlerCall[] = BundlerAction.vaultV2BluePublicAllocatorReallocate(
704
+ * ChainId.EthMainnet,
705
+ * keyrockUsdcVault,
706
+ * sourceAdapterFixture,
707
+ * sourceMarket,
708
+ * targetAdapterFixture,
709
+ * targetMarket,
710
+ * 1_000_000n,
711
+ * 1_000_000_000_000_000n,
712
+ * );
713
+ * // Bundler3 resets and approves 1_000 USDC units, then calls `reallocate` with zero native value.
714
+ * ```
715
+ */
716
+ function vaultV2BluePublicAllocatorReallocate(chainId: number, vault: Address, deallocateAdapter: Address, deallocateMarket: InputMarketParams, allocateAdapter: Address, allocateMarket: InputMarketParams, assets: bigint, penalty: bigint, skipRevert?: boolean): BundlerCall[];
717
+ /**
718
+ * Encodes a Vault V2 Blue Public Allocator allocation from vault idle liquidity.
719
+ *
720
+ * @remarks Bundler3 must already hold the computed penalty assets. The
721
+ * high-level Blue builders add the corresponding GeneralAdapter1 transfer.
722
+ *
723
+ * @param chainId - Chain whose canonical Blue Public Allocator is called.
724
+ * @param vault - Vault whose idle liquidity is allocated.
725
+ * @param adapter - Vault V2 adapter supplying the target market.
726
+ * @param market - Target Morpho Blue market parameters.
727
+ * @param assets - Assets to allocate, bounded by `uint128` by the high-level action.
728
+ * @param penalty - Vault-configured proportional penalty, scaled by WAD.
729
+ * @param skipRevert - Whether Bundler3 should tolerate a revert.
730
+ * @returns A zero reset and exact approval when needed, then the allocator call.
731
+ * @throws {BundlerErrors.UnexpectedAction} when the chain has no Blue Public Allocator deployment.
732
+ * @throws {BundlerErrors.SkippableAllocatorPenalty} when `skipRevert` is true and a token approval is required.
733
+ * @example
734
+ * ```ts
735
+ * import { ChainId, type InputMarketParams } from "@morpho-org/blue-sdk";
736
+ * import {
737
+ * BundlerAction,
738
+ * type BundlerCall,
739
+ * } from "@morpho-org/morpho-sdk/bundler";
740
+ * import type { Address } from "viem";
741
+ *
742
+ * const keyrockUsdcVault =
743
+ * "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145" satisfies Address;
744
+ * const targetAdapterFixture =
745
+ * "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC" satisfies Address;
746
+ * const usdc = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" satisfies Address;
747
+ * const weth = "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2" satisfies Address;
748
+ * const ethUsdOracle = "0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419" satisfies Address;
749
+ * const adaptiveCurveIrm = "0x870aC11D48B15DB9a138Cf899d20F13F79Ba00BC" satisfies Address;
750
+ * const targetMarket = {
751
+ * loanToken: usdc,
752
+ * collateralToken: weth,
753
+ * oracle: ethUsdOracle,
754
+ * irm: adaptiveCurveIrm,
755
+ * lltv: 860_000_000_000_000_000n,
756
+ * } satisfies InputMarketParams;
757
+ *
758
+ * const calls: BundlerCall[] = BundlerAction.vaultV2BluePublicAllocatorAllocateFromIdle(
759
+ * ChainId.EthMainnet,
760
+ * keyrockUsdcVault,
761
+ * targetAdapterFixture,
762
+ * targetMarket,
763
+ * 1_000_000n,
764
+ * 1_000_000_000_000_000n,
765
+ * );
766
+ * // Bundler3 resets and approves 1_000 USDC units, then calls `allocateFromIdle` with zero native value.
767
+ * ```
768
+ */
769
+ function vaultV2BluePublicAllocatorAllocateFromIdle(chainId: number, vault: Address, adapter: Address, market: InputMarketParams, assets: bigint, penalty: bigint, skipRevert?: boolean): BundlerCall[];
653
770
  /**
654
771
  * Encodes a GeneralAdapter1 native-token wrap call.
655
772
  *