@morpho-org/morpho-sdk 8.1.0 → 8.2.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.
@@ -142,9 +142,13 @@ Get `positionData` from
142
142
  `midnight.getPositionData({ marketId: marketData.id, accountAddress })`. For each collateral index,
143
143
  read `price()` from the oracle at `marketData.params.collateralParams[i].oracle` with viem's
144
144
  `readContract`. Prices use `ORACLE_PRICE_SCALE` and must be in the same index order as the market's
145
- collateral parameters. Pass `collateralPrices: []` only when the SDK's conservative post-operation
146
- debt is zero, such as after a `full` repay, a repayment units target covering `positionData.debt`,
147
- or `minUnits` / `repay.assets` covering it. Otherwise, pass the prices. For example:
145
+ collateral parameters. `takeBorrow` and `supplyCollateralTakeBorrow` always need prices, because
146
+ debt after a borrow is always positive. `takeRepayWithdrawCollateral` and
147
+ `repayWithdrawCollateral` need prices only when `collateralWithdrawals` is non-empty and the SDK's
148
+ conservative post-operation debt is positive. For these two methods, pass `collateralPrices: []`
149
+ when there is no collateral withdrawal, including a partial repayment that leaves debt, or when the
150
+ conservative post-operation debt is zero, such as after a `full` repay, a repayment units target
151
+ covering `positionData.debt`, or `minUnits` / `repay.assets` covering it. For example:
148
152
 
149
153
  ```ts
150
154
  midnight.takeBorrow({
package/README.md CHANGED
@@ -78,6 +78,16 @@ prerequisites.
78
78
  - **`getRequirements()`** — async; the on-chain prerequisites to satisfy first: ERC-20 approvals, permit / Permit2 signatures, Morpho authorization, or (for Midnight) operator authorization.
79
79
  - **`buildTx(signatures?)`** — synchronous; the final, deep-frozen viem transaction. Pass any signatures collected from the requirements.
80
80
 
81
+ Every transaction carries `tx.action` — typed metadata describing the encoded call (`type` plus
82
+ the normalized `args`, including `referralFeeAssets`: the exact referral-fee amount the
83
+ BlueBundlesV1 call charges, where derivable; it is omitted in exact-shares mode
84
+ (`blueWithdraw`, `blueRepay` and `blueRepayWithdrawCollateral` with a shares input),
85
+ where the underlying amount is resolved at execution. On the repay actions it is set
86
+ only for an exact-assets repay (`repayAssets > 0n`), so it is also omitted when
87
+ `blueRepayWithdrawCollateral` has no repay leg).
88
+ `@morpho-org/evm-simulation`'s `toSimulationLimits` consumes this metadata to derive simulation
89
+ limits from an action.
90
+
81
91
  ```typescript
82
92
  const vaultData = await vault.getData();
83
93
  const { buildTx, getRequirements } = vault.deposit({ amount, userAddress, vaultData });
@@ -175,6 +175,7 @@ const blueRepayWithdrawCollateral = (params) => {
175
175
  nativeAmount: value > 0n ? value : undefined,
176
176
  referralFeePct,
177
177
  referralFeeRecipient,
178
+ referralFeeAssets: repayAssets > 0n ? minimumRepayAssets - repayAssets : undefined,
178
179
  deadline: params.args.deadline,
179
180
  },
180
181
  },
@@ -5,7 +5,8 @@ const viem_1 = require("viem");
5
5
  const abis_js_1 = require("../../abis.js");
6
6
  const validate_js_1 = require("../../helpers/validate.js");
7
7
  const index_js_1 = require("../../types/index.js");
