@morpho-org/morpho-sdk 9.0.0 → 9.1.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 +3 -1
  2. package/lib/cjs/actions/blue/borrow.d.ts +1 -0
  3. package/lib/cjs/actions/blue/borrow.js +1 -0
  4. package/lib/cjs/actions/blue/refinance.d.ts +1 -0
  5. package/lib/cjs/actions/blue/refinance.js +3 -0
  6. package/lib/cjs/actions/blue/repay.d.ts +1 -0
  7. package/lib/cjs/actions/blue/repay.js +1 -0
  8. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  9. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -0
  10. package/lib/cjs/actions/blue/supply.d.ts +1 -0
  11. package/lib/cjs/actions/blue/supply.js +2 -0
  12. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -0
  13. package/lib/cjs/actions/blue/supplyCollateral.js +1 -0
  14. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  15. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +2 -0
  16. package/lib/cjs/actions/blue/withdraw.d.ts +1 -0
  17. package/lib/cjs/actions/blue/withdraw.js +2 -0
  18. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -0
  19. package/lib/cjs/actions/blue/withdrawCollateral.js +1 -0
  20. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  21. package/lib/cjs/actions/midnight/takeLend.js +1 -0
  22. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  24. package/lib/cjs/blue/errors.d.ts +1 -1
  25. package/lib/cjs/blue/errors.js +2 -1
  26. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  27. package/lib/cjs/client/morphoViemExtension.js +1 -7
  28. package/lib/cjs/entities/blue/blue.d.ts +43 -7
  29. package/lib/cjs/entities/blue/blue.js +27 -3
  30. package/lib/cjs/entities/midnight/midnight.d.ts +14 -6
  31. package/lib/cjs/entities/midnight/midnight.js +14 -6
  32. package/lib/cjs/entities/midnight/types.d.ts +9 -2
  33. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +3 -1
  34. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -5
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +40 -13
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.js +207 -70
  37. package/lib/cjs/errors.d.ts +1 -1
  38. package/lib/cjs/errors.js +3 -2
  39. package/lib/cjs/helpers/validate.d.ts +11 -1
  40. package/lib/cjs/helpers/validate.js +17 -1
  41. package/lib/cjs/helpers/validateTakeableOffers.d.ts +4 -2
  42. package/lib/cjs/helpers/validateTakeableOffers.js +12 -1
  43. package/lib/cjs/types/error.d.ts +10 -1
  44. package/lib/cjs/types/error.js +13 -2
  45. package/lib/cjs/types/sharedLiquidity.d.ts +27 -11
  46. package/lib/esm/actions/blue/borrow.d.ts +1 -0
  47. package/lib/esm/actions/blue/borrow.js +1 -0
  48. package/lib/esm/actions/blue/refinance.d.ts +1 -0
  49. package/lib/esm/actions/blue/refinance.js +4 -1
  50. package/lib/esm/actions/blue/repay.d.ts +1 -0
  51. package/lib/esm/actions/blue/repay.js +1 -0
  52. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  53. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -1
  54. package/lib/esm/actions/blue/supply.d.ts +1 -0
  55. package/lib/esm/actions/blue/supply.js +3 -1
  56. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -0
  57. package/lib/esm/actions/blue/supplyCollateral.js +1 -0
  58. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  59. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -1
  60. package/lib/esm/actions/blue/withdraw.d.ts +1 -0
  61. package/lib/esm/actions/blue/withdraw.js +3 -1
  62. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -0
  63. package/lib/esm/actions/blue/withdrawCollateral.js +1 -0
  64. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  65. package/lib/esm/actions/midnight/takeLend.js +1 -0
  66. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  67. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  68. package/lib/esm/blue/errors.d.ts +1 -1
  69. package/lib/esm/blue/errors.js +1 -1
  70. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  71. package/lib/esm/client/morphoViemExtension.js +1 -7
  72. package/lib/esm/entities/blue/blue.d.ts +43 -7
  73. package/lib/esm/entities/blue/blue.js +27 -3
  74. package/lib/esm/entities/midnight/midnight.d.ts +14 -6
  75. package/lib/esm/entities/midnight/midnight.js +14 -6
  76. package/lib/esm/entities/midnight/types.d.ts +9 -2
  77. package/lib/esm/entities/vaultV2/vaultV2.d.ts +3 -1
  78. package/lib/esm/entities/vaultV2/vaultV2.js +9 -6
  79. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +40 -13
  80. package/lib/esm/entities/vaultV2BlueReallocationData.js +208 -71
  81. package/lib/esm/errors.d.ts +1 -1
  82. package/lib/esm/errors.js +1 -1
  83. package/lib/esm/helpers/validate.d.ts +11 -1
  84. package/lib/esm/helpers/validate.js +15 -0
  85. package/lib/esm/helpers/validateTakeableOffers.d.ts +4 -2
  86. package/lib/esm/helpers/validateTakeableOffers.js +13 -2
  87. package/lib/esm/types/error.d.ts +10 -1
  88. package/lib/esm/types/error.js +11 -1
  89. package/lib/esm/types/sharedLiquidity.d.ts +27 -11
  90. package/package.json +4 -4