8
- const common_js_1 = require("./common.js");
8
+ const common_js_1 = require("../bundles/common.js");
9
+ const common_js_2 = require("./common.js");
9
10
  /**
10
11
  * Encodes a direct BlueBundlesV1 loan-asset supply transaction.
11
12
  *
@@ -74,22 +75,22 @@ const blueSupply = (params) => {
74
75
  referralFeeRecipient: params.args.referralFeeRecipient,
75
76
  metadata: params.metadata,
76
77
  };
77
- const { referralFeePct, referralFeeRecipient } = (0, common_js_1.normalizeBlueBundlesV1CommonParams)(common);
78
- const value = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
78
+ const { referralFeePct, referralFeeRecipient } = (0, common_js_2.normalizeBlueBundlesV1CommonParams)(common);
79
+ const value = (0, common_js_2.validateBlueBundlesV1NativeFunding)({
79
80
  chainId,
80
81
  token: marketParams.loanToken,
81
82
  fundedAmount: assets,
82
83
  nativeAmount: params.args.nativeAmount,
83
84
  requirementSignature,
84
85
  });
85
- const tokenPermit = (0, common_js_1.getBlueBundlesV1TokenPermit)({
86
+ const tokenPermit = (0, common_js_2.getBlueBundlesV1TokenPermit)({
86
87
  chainId,
87
88
  userAddress,
88
89
  token: marketParams.loanToken,
89
90
  amount: assets,
90
91
  requirementSignature,
91
92
  });
92
- return (0, common_js_1.finalizeBlueBundlesV1Transaction)({
93
+ return (0, common_js_2.finalizeBlueBundlesV1Transaction)({
93
94
  common,
94
95
  value,
95
96
  data: (0, viem_1.encodeFunctionData)({
@@ -113,6 +114,7 @@ const blueSupply = (params) => {
113
114
  nativeAmount: value > 0n ? value : undefined,
114
115
  referralFeePct,
115
116
  referralFeeRecipient,
117
+ referralFeeAssets: (0, common_js_1.getBundlesReferralFeeAssets)(assets, referralFeePct),
116
118
  deadline: params.args.deadline,
117
119
  },
118
120
  },
@@ -5,7 +5,8 @@ const viem_1 = require("viem");
5
5
  const abis_js_1 = require("../../abis.js");
6
6
  const validate_js_1 = require("../../helpers/validate.js");
7
7
  const index_js_1 = require("../../types/index.js");
8
- const common_js_1 = require("./common.js");
8
+ const common_js_1 = require("../bundles/common.js");
9
+ const common_js_2 = require("./common.js");
9
10
  /**
10
11
  * Encodes a direct BlueBundlesV1 collateral supply and/or borrow transaction.
11
12
  *
@@ -104,28 +105,28 @@ const blueSupplyCollateralBorrow = (params) => {
104
105
  referralFeeRecipient: params.args.referralFeeRecipient,
105
106
  metadata: params.metadata,
106
107
  };
107
- const { referralFeePct, referralFeeRecipient } = (0, common_js_1.normalizeBlueBundlesV1CommonParams)(common);
108
- const value = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
108
+ const { referralFeePct, referralFeeRecipient } = (0, common_js_2.normalizeBlueBundlesV1CommonParams)(common);
109
+ const value = (0, common_js_2.validateBlueBundlesV1NativeFunding)({
109
110
  chainId,
110
111
  token: marketParams.collateralToken,
111
112
  fundedAmount: collateralAssets,
112
113
  nativeAmount: params.args.nativeAmount,
113
114
  requirementSignature,
114
115
  });
115
- const collateralPermit = (0, common_js_1.getBlueBundlesV1TokenPermit)({
116
+ const collateralPermit = (0, common_js_2.getBlueBundlesV1TokenPermit)({
116
117
  chainId,
117
118
  userAddress,
118
119
  token: marketParams.collateralToken,
119
120
  amount: collateralAssets,
120
121
  requirementSignature,
121
122
  });
122
- const signedAuthorization = (0, common_js_1.getBlueBundlesV1SignedAuthorization)({
123
+ const signedAuthorization = (0, common_js_2.getBlueBundlesV1SignedAuthorization)({
123
124
  chainId,
124
125
  userAddress,
125
126
  authorizationSignature,
126
127
  });
127
- const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)(reallocations, marketParams);
128
- const reallocationPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
128
+ const publicAllocations = (0, common_js_2.getBlueBundlesV1PublicAllocations)(reallocations, marketParams);
129
+ const reallocationPenaltyAssets = (0, common_js_2.getBlueBundlesV1PenaltyAssets)(publicAllocations);
129
130
  if (reallocationPenaltyAssets > borrowAssets) {
130
131
  throw new index_js_1.InputExceedsMaxError({
131
132
  field: "reallocationPenaltyAssets",
@@ -133,7 +134,7 @@ const blueSupplyCollateralBorrow = (params) => {
133
134
  max: borrowAssets,
134
135
  });
135
136
  }
136
- return (0, common_js_1.finalizeBlueBundlesV1Transaction)({
137
+ return (0, common_js_2.finalizeBlueBundlesV1Transaction)({
137
138
  common,
138
139
  value,
139
140
  data: (0, viem_1.encodeFunctionData)({
@@ -165,6 +166,7 @@ const blueSupplyCollateralBorrow = (params) => {
165
166
  reallocationPenaltyAssets,
166
167
  referralFeePct,
167
168
  referralFeeRecipient,
169
+ referralFeeAssets: (0, common_js_1.getBundlesReferralFeeAssets)(borrowAssets - reallocationPenaltyAssets, referralFeePct),
168
170
  deadline: params.args.deadline,
169
171
  },
170
172
  },
@@ -5,7 +5,8 @@ const viem_1 = require("viem");
5
5
  const abis_js_1 = require("../../abis.js");
6
6
  const validate_js_1 = require("../../helpers/validate.js");
7
7
  const index_js_1 = require("../../types/index.js");
8
- const common_js_1 = require("./common.js");
8
+ const common_js_1 = require("../bundles/common.js");
9
+ const common_js_2 = require("./common.js");
9
10
  /**
10
11
  * Encodes a direct BlueBundlesV1 loan-asset withdrawal transaction.
11
12
  *
@@ -82,14 +83,14 @@ const blueWithdraw = (params) => {
82
83
  referralFeeRecipient: params.args.referralFeeRecipient,
83
84
  metadata: params.metadata,
84
85
  };
85
- const { referralFeePct, referralFeeRecipient } = (0, common_js_1.normalizeBlueBundlesV1CommonParams)(common);
86
- const signedAuthorization = (0, common_js_1.getBlueBundlesV1SignedAuthorization)({
86
+ const { referralFeePct, referralFeeRecipient } = (0, common_js_2.normalizeBlueBundlesV1CommonParams)(common);
87
+ const signedAuthorization = (0, common_js_2.getBlueBundlesV1SignedAuthorization)({
87
88
  chainId,
88
89
  userAddress,
89
90
  authorizationSignature,
90
91
  });
91
- const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)([...(params.args.reallocations ?? [])], marketParams);
92
- const reallocationPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
92
+ const publicAllocations = (0, common_js_2.getBlueBundlesV1PublicAllocations)([...(params.args.reallocations ?? [])], marketParams);
93
+ const reallocationPenaltyAssets = (0, common_js_2.getBlueBundlesV1PenaltyAssets)(publicAllocations);
93
94
  if (withdrawAssets > 0n && reallocationPenaltyAssets > withdrawAssets) {
94
95
  throw new index_js_1.InputExceedsMaxError({
95
96
  field: "reallocationPenaltyAssets",
@@ -97,7 +98,7 @@ const blueWithdraw = (params) => {
97
98
  max: withdrawAssets,
98
99
  });
99
100
  }
100
- return (0, common_js_1.finalizeBlueBundlesV1Transaction)({
101
+ return (0, common_js_2.finalizeBlueBundlesV1Transaction)({
101
102
  common,
102
103
  value: 0n,
103
104
  data: (0, viem_1.encodeFunctionData)({
@@ -125,6 +126,9 @@ const blueWithdraw = (params) => {
125
126
  reallocationPenaltyAssets,
126
127
  referralFeePct,
127
128
  referralFeeRecipient,
129
+ referralFeeAssets: withdrawAssets > 0n
130
+ ? (0, common_js_1.getBundlesReferralFeeAssets)(withdrawAssets - reallocationPenaltyAssets, referralFeePct)
131
+ : undefined,
128
132
  deadline: params.args.deadline,
129
133
  },
130
134
  },
@@ -155,9 +155,10 @@ export interface MidnightPositionHealthParams {
155
155
  /** Owner-bound snapshot returned by `getPositionData`. */
156
156
  readonly positionData: AccrualPosition;
157
157
  /** Values from `price()` on each `marketData.params.collateralParams[i].oracle`,
158
- * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE`. An empty array is
159
- * safe only when the SDK's conservative post-operation debt is zero, such as after a `full` repay,
160
- * a repayment units target covering `positionData.debt`, or `minUnits`/`repay.assets` covering it.
158
+ * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE`. Borrow methods always
159
+ * need prices. `takeRepayWithdrawCollateral` and `repayWithdrawCollateral` need them only when
160
+ * `collateralWithdrawals` is non-empty and the SDK's conservative post-operation debt is positive;
161
+ * otherwise an empty array is safe.
161
162
  */
162
163
  readonly collateralPrices: readonly bigint[];
163
164
  }
@@ -369,12 +369,18 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
369
369
  * (two hours by default; `0n` disables it). When an operation's plan would
370
370
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
371
  * BluePublicAllocator cap, the plan is reduced to the larger of the
372
- * operation's absolute shortfall and what vaults below their cap moved. The
373
- * kept headroom absorbs other allocations up to that share of the cap landing
374
- * before inclusion. The plan uses the full cap only when the shortfall needs
375
- * it, and can then still revert if another allocation lands first. A plan of
376
- * only the shortfall leaves the market fully utilized, so a competing borrow
377
- * or withdraw landing first can also make it revert. For market-source reallocations
372
+ * operation's absolute shortfall and what unbound legs moved (legs that
373
+ * neither come within the headroom of an allocator cap nor take nearly all
374
+ * of their source vault's idle). The kept headroom absorbs other allocations
375
+ * up to that share of the cap landing before inclusion. The plan uses the
376
+ * full cap only when the shortfall needs it, and can then still revert if
377
+ * another allocation lands first.
378
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
379
+ * vault's starting idle are bound the same way, so an operation without
380
+ * shortfall whose plan draws only on such idle plans no reallocation.
381
+ * A plan of only the shortfall leaves the market fully utilized, so a
382
+ * competing borrow or withdraw landing first can also make it revert. For
383
+ * market-source reallocations
378
384
  * the source position's interest is also reserved on cap ids shared with the
379
385
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
380
386
  * or allocator capacity are skipped before projecting source interest. The