@@ -6,6 +6,7 @@ import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBl
6
6
  import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
7
7
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
8
8
  import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
9
+ import { validateMarketParamsId } from "../../helpers/validate.js";
9
10
  import { ExpiredDeadlineError, InputExceedsMaxError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
10
11
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
11
12
  import { getBundlesTokenRequirements } from "../requirements/index.js";
@@ -15,11 +16,20 @@ export class MorphoBlue {
15
16
  client;
16
17
  marketParams;
17
18
  chainId;
19
+ /**
20
+ * Binds `client` to the market described by `marketParams` on `chainId`.
21
+ *
22
+ * @param client - Morpho client used for reads and requirement lookups.
23
+ * @param marketParams - Market params whose `id` must hash from their five tuple fields.
24
+ * @param chainId - Chain the market lives on.
25
+ * @throws {MarketIdMismatchError} when `marketParams.id` does not hash from its tuple fields.
26
+ */
18
27
  // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
19
28
  constructor(client, marketParams, chainId) {
20
29
  this.client = client;
21
30
  this.marketParams = marketParams;
22
31
  this.chainId = chainId;
32
+ validateMarketParamsId(marketParams);
23
33
  }
24
34
  validateDeadline(deadline, now = Time.timestamp()) {
25
35
  if (deadline <= now) {
@@ -637,6 +647,7 @@ export class MorphoBlue {
637
647
  refinance(params) {
638
648
  const { userAddress, positionData, destination, deadline, referralFeeRecipient, } = params;
639
649
  this.validateWriteCommon(params);
650
+ validateMarketParamsId(destination.marketParams);
640
651
  // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
641
652
  // here, matching the pure action's normalization.
642
653
  const referralFeePct = params.referralFeePct ?? 0n;
@@ -720,10 +731,13 @@ export class MorphoBlue {
720
731
  *
721
732
  * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each
722
733
  * vault's BluePublicAllocator permissions and allocation caps at one block.
734
+ * The snapshot keeps the fetched block's timestamp as its default planning time.
723
735
  *
724
736
  * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity.
725
737
  * @param params.block.number - Block number used for every RPC read.
726
- * @param params.block.timestamp - Timestamp corresponding to the fetched block.
738
+ * @param params.block.timestamp - Timestamp of the fetched block. Stored on the snapshot and used as the
739
+ * planning timestamp when `options.timestamp` is omitted, never earlier than the latest market/vault
740
+ * `lastUpdate`. An explicit `options.timestamp` is used as given.
727
741
  * @returns A `VaultV2BlueReallocationData` snapshot ready for {@link getVaultV2BlueReallocations}.
728
742
  * @throws {ChainIdMismatchError} when the client declares another chain or its RPC reports another
729
743
  * chain via `eth_chainId`.
@@ -779,6 +793,7 @@ export class MorphoBlue {
779
793
  ]);
780
794
  return new VaultV2BlueReallocationData({
781
795
  chainId: this.chainId,
796
+ timestamp: block.timestamp,
782
797
  markets: { [targetMarket.id]: targetMarket },
783
798
  vaults: Object.fromEntries(vaultEntries.map(({ vault }) => [vault.address, vault])),
784
799
  allocations: Object.fromEntries(vaultEntries.map(({ publicAllocatorData, vault }) => [
@@ -809,14 +824,23 @@ export class MorphoBlue {
809
824
  * persist across every leg of a plan. Operation plans keep
810
825
  * `allocatorCapHeadroom` (1% of the cap by default) free under each target
811
826
  * BluePublicAllocator cap unless the operation shortfall needs it.
827
+ * For `refinance`, compute the plan on the destination-market handle (for
828
+ * example, `client.morpho.blue(destination.marketParams, chainId)`), not the
829
+ * source-market handle. Pass the source position's `borrowAssets` accrued to
830
+ * `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
831
+ * `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
832
+ * The planner includes the referral fee and its own planned allocator-leg
833
+ * penalties in destination debt. Refinance never uses vaults with a 100%
834
+ * penalty.
812
835
  *
813
836
  * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
814
837
  * @param params.options - Optional allocator discovery controls and operation to support.
815
838
  * @returns Action-ready reallocations and their post-simulation state.
816
839
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
817
840
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
818
- * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, or penalty limit is negative.
841
+ * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, penalty limit, or referral-fee percentage is negative.
819
842
  * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
843
+ * @throws {ReferralFeePctExceededError} when the referral-fee percentage is at least WAD.
820
844
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
821
845
  * @throws {UnknownReallocationMarketError} when a required market is absent.
822
846
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -826,7 +850,7 @@ export class MorphoBlue {
826
850
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
827
851
  * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition.
828
852
  * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
829
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall.
853
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall and, for refinance, its planned allocator penalties.
830
854
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
831
855
  * @example
832
856
  * ```ts
@@ -197,6 +197,7 @@ export declare class MorphoMidnight {
197
197
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
198
198
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
199
199
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
200
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
200
201
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
201
202
  * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
202
203
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
@@ -552,6 +553,7 @@ export declare class MorphoMidnight {
552
553
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
553
554
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
554
555
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
556
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
555
557
  * @throws {ExpiredDeadlineError} when `deadline` has expired.
556
558
  * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
557
559
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
@@ -636,14 +638,14 @@ export declare class MorphoMidnight {
636
638
  * for a new publication. Calls the Midnight mempool validation API while preparing the tree;
637
639
  * `validation: false` skips that call.
638
640
  *
639
- * @param params - Maker, lend-side offers, loan reserve, cancellations, and deadline.
641
+ * @param params - Maker, lend-side offers, `loanAssets` and `reservedLoanAssets` allowance thresholds, cancellations, and deadline.
640
642
  * @param params.accountAddress - Maker expected on every offer; must send the transaction.
641
643
  * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
642
644
  * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
643
645
  * @param params.deadline - Bundle execution deadline timestamp.
644
646
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
645
647
  * @param params.loanToken - Loan token shared by every offer market.
646
- * @param params.loanAssets - New loan reserve assigned to the published groups.
648
+ * @param params.loanAssets - Minimum Midnight allowance (with `reservedLoanAssets`) that `getRequirements()` checks; the approval it returns is unlimited. The signed offer caps bound fills.
647
649
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
648
650
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
649
651
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
@@ -781,6 +783,12 @@ export declare class MorphoMidnight {
781
783
  * `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
782
784
  * accruing interest to the current time before previewing parked shares (markets whose
783
785
  * IRM the SDK cannot accrue are previewed on their last-updated state).
786
+ * The share check runs once, before signing: the bundle supplies `assetsToPark` with no
787
+ * minimum-shares bound, so interest accrued before inclusion can still round the supply down
788
+ * to zero shares if `assetsToPark` is worth less than one share at inclusion. A preview above
789
+ * one share does not rule this out: interest accrued while the transaction waits, or not
790
+ * accrued by the SDK for an IRM it cannot accrue, raises the share price. Choosing a market
791
+ * whose share price makes that impossible is the caller's responsibility.
784
792
  * The caller is responsible for trusting the Blue market's oracle and IRM. If Blue liquidity is
785
793
  * drained, callback offers cannot fill until liquidity returns. `assetsToPark` may underfund the
786
794
  * offers; top-ups are allowed.
@@ -841,7 +849,7 @@ export declare class MorphoMidnight {
841
849
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
842
850
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
843
851
  * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
844
- * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
852
+ * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
845
853
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
846
854
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
847
855
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
@@ -940,7 +948,7 @@ export declare class MorphoMidnight {
940
948
  *
941
949
  * Shares the lend-side publication and requirement handling of {@link MorphoMidnight.makeLend}.
942
950
  * Loan assets are pulled by Midnight when the offers fill, not during publication.
943
- * The loan reserve uses the same approval sizing as `makeLend`.
951
+ * `loanAssets` is only the allowance threshold `getRequirements()` checks, as in `makeLend`; the signed offer caps bound fills.
944
952
  * A partially consumed offer group remains publishable with its shared remaining cap reduced.
945
953
  * No repay offer can be live after market maturity; late borrowers should repay directly with
946
954
  * {@link MorphoMidnight.repayWithdrawCollateral}.
@@ -948,14 +956,14 @@ export declare class MorphoMidnight {
948
956
  * Every offer must already have `buy = true` and `reduceOnly = true`.
949
957
  * The supplied tree, group caps and prices are preserved; no separate root signature is needed.
950
958
  *
951
- * @param params - Maker, reduce-only offers, optional cancellations, loan reserve, and deadline.
959
+ * @param params - Maker, reduce-only offers, optional cancellations, `loanAssets` and `reservedLoanAssets` allowance thresholds, and deadline.
952
960
  * @param params.accountAddress - Maker expected on every offer; must send the transaction.
953
961
  * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
954
962
  * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
955
963
  * @param params.deadline - Bundle execution deadline timestamp.
956
964
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
957
965
  * @param params.loanToken - Loan token shared by every offer market.
958
- * @param params.loanAssets - New loan reserve assigned to the published groups.
966
+ * @param params.loanAssets - Minimum Midnight allowance (with `reservedLoanAssets`) that `getRequirements()` checks; the approval it returns is unlimited. The signed offer caps bound fills.
959
967
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
960
968
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
961
969
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
@@ -339,6 +339,7 @@ export class MorphoMidnight {
339
339
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
340
340
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
341
341
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
342
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
342
343
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
343
344
  * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
344
345
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
@@ -927,6 +928,7 @@ export class MorphoMidnight {
927
928
  * @throws {EmptyMidnightTakeableOffersError} when no offers are supplied.
928
929
  * @throws {MidnightOfferSideMismatchError} when an offer has the wrong maker side.
929
930
  * @throws {MidnightTakeableOfferMarketMismatchError} when an offer targets another market.
931
+ * @throws {MidnightTakeableOfferZeroSellerReceiverError} when a sell offer routes seller proceeds to the zero address.
930
932
  * @throws {ExpiredDeadlineError} when `deadline` has expired.
931
933
  * @throws {MidnightTakeDeadlineTooFarError} when `deadline` is more than one hour from now.
932
934
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
@@ -1151,14 +1153,14 @@ export class MorphoMidnight {
1151
1153
  * for a new publication. Calls the Midnight mempool validation API while preparing the tree;
1152
1154
  * `validation: false` skips that call.
1153
1155
  *
1154
- * @param params - Maker, lend-side offers, loan reserve, cancellations, and deadline.
1156
+ * @param params - Maker, lend-side offers, `loanAssets` and `reservedLoanAssets` allowance thresholds, cancellations, and deadline.
1155
1157
  * @param params.accountAddress - Maker expected on every offer; must send the transaction.
1156
1158
  * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
1157
1159
  * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
1158
1160
  * @param params.deadline - Bundle execution deadline timestamp.
1159
1161
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1160
1162
  * @param params.loanToken - Loan token shared by every offer market.
1161
- * @param params.loanAssets - New loan reserve assigned to the published groups.
1163
+ * @param params.loanAssets - Minimum Midnight allowance (with `reservedLoanAssets`) that `getRequirements()` checks; the approval it returns is unlimited. The signed offer caps bound fills.
1162
1164
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups, excluding groups in `cancellations`.
1163
1165
  * @returns Prepared group metadata, lazy approval/authorization requirements, and a synchronous transaction builder.
1164
1166
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
@@ -1368,6 +1370,12 @@ export class MorphoMidnight {
1368
1370
  * `midnightBlueBuyCallbackFactory`, `accountAddress` and `callbackSalt`, and fetches the Morpho Blue market,
1369
1371
  * accruing interest to the current time before previewing parked shares (markets whose
1370
1372
  * IRM the SDK cannot accrue are previewed on their last-updated state).
1373
+ * The share check runs once, before signing: the bundle supplies `assetsToPark` with no
1374
+ * minimum-shares bound, so interest accrued before inclusion can still round the supply down
1375
+ * to zero shares if `assetsToPark` is worth less than one share at inclusion. A preview above
1376
+ * one share does not rule this out: interest accrued while the transaction waits, or not
1377
+ * accrued by the SDK for an IRM it cannot accrue, raises the share price. Choosing a market
1378
+ * whose share price makes that impossible is the caller's responsibility.
1371
1379
  * The caller is responsible for trusting the Blue market's oracle and IRM. If Blue liquidity is
1372
1380
  * drained, callback offers cannot fill until liquidity returns. `assetsToPark` may underfund the
1373
1381
  * offers; top-ups are allowed.
@@ -1428,7 +1436,7 @@ export class MorphoMidnight {
1428
1436
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1429
1437
  * @throws {viem.BaseError} when a pinned block, multicall, or oracle-code read fails.
1430
1438
  * @throws {EmptyBlueParkingMarketError} when `blueMarket` has no supply shares.
1431
- * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price.
1439
+ * @throws {ZeroBlueParkingSharesError} when `assetsToPark` would mint no supply shares at the current share price (checked at preparation time only).
1432
1440
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1433
1441
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1434
1442
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
@@ -1671,7 +1679,7 @@ export class MorphoMidnight {
1671
1679
  *
1672
1680
  * Shares the lend-side publication and requirement handling of {@link MorphoMidnight.makeLend}.
1673
1681
  * Loan assets are pulled by Midnight when the offers fill, not during publication.
1674
- * The loan reserve uses the same approval sizing as `makeLend`.
1682
+ * `loanAssets` is only the allowance threshold `getRequirements()` checks, as in `makeLend`; the signed offer caps bound fills.
1675
1683
  * A partially consumed offer group remains publishable with its shared remaining cap reduced.
1676
1684
  * No repay offer can be live after market maturity; late borrowers should repay directly with
1677
1685
  * {@link MorphoMidnight.repayWithdrawCollateral}.
@@ -1679,14 +1687,14 @@ export class MorphoMidnight {
1679
1687
  * Every offer must already have `buy = true` and `reduceOnly = true`.
1680
1688
  * The supplied tree, group caps and prices are preserved; no separate root signature is needed.
1681
1689
  *
1682
- * @param params - Maker, reduce-only offers, optional cancellations, loan reserve, and deadline.
1690
+ * @param params - Maker, reduce-only offers, optional cancellations, `loanAssets` and `reservedLoanAssets` allowance thresholds, and deadline.
1683
1691
  * @param params.accountAddress - Maker expected on every offer; must send the transaction.
1684
1692
  * @param params.offers - PriceRatifierV1 or RateRatifierV1 tree, or its `Tree.create` request.
1685
1693
  * @param params.cancellations - Previous groups to cancel with their consumption ceilings.
1686
1694
  * @param params.deadline - Bundle execution deadline timestamp.
1687
1695
  * @param params.validation - Midnight mempool API request controls, or `false` to skip the API call.
1688
1696
  * @param params.loanToken - Loan token shared by every offer market.
1689
- * @param params.loanAssets - New loan reserve assigned to the published groups.
1697
+ * @param params.loanAssets - Minimum Midnight allowance (with `reservedLoanAssets`) that `getRequirements()` checks; the approval it returns is unlimited. The signed offer caps bound fills.
1690
1698
  * @param params.reservedLoanAssets - Existing loan assets reserved by other open groups.
1691
1699
  * @returns Prepared root and groups, lazy requirements, and a synchronous publication builder.
1692
1700
  * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId` during `getOffersData()` or `getRequirements`, another chain than this entity's.
@@ -51,7 +51,14 @@ export interface MakeOffersParams {
51
51
  /** Parameters for a Midnight lend maker flow. */
52
52
  export interface MakeLendParams extends MakeOffersParams {
53
53
  readonly loanToken: Address;
54
- /** New group loan reserve. For grouped OCA offers, pass the group reserve once instead of summing every leg. */
54
+ /**
55
+ * Minimum Midnight loan-token allowance, together with `reservedLoanAssets`, that `getRequirements()` checks.
56
+ * When the allowance is lower, it returns an unlimited approval (`maxUint256`, capped per token by `MAX_TOKEN_APPROVALS`).
57
+ * Not checked against the offers: their signed `maxAssets`/`maxUnits` caps, the maker's balance and the
58
+ * allowance bound what takers can fill, so size those caps to what you mean to lend
59
+ * (`maxAssets` counts loan assets, `maxUnits` counts position units).
60
+ * For grouped OCA offers, pass the group amount once instead of summing every leg.
61
+ */
55
62
  readonly loanAssets: bigint;
56
63
  /** Existing loan assets reserved across the maker's other open groups, including consumed amounts when available. Leave out groups listed in `cancellations`; this transaction cancels them. */
57
64
  readonly reservedLoanAssets?: bigint;
@@ -62,7 +69,7 @@ export interface SupplyBlueMakeLendParams extends MakeOffersParams {
62
69
  * Morpho Blue market the parked assets are supplied to; its loan token must match every offer.
63
70
  * The contract does not check supply share-price slippage: use only markets protected against
64
71
  * supply-share-price inflation. Markets with no supply shares or parked amounts that mint zero
65
- * shares are rejected.
72
+ * shares are rejected (checked at preparation time; see `supplyBlueMakeLend`).
66
73
  */
67
74
  readonly blueMarket: BlueMarketParams;
68
75
  /** Loan assets pulled from the maker and supplied to `blueMarket` for the maker's callback. */
@@ -1,4 +1,4 @@
1
- import { type AccrualVaultV2, type MarketParams } from "@morpho-org/blue-sdk";
1
+ import { type AccrualVaultV2, MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { type Address } from "viem";
4
4
  import type { FetchParameters } from "../../types/data.js";
@@ -504,6 +504,8 @@ export interface VaultV2Actions {
504
504
  * This is the share-based counterpart to forceWithdraw, useful for maximum withdrawal scenarios
505
505
  * where specifying an exact asset amount is impractical.
506
506
  *
507
+ * Inputs are copied when the handle is created, so later changes to them are not encoded.
508
+ *
507
509
  * The total assets passed to forceDeallocate calls must be greater than or equal to the
508
510
  * asset-equivalent of the redeemed shares. The caller should apply a buffer on the deallocated
509
511
  * amounts to account for share-price drift between submission and execution.
@@ -1,4 +1,4 @@
1
- import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
1
+ import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketParams, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { _try, getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
@@ -694,15 +694,18 @@ export class MorphoVaultV2 {
694
694
  }
695
695
  forceRedeem({ deallocations, redeem, userAddress, }) {
696
696
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
697
+ const shares = redeem.shares;
698
+ const deallocationsSnapshot = deallocations.map(({ adapter, marketParams, amount }) => ({
699
+ adapter,
700
+ amount,
701
+ ...(marketParams && { marketParams: new MarketParams(marketParams) }),
702
+ }));
697
703
  return {
698
704
  buildTx: () => vaultV2ForceRedeem({
699
705
  vault: { address: this.vault },
700
706
  args: {
701
- deallocations,
702
- redeem: {
703
- shares: redeem.shares,
704
- recipient: userAddress,
705
- },
707
+ deallocations: deallocationsSnapshot,
708
+ redeem: { shares, recipient: userAddress },
706
709
  onBehalf: userAddress,
707
710
  },
708
711
  metadata: this.client.options.metadata,
@@ -1,4 +1,4 @@
1
- import { AccrualVaultV2, AccrualVaultV2MorphoMarketV1AdapterV2, type IAccrualVaultV2Adapter, type IVaultV2Allocation, type IVaultV2BlueMarketPublicAllocatorConfig, type IVaultV2BluePublicAllocatorConfig, Market, type MarketId, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig } from "@morpho-org/blue-sdk";
1
+ import { AccrualVaultV2, AccrualVaultV2MorphoMarketV1AdapterV2, type BigIntish, type IAccrualVaultV2Adapter, type IVaultV2Allocation, type IVaultV2BlueMarketPublicAllocatorConfig, type IVaultV2BluePublicAllocatorConfig, Market, type MarketId, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig } from "@morpho-org/blue-sdk";
2
2
  import { type Address, type Hash } from "viem";
3
3
  import type { VaultV2BluePublicAllocatorOptions, VaultV2BlueReallocation } from "../types/index.js";
4
4
  type ReadonlyMarketSnapshot = Readonly<Market>;
@@ -19,6 +19,13 @@ type ReadonlyVaultSnapshot = Readonly<Omit<AccrualVaultV2, "adapters" | "liquidi
19
19
  export interface InputVaultV2BlueReallocationData {
20
20
  /** Chain id associated with the fetched state. */
21
21
  readonly chainId: number;
22
+ /**
23
+ * Timestamp of the block the state was fetched at. When present, this is the
24
+ * default planning timestamp when `options.timestamp` is omitted, never
25
+ * earlier than the latest market/vault `lastUpdate`; when absent, planning
26
+ * defaults to the latest market/vault `lastUpdate`.
27
+ */
28
+ readonly timestamp?: BigIntish;
22
29
  /** Markets indexed by market id. */
23
30
  readonly markets?: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
24
31
  /** Accrued Vault V2 entities indexed by vault address. */
@@ -78,6 +85,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
78
85
  private readonly mutableAllocations;
79
86
  /** Chain id associated with this snapshot. */
80
87
  readonly chainId: number;
88
+ /** Timestamp of the block the state was fetched at. */
89
+ readonly timestamp?: bigint;
81
90
  /** Markets indexed by market id. */
82
91
  readonly markets: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
83
92
  /** Vault V2 entities indexed by address. */
@@ -356,16 +365,29 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
356
365
  * Computes Vault V2 BluePublicAllocator calls available for a target market.
357
366
  *
358
367
  * Without `options.operation`, discovers every friendly call. With an
359
- * operation, targets the amount required by that borrow or loan-asset
360
- * withdrawal and falls back to 100% source utilization only when friendly
361
- * liquidity cannot cover the absolute shortfall. A shared relative-cap lower
362
- * bound may require one call to exceed the targeted amount. Friendly source
363
- * utilization defaults to 90% and is configurable through
364
- * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
365
- * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
366
- * considered. Market/vault state and the returned post-state stay at
367
- * `timestamp`; only target-market cap checks reserve interest the vault's
368
- * existing allocation would accrue through `timestamp + capAccrualBuffer`
368
+ * operation, penalty tiers are considered ascending, starting with free
369
+ * vaults. The free tier aims to bring the target market back to 90%
370
+ * utilization; positive tiers cover only the remaining absolute shortfall
371
+ * (borrows minus supply). Within each tier, source markets go to the
372
+ * friendly source utilization (90% by default) before 100%. Free capacity
373
+ * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
374
+ * it instead. Discovery and liquidity getters still count every vault up to
375
+ * `options.maxPenalty`. A shared relative-cap lower bound may require one call
376
+ * to exceed the targeted amount. For `refinance`, compute the plan on the
377
+ * destination-market handle (for example,
378
+ * `client.morpho.blue(destination.marketParams, chainId)`), not the source
379
+ * handle. Pass the source position's `borrowAssets` accrued to
380
+ * `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
381
+ * `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
382
+ * The planner includes the referral fee and its allocator-leg penalties in
383
+ * destination debt, so penalized legs also cover their own penalty.
384
+ * Refinance never uses vaults with a 100% penalty.
385
+ * Friendly source utilization defaults to 90% and is configurable through
386
+ * `options.maxWithdrawalUtilization`. Market/vault state and the returned
387
+ * post-state stay at `timestamp`. An enabled operation that needs no
388
+ * reallocation still returns a clone accrued to `timestamp`. Only
389
+ * target-market cap checks reserve interest the vault's existing allocation
390
+ * would accrue through `timestamp + capAccrualBuffer`
369
391
  * (two hours by default; `0n` disables it). When an operation's plan would
370
392
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
393
  * BluePublicAllocator cap, the plan is reduced to the larger of the
@@ -406,8 +428,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
406
428
  * every leg of a plan.
407
429
  * @returns Flat action-ready reallocations and their post-simulation state.
408
430
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
409
- * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
431
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
410
432
  * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
433
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
411
434
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
412
435
  * @throws {UnknownReallocationMarketError} when a required market is absent.
413
436
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -415,7 +438,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
415
438
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
416
439
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
417
440
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
418
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
441
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
419
442
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
420
443
  * @example
421
444
  * ```ts
@@ -450,6 +473,10 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
450
473
  readonly operation?: {
451
474
  readonly type: "borrow" | "withdraw";
452
475
  readonly amount: bigint;
476
+ } | {
477
+ readonly type: "refinance";
478
+ readonly amount: bigint;
479
+ readonly referralFeePct?: bigint;
453
480
  };
454
481
  }): {
455
482
  readonly reallocations: readonly VaultV2BlueReallocation[];