@@ -570,12 +570,18 @@ class VaultV2BlueReallocationData {
570
570
  * (two hours by default; `0n` disables it). When an operation's plan would
571
571
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
572
572
  * BluePublicAllocator cap, the plan is reduced to the larger of the
573
- * operation's absolute shortfall and what vaults below their cap moved. The
574
- * kept headroom absorbs other allocations up to that share of the cap landing
575
- * before inclusion. The plan uses the full cap only when the shortfall needs
576
- * it, and can then still revert if another allocation lands first. A plan of
577
- * only the shortfall leaves the market fully utilized, so a competing borrow
578
- * or withdraw landing first can also make it revert. For market-source reallocations
573
+ * operation's absolute shortfall and what unbound legs moved (legs that
574
+ * neither come within the headroom of an allocator cap nor take nearly all
575
+ * of their source vault's idle). The kept headroom absorbs other allocations
576
+ * up to that share of the cap landing before inclusion. The plan uses the
577
+ * full cap only when the shortfall needs it, and can then still revert if
578
+ * another allocation lands first.
579
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
580
+ * vault's starting idle are bound the same way, so an operation without
581
+ * shortfall whose plan draws only on such idle plans no reallocation.
582
+ * A plan of only the shortfall leaves the market fully utilized, so a
583
+ * competing borrow or withdraw landing first can also make it revert. For
584
+ * market-source reallocations
579
585
  * the source position's interest is also reserved on cap ids shared with the
580
586
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
581
587
  * or allocator capacity are skipped before projecting source interest. The
@@ -736,29 +742,32 @@ class VaultV2BlueReallocationData {
736
742
  }
737
743
  // The fallback pass only runs when the plan moves exactly the absolute
738
744
  // shortfall, which a reduced plan would move anyway.
739
- const capBoundTargets = friendly.allocatorCapBoundTargets;
745
+ const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
746
+ const idleBoundVaults = friendly.idleBoundVaults;
740
747
  let reallocatedAssets = 0n;
741
748
  let unboundAssets = 0n;
742
- for (const { vault, to, assets } of reallocations) {
749
+ for (const { vault, from, to, assets } of reallocations) {
743
750
  reallocatedAssets += assets;
744
751
  const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
745
- if (!capBoundTargets.has(key))
752
+ if (!allocatorCapBoundTargets.has(key) &&
753
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
746
754
  unboundAssets += assets;
747
755
  }
748
756
  return {
749
757
  reallocations,
750
758
  data,
751
- capBound: capBoundTargets.size > 0,
759
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
752
760
  reallocatedAssets,
753
761
  unboundAssets,
754
762
  };
755
763
  };
756
- // A leg that fills an allocator cap reverts once any other allocation to
757
- // that market lands first. A cap-bound plan therefore moves only the
758
- // operation's shortfall, or what vaults below their cap already moved.
764
+ // A leg that fills an allocator cap, or idle legs that together take
765
+ // (nearly) all of a source vault's starting idle, revert once another
766
+ // allocation lands first. A bound plan therefore moves only the operation's
767
+ // shortfall, or what unbound legs moved.
759
768
  const target = plan(requiredAssets, allocatorCapHeadroom);
760
769
  let selected = target;
761
- if (allocatorCapHeadroom > 0n && target.capBound) {
770
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
762
771
  selected = plan(absoluteShortfall > target.unboundAssets
763
772
  ? absoluteShortfall
764
773
  : target.unboundAssets, allocatorCapHeadroom);
@@ -793,6 +802,7 @@ class VaultV2BlueReallocationData {
793
802
  data: this,
794
803
  context,
795
804
  allocatorCapBoundTargets: new Set(),
805
+ idleBoundVaults: new Set(),
796
806
  };
797
807
  this.getMarket(marketId);
798
808
  const timestamp = options.timestamp == null
@@ -812,6 +822,9 @@ class VaultV2BlueReallocationData {
812
822
  const activeAdaptersCache = new Map();
813
823
  let remainingAssets = maxAssets;
814
824
  const allocatorCapBoundTargets = new Set();
825
+ const idleBoundVaults = new Set();
826
+ const initialIdleAssets = new Map();
827
+ const idleTakenAssets = new Map();
815
828
  // Onchain, market interest is booked once at transaction start, on pre-plan
816
829
  // positions at pre-plan rates, and stays on touched positions' cap ids.
817
830
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -880,6 +893,9 @@ class VaultV2BlueReallocationData {
880
893
  const availableIdleAssets = blue_sdk_1.MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
881
894
  ? 0n
882
895
  : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
896
+ const vaultAddressKey = vaultAddress.toLowerCase();
897
+ if (!initialIdleAssets.has(vaultAddressKey))
898
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
883
899
  let activeAdapters = activeAdaptersCache.get(vaultAddress);
884
900
  if (activeAdapters == null) {
885
901
  activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
@@ -1104,11 +1120,22 @@ class VaultV2BlueReallocationData {
1104
1120
  data,
1105
1121
  context: simulationContext,
1106
1122
  allocatorCapBoundTargets,
1123
+ idleBoundVaults,
1107
1124
  };
1108
1125
  const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1109
1126
  if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1110
1127
  // BluePublicAllocator caps are per vault and target adapter.
1111
1128
  allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1129
+ if (acceptedReallocation.from.type === "idle") {
1130
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1131
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1132
+ idleTakenAssets.set(vaultKey, taken);
1133
+ // Candidates always record this; a missing entry counts the vault as bound.
1134
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1135
+ if (taken >=
1136
+ blue_sdk_1.MathLib.zeroFloorSub(initial, blue_sdk_1.MathLib.wMulUp(initial, allocatorCapHeadroom)))
1137
+ idleBoundVaults.add(vaultKey);
1138
+ }
1112
1139
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1113
1140
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1114
1141
  if (touchedVaultPairs == null) {
@@ -1138,6 +1165,7 @@ class VaultV2BlueReallocationData {
1138
1165
  data,
1139
1166
  context: simulationContext,
1140
1167
  allocatorCapBoundTargets,
1168
+ idleBoundVaults,
1141
1169
  };
1142
1170
  }
1143
1171
  /**
@@ -258,6 +258,8 @@ export interface BlueSupplyAction extends BaseAction<"blueSupply", {
258
258
  readonly nativeAmount?: bigint;
259
259
  readonly referralFeePct: bigint;
260
260
  readonly referralFeeRecipient: Address;
261
+ /** Fee deducted from `assets` before supplying: floor(assets * referralFeePct / WAD). */
262
+ readonly referralFeeAssets: bigint;
261
263
  readonly deadline: bigint;
262
264
  }> {
263
265
  }
@@ -271,6 +273,12 @@ export interface BlueWithdrawAction extends BaseAction<"blueWithdraw", {
271
273
  readonly reallocationPenaltyAssets: bigint;
272
274
  readonly referralFeePct: bigint;
273
275
  readonly referralFeeRecipient: Address;
276
+ /**
277
+ * Fee deducted from net withdrawal proceeds:
278
+ * floor((withdrawAssets - reallocationPenaltyAssets) * referralFeePct / WAD); omitted in
279
+ * exact-shares mode, where the received amount is resolved at execution.
280
+ */
281
+ readonly referralFeeAssets?: bigint;
274
282
  readonly deadline: bigint;
275
283
  }> {
276
284
  }
@@ -285,6 +293,12 @@ type BlueSupplyCollateralBorrowActionArgs = {
285
293
  readonly reallocationPenaltyAssets: bigint;
286
294
  readonly referralFeePct: bigint;
287
295
  readonly referralFeeRecipient: Address;
296
+ /**
297
+ * Fee deducted from the borrow leg's net proceeds:
298
+ * floor((borrowAssets - reallocationPenaltyAssets) * referralFeePct / WAD); zero when
299
+ * `borrowAssets` is zero. The collateral-supply leg carries no fee.
300
+ */
301
+ readonly referralFeeAssets: bigint;
288
302
  readonly deadline: bigint;
289
303
  };
290
304
  /** Metadata for a direct BlueBundlesV1 collateral supply. */
@@ -307,6 +321,14 @@ type BlueRepayWithdrawCollateralActionArgs = {
307
321
  readonly nativeAmount?: bigint;
308
322
  readonly referralFeePct: bigint;
309
323
  readonly referralFeeRecipient: Address;
324
+ /**
325
+ * Fee charged on top of the repaid assets, inside `maxRepayAssets`:
326
+ * floor(repayAssets * referralFeePct / (WAD - referralFeePct)); set only for an
327
+ * exact-assets repay (`repayAssets > 0n`), and omitted in exact-shares mode or
328
+ * when there is no repay leg, where the repaid amount is resolved at execution
329
+ * or never repaid.
330
+ */
331
+ readonly referralFeeAssets?: bigint;
310
332
  readonly deadline: bigint;
311
333
  };
312
334
  /** Metadata for a direct BlueBundlesV1 repayment. */
@@ -28,15 +28,20 @@ export interface VaultV2BluePublicAllocatorOptions {
28
28
  * Share of each target-market BluePublicAllocator cap, scaled by WAD, that
29
29
  * operation planning keeps free. When a reallocation toward the utilization
30
30
  * target would come within this headroom of the cap, the plan is reduced to
31
- * the larger of the operation's absolute shortfall and what vaults below
32
- * their cap were already moving. A plan of only the shortfall leaves the
33
- * market fully utilized, so a competing borrow or withdraw landing first can
34
- * still make it revert. If the shortfall cannot be covered while keeping the
35
- * headroom, the plan uses the full cap, first for the shortfall only and
36
- * then toward the utilization target if that is still short.
31
+ * the larger of the operation's absolute shortfall and what unbound legs
32
+ * were already moving (legs that neither come within the headroom of an
33
+ * allocator cap nor take nearly all of their source vault's idle). A plan of
34
+ * only the shortfall leaves the market fully utilized, so a competing borrow
35
+ * or withdraw landing first can still make it revert. If the shortfall cannot
36
+ * be covered while keeping the headroom, the plan uses the full cap, first for
37
+ * the shortfall only and then toward the utilization target if that is still
38
+ * short.
39
+ * The same share marks idle legs as bound: idle legs that together leave at
40
+ * most this share of a source vault's starting idle reduce the plan the same
41
+ * way, since any idle withdrawal landing first would make it revert.
37
42
  * Discovery plans, `getPublicReallocationLiquidity` and
38
43
  * `getAvailableLiquidityToUtilization` ignore it and use the full cap.
39
- * Must not exceed WAD (100%). Set to `0n` to disable.
44
+ * Must not exceed WAD (100%). Set to `0n` to disable both rules.
40
45
  *
41
46
  * @default DEFAULT_ALLOCATOR_CAP_HEADROOM (1%)
42
47
  */
@@ -172,6 +172,7 @@ export const blueRepayWithdrawCollateral = (params) => {
172
172
  nativeAmount: value > 0n ? value : undefined,
173
173
  referralFeePct,
174
174
  referralFeeRecipient,
175
+ referralFeeAssets: repayAssets > 0n ? minimumRepayAssets - repayAssets : undefined,
175
176
  deadline: params.args.deadline,
176
177
  },
177
178
  },
@@ -2,6 +2,7 @@ import { encodeFunctionData } from "viem";
2
2
  import { blueBundlesV1Abi } from "../../abis.js";
3
3
  import { validateUint256Field } from "../../helpers/validate.js";
4
4
  import { NonPositiveInputError } from "../../types/index.js";
5
+ import { getBundlesReferralFeeAssets } from "../bundles/common.js";
5
6
  import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1TokenPermit, normalizeBlueBundlesV1CommonParams, validateBlueBundlesV1NativeFunding, } from "./common.js";
6
7
  /**
7
8
  * Encodes a direct BlueBundlesV1 loan-asset supply transaction.
@@ -110,6 +111,7 @@ export const blueSupply = (params) => {
110
111
  nativeAmount: value > 0n ? value : undefined,
111
112
  referralFeePct,
112
113
  referralFeeRecipient,
114
+ referralFeeAssets: getBundlesReferralFeeAssets(assets, referralFeePct),
113
115
  deadline: params.args.deadline,
114
116
  },
115
117
  },
@@ -2,6 +2,7 @@ import { encodeFunctionData } from "viem";
2
2
  import { blueBundlesV1Abi } from "../../abis.js";
3
3
  import { validateUint256Field } from "../../helpers/validate.js";
4
4
  import { InputExceedsMaxError, NonPositiveInputError, ReallocationsRequireBorrowError, UnexpectedRequirementSignatureError, } from "../../types/index.js";
5
+ import { getBundlesReferralFeeAssets } from "../bundles/common.js";
5
6
  import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1SignedAuthorization, getBlueBundlesV1TokenPermit, normalizeBlueBundlesV1CommonParams, validateBlueBundlesV1NativeFunding, } from "./common.js";
6
7
  /**
7
8
  * Encodes a direct BlueBundlesV1 collateral supply and/or borrow transaction.
@@ -162,6 +163,7 @@ export const blueSupplyCollateralBorrow = (params) => {
162
163
  reallocationPenaltyAssets,
163
164
  referralFeePct,
164
165
  referralFeeRecipient,
166
+ referralFeeAssets: getBundlesReferralFeeAssets(borrowAssets - reallocationPenaltyAssets, referralFeePct),
165
167
  deadline: params.args.deadline,
166
168
  },
167
169
  },
@@ -2,6 +2,7 @@ import { encodeFunctionData } from "viem";
2
2
  import { blueBundlesV1Abi } from "../../abis.js";
3
3
  import { validateUint256Field } from "../../helpers/validate.js";
4
4
  import { InputExceedsMaxError, MutuallyExclusiveWithdrawAmountsError, NonPositiveInputError, } from "../../types/index.js";
5
+ import { getBundlesReferralFeeAssets } from "../bundles/common.js";
5
6
  import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1SignedAuthorization, normalizeBlueBundlesV1CommonParams, } from "./common.js";
6
7
  /**
7
8
  * Encodes a direct BlueBundlesV1 loan-asset withdrawal transaction.
@@ -122,6 +123,9 @@ export const blueWithdraw = (params) => {
122
123
  reallocationPenaltyAssets,
123
124
  referralFeePct,
124
125
  referralFeeRecipient,
126
+ referralFeeAssets: withdrawAssets > 0n
127
+ ? getBundlesReferralFeeAssets(withdrawAssets - reallocationPenaltyAssets, referralFeePct)
128
+ : undefined,
125
129
  deadline: params.args.deadline,
126
130
  },
127
131
  },
@@ -155,9 +155,10 @@ export interface MidnightPositionHealthParams {
155
155
  /** Owner-bound snapshot returned by `getPositionData`. */
156
156
  readonly positionData: AccrualPosition;
157
157
  /** Values from `price()` on each `marketData.params.collateralParams[i].oracle`,
158
- * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE`. An empty array is
159
- * safe only when the SDK's conservative post-operation debt is zero, such as after a `full` repay,
160
- * a repayment units target covering `positionData.debt`, or `minUnits`/`repay.assets` covering it.
158
+ * indexed like `positionData.collateral` and scaled by `ORACLE_PRICE_SCALE`. Borrow methods always
159
+ * need prices. `takeRepayWithdrawCollateral` and `repayWithdrawCollateral` need them only when
160
+ * `collateralWithdrawals` is non-empty and the SDK's conservative post-operation debt is positive;
161
+ * otherwise an empty array is safe.
161
162
  */
162
163
  readonly collateralPrices: readonly bigint[];
163
164
  }
@@ -369,12 +369,18 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
369
369
  * (two hours by default; `0n` disables it). When an operation's plan would
370
370
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
371
  * BluePublicAllocator cap, the plan is reduced to the larger of the
372
- * operation's absolute shortfall and what vaults below their cap moved. The
373
- * kept headroom absorbs other allocations up to that share of the cap landing
374
- * before inclusion. The plan uses the full cap only when the shortfall needs
375
- * it, and can then still revert if another allocation lands first. A plan of
376
- * only the shortfall leaves the market fully utilized, so a competing borrow
377
- * or withdraw landing first can also make it revert. For market-source reallocations
372
+ * operation's absolute shortfall and what unbound legs moved (legs that
373
+ * neither come within the headroom of an allocator cap nor take nearly all
374
+ * of their source vault's idle). The kept headroom absorbs other allocations
375
+ * up to that share of the cap landing before inclusion. The plan uses the
376
+ * full cap only when the shortfall needs it, and can then still revert if
377
+ * another allocation lands first.
378
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
379
+ * vault's starting idle are bound the same way, so an operation without
380
+ * shortfall whose plan draws only on such idle plans no reallocation.
381
+ * A plan of only the shortfall leaves the market fully utilized, so a
382
+ * competing borrow or withdraw landing first can also make it revert. For
383
+ * market-source reallocations
378
384
  * the source position's interest is also reserved on cap ids shared with the
379
385
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
380
386
  * or allocator capacity are skipped before projecting source interest. The
@@ -567,12 +567,18 @@ export class VaultV2BlueReallocationData {
567
567
  * (two hours by default; `0n` disables it). When an operation's plan would
568
568
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
569
569
  * BluePublicAllocator cap, the plan is reduced to the larger of the
570
- * operation's absolute shortfall and what vaults below their cap moved. The
571
- * kept headroom absorbs other allocations up to that share of the cap landing
572
- * before inclusion. The plan uses the full cap only when the shortfall needs
573
- * it, and can then still revert if another allocation lands first. A plan of
574
- * only the shortfall leaves the market fully utilized, so a competing borrow
575
- * or withdraw landing first can also make it revert. For market-source reallocations
570
+ * operation's absolute shortfall and what unbound legs moved (legs that
571
+ * neither come within the headroom of an allocator cap nor take nearly all
572
+ * of their source vault's idle). The kept headroom absorbs other allocations
573
+ * up to that share of the cap landing before inclusion. The plan uses the
574
+ * full cap only when the shortfall needs it, and can then still revert if
575
+ * another allocation lands first.
576
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
577
+ * vault's starting idle are bound the same way, so an operation without
578
+ * shortfall whose plan draws only on such idle plans no reallocation.
579
+ * A plan of only the shortfall leaves the market fully utilized, so a
580
+ * competing borrow or withdraw landing first can also make it revert. For
581
+ * market-source reallocations
576
582
  * the source position's interest is also reserved on cap ids shared with the
577
583
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
578
584
  * or allocator capacity are skipped before projecting source interest. The
@@ -733,29 +739,32 @@ export class VaultV2BlueReallocationData {
733
739
  }
734
740
  // The fallback pass only runs when the plan moves exactly the absolute
735
741
  // shortfall, which a reduced plan would move anyway.
736
- const capBoundTargets = friendly.allocatorCapBoundTargets;
742
+ const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
743
+ const idleBoundVaults = friendly.idleBoundVaults;
737
744
  let reallocatedAssets = 0n;
738
745
  let unboundAssets = 0n;
739
- for (const { vault, to, assets } of reallocations) {
746
+ for (const { vault, from, to, assets } of reallocations) {
740
747
  reallocatedAssets += assets;
741
748
  const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
742
- if (!capBoundTargets.has(key))
749
+ if (!allocatorCapBoundTargets.has(key) &&
750
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
743
751
  unboundAssets += assets;
744
752
  }
745
753
  return {
746
754
  reallocations,
747
755
  data,
748
- capBound: capBoundTargets.size > 0,
756
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
749
757
  reallocatedAssets,
750
758
  unboundAssets,
751
759
  };
752
760
  };
753
- // A leg that fills an allocator cap reverts once any other allocation to
754
- // that market lands first. A cap-bound plan therefore moves only the
755
- // operation's shortfall, or what vaults below their cap already moved.
761
+ // A leg that fills an allocator cap, or idle legs that together take
762
+ // (nearly) all of a source vault's starting idle, revert once another
763
+ // allocation lands first. A bound plan therefore moves only the operation's
764
+ // shortfall, or what unbound legs moved.
756
765
  const target = plan(requiredAssets, allocatorCapHeadroom);
757
766
  let selected = target;
758
- if (allocatorCapHeadroom > 0n && target.capBound) {
767
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
759
768
  selected = plan(absoluteShortfall > target.unboundAssets
760
769
  ? absoluteShortfall
761
770
  : target.unboundAssets, allocatorCapHeadroom);
@@ -790,6 +799,7 @@ export class VaultV2BlueReallocationData {
790
799
  data: this,
791
800
  context,
792
801
  allocatorCapBoundTargets: new Set(),
802
+ idleBoundVaults: new Set(),
793
803
  };
794
804
  this.getMarket(marketId);
795
805
  const timestamp = options.timestamp == null
@@ -809,6 +819,9 @@ export class VaultV2BlueReallocationData {
809
819
  const activeAdaptersCache = new Map();
810
820
  let remainingAssets = maxAssets;
811
821
  const allocatorCapBoundTargets = new Set();
822
+ const idleBoundVaults = new Set();
823
+ const initialIdleAssets = new Map();
824
+ const idleTakenAssets = new Map();
812
825
  // Onchain, market interest is booked once at transaction start, on pre-plan
813
826
  // positions at pre-plan rates, and stays on touched positions' cap ids.
814
827
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -877,6 +890,9 @@ export class VaultV2BlueReallocationData {
877
890
  const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
878
891
  ? 0n
879
892
  : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
893
+ const vaultAddressKey = vaultAddress.toLowerCase();
894
+ if (!initialIdleAssets.has(vaultAddressKey))
895
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
880
896
  let activeAdapters = activeAdaptersCache.get(vaultAddress);
881
897
  if (activeAdapters == null) {
882
898
  activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
@@ -1101,11 +1117,22 @@ export class VaultV2BlueReallocationData {
1101
1117
  data,
1102
1118
  context: simulationContext,
1103
1119
  allocatorCapBoundTargets,
1120
+ idleBoundVaults,
1104
1121
  };
1105
1122
  const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1106
1123
  if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1107
1124
  // BluePublicAllocator caps are per vault and target adapter.
1108
1125
  allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1126
+ if (acceptedReallocation.from.type === "idle") {
1127
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1128
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1129
+ idleTakenAssets.set(vaultKey, taken);
1130
+ // Candidates always record this; a missing entry counts the vault as bound.
1131
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1132
+ if (taken >=
1133
+ MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
1134
+ idleBoundVaults.add(vaultKey);
1135
+ }
1109
1136
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1110
1137
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1111
1138
  if (touchedVaultPairs == null) {
@@ -1135,6 +1162,7 @@ export class VaultV2BlueReallocationData {
1135
1162
  data,
1136
1163
  context: simulationContext,
1137
1164
  allocatorCapBoundTargets,
1165
+ idleBoundVaults,
1138
1166
  };
1139
1167
  }
1140
1168
  /**
@@ -258,6 +258,8 @@ export interface BlueSupplyAction extends BaseAction<"blueSupply", {
258
258
  readonly nativeAmount?: bigint;
259
259
  readonly referralFeePct: bigint;
260
260
  readonly referralFeeRecipient: Address;
261
+ /** Fee deducted from `assets` before supplying: floor(assets * referralFeePct / WAD). */
262
+ readonly referralFeeAssets: bigint;
261
263
  readonly deadline: bigint;
262
264
  }> {
263
265
  }
@@ -271,6 +273,12 @@ export interface BlueWithdrawAction extends BaseAction<"blueWithdraw", {
271
273
  readonly reallocationPenaltyAssets: bigint;
272
274
  readonly referralFeePct: bigint;
273
275
  readonly referralFeeRecipient: Address;
276
+ /**
277
+ * Fee deducted from net withdrawal proceeds:
278
+ * floor((withdrawAssets - reallocationPenaltyAssets) * referralFeePct / WAD); omitted in
279
+ * exact-shares mode, where the received amount is resolved at execution.
280
+ */
281
+ readonly referralFeeAssets?: bigint;
274
282
  readonly deadline: bigint;
275
283
  }> {
276
284
  }
@@ -285,6 +293,12 @@ type BlueSupplyCollateralBorrowActionArgs = {
285
293
  readonly reallocationPenaltyAssets: bigint;
286
294
  readonly referralFeePct: bigint;
287
295
  readonly referralFeeRecipient: Address;
296
+ /**
297
+ * Fee deducted from the borrow leg's net proceeds:
298
+ * floor((borrowAssets - reallocationPenaltyAssets) * referralFeePct / WAD); zero when
299
+ * `borrowAssets` is zero. The collateral-supply leg carries no fee.
300
+ */
301
+ readonly referralFeeAssets: bigint;
288
302
  readonly deadline: bigint;
289
303
  };
290
304
  /** Metadata for a direct BlueBundlesV1 collateral supply. */
@@ -307,6 +321,14 @@ type BlueRepayWithdrawCollateralActionArgs = {
307
321
  readonly nativeAmount?: bigint;
308
322
  readonly referralFeePct: bigint;
309
323
  readonly referralFeeRecipient: Address;
324
+ /**
325
+ * Fee charged on top of the repaid assets, inside `maxRepayAssets`:
326
+ * floor(repayAssets * referralFeePct / (WAD - referralFeePct)); set only for an
327
+ * exact-assets repay (`repayAssets > 0n`), and omitted in exact-shares mode or
328
+ * when there is no repay leg, where the repaid amount is resolved at execution
329
+ * or never repaid.
330
+ */
331
+ readonly referralFeeAssets?: bigint;
310
332
  readonly deadline: bigint;
311
333
  };
312
334
  /** Metadata for a direct BlueBundlesV1 repayment. */
@@ -28,15 +28,20 @@ export interface VaultV2BluePublicAllocatorOptions {
28
28
  * Share of each target-market BluePublicAllocator cap, scaled by WAD, that
29
29
  * operation planning keeps free. When a reallocation toward the utilization
30
30
  * target would come within this headroom of the cap, the plan is reduced to
31
- * the larger of the operation's absolute shortfall and what vaults below
32
- * their cap were already moving. A plan of only the shortfall leaves the
33
- * market fully utilized, so a competing borrow or withdraw landing first can
34
- * still make it revert. If the shortfall cannot be covered while keeping the
35
- * headroom, the plan uses the full cap, first for the shortfall only and
36
- * then toward the utilization target if that is still short.
31
+ * the larger of the operation's absolute shortfall and what unbound legs
32
+ * were already moving (legs that neither come within the headroom of an
33
+ * allocator cap nor take nearly all of their source vault's idle). A plan of
34
+ * only the shortfall leaves the market fully utilized, so a competing borrow
35
+ * or withdraw landing first can still make it revert. If the shortfall cannot
36
+ * be covered while keeping the headroom, the plan uses the full cap, first for
37
+ * the shortfall only and then toward the utilization target if that is still
38
+ * short.
39
+ * The same share marks idle legs as bound: idle legs that together leave at
40
+ * most this share of a source vault's starting idle reduce the plan the same
41
+ * way, since any idle withdrawal landing first would make it revert.
37
42
  * Discovery plans, `getPublicReallocationLiquidity` and
38
43
  * `getAvailableLiquidityToUtilization` ignore it and use the full cap.
39
- * Must not exceed WAD (100%). Set to `0n` to disable.
44
+ * Must not exceed WAD (100%). Set to `0n` to disable both rules.
40
45
  *
41
46
  * @default DEFAULT_ALLOCATOR_CAP_HEADROOM (1%)
42
47
  */
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "8.1.0",
4
+ "version": "8.2.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",