@morpho-org/morpho-sdk 6.0.0-next.1 → 6.0.0-next.2

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 (174) hide show
  1. package/MIGRATION-v5-to-v6.md +127 -16
  2. package/README.md +17 -11
  3. package/lib/cjs/abis.d.ts +17 -2
  4. package/lib/cjs/abis.js +14 -1
  5. package/lib/cjs/actions/blue/common.js +5 -26
  6. package/lib/cjs/actions/blue/supply.js +2 -7
  7. package/lib/cjs/actions/bundles/common.d.ts +32 -2
  8. package/lib/cjs/actions/bundles/common.js +68 -30
  9. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -0
  10. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +6 -10
  11. package/lib/cjs/actions/requirements/blue/index.d.ts +0 -1
  12. package/lib/cjs/actions/requirements/blue/index.js +0 -1
  13. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +15 -8
  14. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +20 -20
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -27
  17. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +4 -2
  18. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.js +15 -10
  19. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  20. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  21. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  22. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  23. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +1 -0
  24. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +4 -1
  25. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +5 -2
  26. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +6 -0
  27. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +2 -0
  28. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -0
  29. package/lib/cjs/actions/vaultV1/inKindRedeem.js +3 -2
  30. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +58 -39
  31. package/lib/cjs/actions/vaultV2/forceWithdraw.js +87 -60
  32. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -0
  33. package/lib/cjs/actions/vaultV2/inKindRedeem.js +3 -2
  34. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  35. package/lib/cjs/blue/abis.d.ts +5 -1
  36. package/lib/cjs/blue/abis.js +2 -0
  37. package/lib/cjs/blue/entities.d.ts +8 -2
  38. package/lib/cjs/blue/entities.js +1 -0
  39. package/lib/cjs/blue/errors.d.ts +1 -1
  40. package/lib/cjs/blue/errors.js +2 -1
  41. package/lib/cjs/blue/fetch.d.ts +3 -1
  42. package/lib/cjs/blue/fetch.js +1 -0
  43. package/lib/cjs/entities/blue/blue.d.ts +15 -6
  44. package/lib/cjs/entities/blue/blue.js +3 -0
  45. package/lib/cjs/entities/index.d.ts +8 -2
  46. package/lib/cjs/entities/index.js +1 -0
  47. package/lib/cjs/entities/midnight/midnight.js +20 -24
  48. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  49. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +19 -14
  50. package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  51. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  52. package/lib/cjs/entities/requirements/index.js +1 -0
  53. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +10 -5
  54. package/lib/cjs/entities/vaultV1/vaultV1.js +13 -1
  55. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +6 -0
  56. package/lib/cjs/entities/vaultV1ReallocationData.js +20 -5
  57. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +140 -34
  58. package/lib/cjs/entities/vaultV2/vaultV2.js +229 -16
  59. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +8 -1
  60. package/lib/cjs/entities/vaultV2BlueReallocationData.js +46 -13
  61. package/lib/cjs/errors.d.ts +1 -1
  62. package/lib/cjs/errors.js +3 -2
  63. package/lib/cjs/fetch.d.ts +3 -1
  64. package/lib/cjs/fetch.js +1 -0
  65. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +2 -0
  66. package/lib/cjs/helpers/computeVaultV1Reallocations.js +2 -0
  67. package/lib/cjs/helpers/index.d.ts +3 -1
  68. package/lib/cjs/helpers/index.js +10 -1
  69. package/lib/cjs/helpers/metadata.d.ts +3 -5
  70. package/lib/cjs/helpers/metadata.js +4 -6
  71. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  72. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +164 -0
  73. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  74. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +2 -0
  75. package/lib/cjs/helpers/slippage.d.ts +46 -0
  76. package/lib/cjs/helpers/slippage.js +65 -0
  77. package/lib/cjs/helpers/validate.d.ts +65 -8
  78. package/lib/cjs/helpers/validate.js +83 -9
  79. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  80. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +369 -0
  81. package/lib/cjs/types/action.d.ts +95 -13
  82. package/lib/cjs/types/error.d.ts +290 -12
  83. package/lib/cjs/types/error.js +312 -24
  84. package/lib/cjs/types/sharedLiquidity.d.ts +2 -2
  85. package/lib/cjs/utils.d.ts +3 -1
  86. package/lib/cjs/utils.js +10 -1
  87. package/lib/esm/abis.d.ts +17 -2
  88. package/lib/esm/abis.js +17 -2
  89. package/lib/esm/actions/blue/common.js +7 -28
  90. package/lib/esm/actions/blue/supply.js +4 -9
  91. package/lib/esm/actions/bundles/common.d.ts +32 -2
  92. package/lib/esm/actions/bundles/common.js +68 -31
  93. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -0
  94. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +8 -12
  95. package/lib/esm/actions/requirements/blue/index.d.ts +0 -1
  96. package/lib/esm/actions/requirements/blue/index.js +0 -1
  97. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +15 -8
  98. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +21 -21
  99. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  100. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -28
  101. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +4 -2
  102. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.js +15 -10
  103. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  104. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  105. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  106. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  107. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +1 -0
  108. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +4 -1
  109. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +5 -2
  110. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +6 -0
  111. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +2 -0
  112. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -0
  113. package/lib/esm/actions/vaultV1/inKindRedeem.js +3 -2
  114. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +58 -39
  115. package/lib/esm/actions/vaultV2/forceWithdraw.js +89 -62
  116. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -0
  117. package/lib/esm/actions/vaultV2/inKindRedeem.js +3 -2
  118. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  119. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +3 -1
  120. package/lib/esm/blue/abis.d.ts +5 -1
  121. package/lib/esm/blue/abis.js +5 -1
  122. package/lib/esm/blue/entities.d.ts +8 -2
  123. package/lib/esm/blue/entities.js +3 -1
  124. package/lib/esm/blue/errors.d.ts +1 -1
  125. package/lib/esm/blue/errors.js +1 -1
  126. package/lib/esm/blue/fetch.d.ts +3 -1
  127. package/lib/esm/blue/fetch.js +3 -1
  128. package/lib/esm/entities/blue/blue.d.ts +15 -6
  129. package/lib/esm/entities/blue/blue.js +3 -0
  130. package/lib/esm/entities/index.d.ts +8 -2
  131. package/lib/esm/entities/index.js +3 -1
  132. package/lib/esm/entities/midnight/midnight.js +20 -24
  133. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  134. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +20 -15
  135. package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  136. package/lib/esm/entities/requirements/index.d.ts +1 -0
  137. package/lib/esm/entities/requirements/index.js +1 -0
  138. package/lib/esm/entities/vaultV1/vaultV1.d.ts +10 -5
  139. package/lib/esm/entities/vaultV1/vaultV1.js +14 -2
  140. package/lib/esm/entities/vaultV1ReallocationData.d.ts +6 -0
  141. package/lib/esm/entities/vaultV1ReallocationData.js +20 -5
  142. package/lib/esm/entities/vaultV2/vaultV2.d.ts +140 -34
  143. package/lib/esm/entities/vaultV2/vaultV2.js +234 -21
  144. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +8 -1
  145. package/lib/esm/entities/vaultV2BlueReallocationData.js +46 -13
  146. package/lib/esm/errors.d.ts +1 -1
  147. package/lib/esm/errors.js +1 -1
  148. package/lib/esm/fetch.d.ts +3 -1
  149. package/lib/esm/fetch.js +3 -1
  150. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +2 -0
  151. package/lib/esm/helpers/computeVaultV1Reallocations.js +2 -0
  152. package/lib/esm/helpers/index.d.ts +3 -1
  153. package/lib/esm/helpers/index.js +3 -1
  154. package/lib/esm/helpers/metadata.d.ts +3 -5
  155. package/lib/esm/helpers/metadata.js +4 -6
  156. package/lib/esm/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  157. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +161 -0
  158. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  159. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +2 -0
  160. package/lib/esm/helpers/slippage.d.ts +46 -0
  161. package/lib/esm/helpers/slippage.js +65 -1
  162. package/lib/esm/helpers/validate.d.ts +65 -8
  163. package/lib/esm/helpers/validate.js +82 -10
  164. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  165. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +362 -0
  166. package/lib/esm/types/action.d.ts +95 -13
  167. package/lib/esm/types/error.d.ts +290 -12
  168. package/lib/esm/types/error.js +301 -19
  169. package/lib/esm/types/sharedLiquidity.d.ts +2 -2
  170. package/lib/esm/utils.d.ts +3 -1
  171. package/lib/esm/utils.js +3 -1
  172. package/package.json +7 -7
  173. /package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
  174. /package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
@@ -550,7 +550,6 @@ class MorphoMidnight {
550
550
  }
551
551
  });
552
552
  const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
553
- const signedPayloads = new Map();
554
553
  return {
555
554
  groups: data.groups,
556
555
  root: data.tree.root,
@@ -567,14 +566,12 @@ class MorphoMidnight {
567
566
  })));
568
567
  requirements.push(...(await this.getRatifierRequirements({
569
568
  offersData: data,
570
- signedPayloads,
571
569
  })));
572
570
  return requirements;
573
571
  },
574
572
  buildTx: (signatures) => this.buildSubmitOffersTx({
575
573
  offersData: data,
576
574
  signatures,
577
- signedPayloads,
578
575
  }),
579
576
  };
580
577
  }
@@ -605,7 +602,6 @@ class MorphoMidnight {
605
602
  validation: params.validation,
606
603
  });
607
604
  (0, validateOfferSides_js_1.validateOfferSides)(data.tree.offers, false);
608
- const signedPayloads = new Map();
609
605
  return {
610
606
  groups: data.groups,
611
607
  root: data.tree.root,
@@ -613,13 +609,11 @@ class MorphoMidnight {
613
609
  getRequirements: async () => {
614
610
  return await this.getRatifierRequirements({
615
611
  offersData: data,
616
- signedPayloads,
617
612
  });
618
613
  },
619
614
  buildTx: (signatures) => this.buildSubmitOffersTx({
620
615
  offersData: data,
621
616
  signatures,
622
- signedPayloads,
623
617
  }),
624
618
  };
625
619
  }
@@ -677,7 +671,6 @@ class MorphoMidnight {
677
671
  }
678
672
  }
679
673
  const midnight = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnight");
680
- const signedPayloads = new Map();
681
674
  return {
682
675
  groups: data.groups,
683
676
  root: data.tree.root,
@@ -702,7 +695,6 @@ class MorphoMidnight {
702
695
  }),
703
696
  ...(await this.getRatifierRequirements({
704
697
  offersData: data,
705
- signedPayloads,
706
698
  })),
707
699
  ];
708
700
  return requirements;
@@ -710,7 +702,6 @@ class MorphoMidnight {
710
702
  buildTx: (signatures) => this.buildSubmitOffersTx({
711
703
  offersData: data,
712
704
  signatures,
713
- signedPayloads,
714
705
  }),
715
706
  };
716
707
  }
@@ -910,6 +901,18 @@ class MorphoMidnight {
910
901
  requirements.push(authorization);
911
902
  if (data.ratifierType === "ecrecover") {
912
903
  const chainId = this.chainId;
904
+ // The offer-tree EIP-712 payload is signed over the tree, not the signer, so it is fully
905
+ // determined at build time and stored on the action for external signing.
906
+ const treeTypedData = midnight_sdk_1.EcrecoverRatifierUtils.typedData({
907
+ tree: data.tree,
908
+ chainId,
909
+ });
910
+ const typedData = (0, morpho_ts_1.deepFreeze)({
911
+ domain: treeTypedData.domain,
912
+ types: treeTypedData.types,
913
+ primaryType: treeTypedData.primaryType,
914
+ message: treeTypedData.message,
915
+ });
913
916
  const action = {
914
917
  type: "midnightOfferRootSignature",
915
918
  args: {
@@ -917,32 +920,23 @@ class MorphoMidnight {
917
920
  ratifier: data.ratifier,
918
921
  offers: data.tree.offers.length,
919
922
  },
923
+ typedData,
920
924
  };
921
925
  requirements.push({
922
926
  action,
923
927
  async sign(client, userAddress) {
924
- const typedData = midnight_sdk_1.EcrecoverRatifierUtils.typedData({
925
- tree: data.tree,
926
- chainId,
927
- });
928
- const typedDataDefinition = {
929
- domain: typedData.domain,
930
- types: typedData.types,
931
- primaryType: typedData.primaryType,
932
- message: typedData.message,
933
- };
934
928
  const signature = await (0, signAndVerifyTypedData_js_1.signAndVerifyTypedData)({
935
929
  client,
936
930
  userAddress,
937
- typedData: typedDataDefinition,
931
+ typedData,
938
932
  });
933
+ // Derive the ratification payload `buildTx()` submits.
939
934
  const items = await midnight_sdk_1.EcrecoverRatifierUtils.ratify({
940
935
  tree: data.tree,
941
936
  account: userAddress,
942
937
  signature,
943
938
  });
944
939
  const payload = await midnight_sdk_1.Payload.encode(items);
945
- params.signedPayloads.set(signature.toLowerCase(), payload);
946
940
  return (0, morpho_ts_1.deepFreeze)({
947
941
  args: {
948
942
  owner: userAddress,
@@ -1010,11 +1004,13 @@ class MorphoMidnight {
1010
1004
  actualOffers: signature.action.args.offers,
1011
1005
  });
1012
1006
  }
1013
- const signedPayload = params.signedPayloads.get(signature.args.signature.toLowerCase());
1014
- if (signedPayload == null) {
1007
+ // The payload is carried on the signature the caller hands to buildTx, so
1008
+ // a prepared offer-root requirement can be signed on one instance and
1009
+ // submitted from another without sharing in-memory state.
1010
+ if (signature.args.payload == null) {
1015
1011
  throw new index_js_4.UnpreparedMidnightOfferRootSignatureError();
1016
1012
  }
1017
- payload = signedPayload;
1013
+ payload = signature.args.payload;
1018
1014
  }
1019
1015
  else {
1020
1016
  (0, index_js_4.selectRequirementSignatures)(collectedSignatures, {});
@@ -22,7 +22,7 @@ export interface GetBundlesTokenRequirementsParams {
22
22
  readonly supportDeployless?: boolean;
23
23
  /** Prefer ERC-2612 when the token exposes a compatible nonce. */
24
24
  readonly useSimplePermit?: boolean;
25
- /** Explicit unused Permit2 SignatureTransfer unordered nonce. */
25
+ /** Explicit unused uint256 nonce; defaults to the lowest unused nonce found via getUnusedPermit2Nonce. */
26
26
  readonly permit2Nonce?: bigint;
27
27
  }
28
28
  /**
@@ -31,8 +31,8 @@ export interface GetBundlesTokenRequirementsParams {
31
31
  *
32
32
  * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
33
33
  * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names the bundles contract
34
- * as spender. Permit2 SignatureTransfer requires an explicit unused unordered nonce so concurrent
35
- * requirements never silently sign the same owner-global nonce.
34
+ * as spender. The resolver picks the lowest unused unordered nonce by default; concurrent flows for
35
+ * the same owner should pass explicit nonces.
36
36
  *
37
37
  * @param viemClient - Connected viem client used for allowance and nonce reads.
38
38
  * @param params - Token requirement parameters.
@@ -46,7 +46,8 @@ export interface GetBundlesTokenRequirementsParams {
46
46
  * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
47
47
  * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
48
48
  * @param params.useSimplePermit - Prefer ERC-2612 when its nonce probe succeeds.
49
- * @param params.permit2Nonce - Explicit unused uint256 nonce required when Permit2 is selected.
49
+ * @param params.permit2Nonce - Explicit unused uint256 nonce; defaults to the lowest unused nonce
50
+ * found via {@link getUnusedPermit2Nonce}.
50
51
  * @returns Ordered deep-frozen approval transactions and/or signable token requirements.
51
52
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
52
53
  * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
@@ -55,7 +56,8 @@ export interface GetBundlesTokenRequirementsParams {
55
56
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
56
57
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not the chain's registered
57
58
  * BlueBundlesV1 or VaultBundlesV1 deployment, including for a zero-amount request.
58
- * @throws {MissingPermit2SignatureTransferNonceError} when Permit2 is selected without a nonce.
59
+ * @throws {NoUnusedPermit2NonceError} when every Permit2 nonce for the owner is consumed and none
60
+ * was passed explicitly.
59
61
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
60
62
  * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
61
63
  * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount` is below `amount`.
@@ -79,7 +81,6 @@ export interface GetBundlesTokenRequirementsParams {
79
81
  * chainId: mainnet.id,
80
82
  * deadline: 1_900_000_000n,
81
83
  * supportSignature: true,
82
- * permit2Nonce: 42n,
83
84
  * });
84
85
  * // requirements contains approvals and/or signable bundles token requirements.
85
86
  * ```
@@ -10,14 +10,15 @@ const index_js_1 = require("../../actions/bundles/index.js");
10
10
  const encodeErc20Permit_js_1 = require("../../actions/requirements/encode/encodeErc20Permit.js");
11
11
  const index_js_2 = require("../../helpers/index.js");
12
12
  const index_js_3 = require("../../types/index.js");
13
+ const getUnusedPermit2Nonce_js_1 = require("./getUnusedPermit2Nonce.js");
13
14
  /**
14
15
  * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
15
16
  * a registered fixed bundles contract.
16
17
  *
17
18
  * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
18
19
  * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names the bundles contract
19
- * as spender. Permit2 SignatureTransfer requires an explicit unused unordered nonce so concurrent
20
- * requirements never silently sign the same owner-global nonce.
20
+ * as spender. The resolver picks the lowest unused unordered nonce by default; concurrent flows for
21
+ * the same owner should pass explicit nonces.
21
22
  *
22
23
  * @param viemClient - Connected viem client used for allowance and nonce reads.
23
24
  * @param params - Token requirement parameters.
@@ -31,7 +32,8 @@ const index_js_3 = require("../../types/index.js");
31
32
  * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
32
33
  * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
33
34
  * @param params.useSimplePermit - Prefer ERC-2612 when its nonce probe succeeds.
34
- * @param params.permit2Nonce - Explicit unused uint256 nonce required when Permit2 is selected.
35
+ * @param params.permit2Nonce - Explicit unused uint256 nonce; defaults to the lowest unused nonce
36
+ * found via {@link getUnusedPermit2Nonce}.
35
37
  * @returns Ordered deep-frozen approval transactions and/or signable token requirements.
36
38
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
37
39
  * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
@@ -40,7 +42,8 @@ const index_js_3 = require("../../types/index.js");
40
42
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
41
43
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not the chain's registered
42
44
  * BlueBundlesV1 or VaultBundlesV1 deployment, including for a zero-amount request.
43
- * @throws {MissingPermit2SignatureTransferNonceError} when Permit2 is selected without a nonce.
45
+ * @throws {NoUnusedPermit2NonceError} when every Permit2 nonce for the owner is consumed and none
46
+ * was passed explicitly.
44
47
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
45
48
  * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
46
49
  * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount` is below `amount`.
@@ -64,7 +67,6 @@ const index_js_3 = require("../../types/index.js");
64
67
  * chainId: mainnet.id,
65
68
  * deadline: 1_900_000_000n,
66
69
  * supportSignature: true,
67
- * permit2Nonce: 42n,
68
70
  * });
69
71
  * // requirements contains approvals and/or signable bundles token requirements.
70
72
  * ```
@@ -121,6 +123,7 @@ const getBundlesTokenRequirements = async (viemClient, params) => {
121
123
  return [
122
124
  await (0, encodeErc20Permit_js_1.encodeErc20Permit)(viemClient, {
123
125
  token: params.token,
126
+ owner: params.owner,
124
127
  spender: params.spender,
125
128
  amount: params.amount,
126
129
  chainId: params.chainId,
@@ -132,20 +135,22 @@ const getBundlesTokenRequirements = async (viemClient, params) => {
132
135
  }
133
136
  }
134
137
  if (permit2 != null) {
135
- if (params.permit2Nonce == null) {
136
- throw new index_js_3.MissingPermit2SignatureTransferNonceError();
138
+ const permit2Nonce = params.permit2Nonce ??
139
+ (await (0, getUnusedPermit2Nonce_js_1.getUnusedPermit2Nonce)(viemClient, {
140
+ owner: params.owner,
141
+ chainId: params.chainId,
142
+ }));
143
+ if (permit2Nonce < 0n) {
144
+ throw new index_js_3.NegativeInputError("permit2Nonce", permit2Nonce);
137
145
  }
138
- if (params.permit2Nonce < 0n) {
139
- throw new index_js_3.NegativeInputError("permit2Nonce", params.permit2Nonce);
140
- }
141
- if (params.permit2Nonce > viem_1.maxUint256) {
146
+ if (permit2Nonce > viem_1.maxUint256) {
142
147
  throw new index_js_3.InputExceedsMaxError({
143
148
  field: "permit2Nonce",
144
- value: params.permit2Nonce,
149
+ value: permit2Nonce,
145
150
  max: viem_1.maxUint256,
146
151
  });
147
152
  }
148
- const wordPosition = params.permit2Nonce >> 8n;
153
+ const wordPosition = permit2Nonce >> 8n;
149
154
  const [allowance, nonceBitmap] = await Promise.all([
150
155
  (0, actions_1.readContract)(viemClient, {
151
156
  abi: viem_1.erc20Abi,
@@ -170,7 +175,7 @@ const getBundlesTokenRequirements = async (viemClient, params) => {
170
175
  state: {
171
176
  type: "permit2SignatureTransfer",
172
177
  permit2Allowance: allowance,
173
- permit2Nonce: params.permit2Nonce,
178
+ permit2Nonce,
174
179
  nonceBitmap,
175
180
  },
176
181
  });
@@ -5,9 +5,9 @@ const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const actions_1 = require("viem/actions");
8
- const index_js_1 = require("../../../helpers/index.js");
9
- const validate_js_1 = require("../../../helpers/validate.js");
10
- const index_js_2 = require("../../../types/index.js");
8
+ const index_js_1 = require("../../helpers/index.js");
9
+ const validate_js_1 = require("../../helpers/validate.js");
10
+ const index_js_2 = require("../../types/index.js");
11
11
  /** Highest Permit2 nonce-bitmap word index; each word covers 256 unordered nonces. */
12
12
  const MAX_PERMIT2_NONCE_WORD = viem_1.maxUint256 >> 8n;
13
13
  /**
@@ -1 +1,2 @@
1
1
  export * from "./getBundlesTokenRequirements.js";
2
+ export * from "./getUnusedPermit2Nonce.js";
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./getBundlesTokenRequirements.js"), exports);
18
+ __exportStar(require("./getUnusedPermit2Nonce.js"), exports);
@@ -5,10 +5,10 @@ import type { FetchParameters } from "../../types/data.js";
5
5
  import { type ActionOutput, type ActionRequirement, type BundlesFundingArgs, type BundlesTokenRequirementsOptions, type MorphoClientType, type RequirementSignature, type VaultV1DepositAction, type VaultV1InKindRedeemAction, type VaultV1MigrateToV2Action, type VaultV1MigrateToV2AmountArgs, type VaultV1RedeemAction, type VaultV1WithdrawAction } from "../../types/index.js";
6
6
  export interface VaultV1Actions {
7
7
  /**
8
- * Fetches the latest vault data with accrued interest.
8
+ * Fetches direct onchain vault and allocation state without applying virtual interest.
9
9
  *
10
10
  * @param {FetchParameters} [parameters] - Optional fetch parameters (block number, state overrides, etc.).
11
- * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>} The latest vault data.
11
+ * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>} The requested vault state.
12
12
  */
13
13
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>;
14
14
  /**
@@ -46,8 +46,8 @@ export interface VaultV1Actions {
46
46
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
47
47
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
48
48
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
49
- * @throws {MissingPermit2SignatureTransferNonceError} from `getRequirements()` when Permit2 is
50
- * selected without an explicit nonce.
49
+ * @throws {NoUnusedPermit2NonceError} from `getRequirements()` when every Permit2 nonce for the
50
+ * owner is consumed and none was passed explicitly.
51
51
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
52
52
  * explicit Permit2 nonce is consumed.
53
53
  * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
@@ -249,9 +249,11 @@ export interface VaultV1Actions {
249
249
  * @param params.deadline - Optional shared permit/bundle deadline; defaults to two hours from now.
250
250
  * @returns Lazy prerequisite resolution and a synchronous transaction builder.
251
251
  * @throws {ChainIdMismatchError} when the client and entity target different chains.
252
+ * @throws {UnsupportedBlueMarketIrmError} when an allocated market with positive debt uses an unsupported IRM.
252
253
  * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
253
- * @throws {NonPositiveInputError} when `amount` is not positive.
254
+ * @throws {NonPositiveInputError} when `amount` or `deadline` is not positive.
254
255
  * @throws {EmptyMarketParamsListError} when the market list is empty.
256
+ * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
255
257
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
256
258
  * requirement resolution.
257
259
  * @throws {InKindRedeemCoverageError} when the ordered list cannot cover `amount` without
@@ -326,6 +328,8 @@ export interface VaultV1Actions {
326
328
  * `getRequirements()` re-reads the live share allowance on every call, so a requirement
327
329
  * satisfied between calls stops being reported, while the derived source share cap stays
328
330
  * pinned to the supplied snapshot.
331
+ * @throws {UnknownBlueMarketAllocationError} when a source withdraw-queue market has no allocation snapshot.
332
+ * @throws {UnsupportedBlueMarketIrmError} when required interest projection encounters an unsupported IRM.
329
333
  * @throws {ChainIdMismatchError} when the connected client targets another chain.
330
334
  * @throws {VaultAddressMismatchError} when `sourceVault` belongs to another vault.
331
335
  * @throws {VaultAssetMismatchError} when the source and destination vault assets differ.
@@ -442,6 +446,7 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
442
446
  readonly userAddress: Address;
443
447
  readonly deadline?: bigint;
444
448
  }): ActionOutput<VaultV1InKindRedeemAction, readonly RequirementSignature[], undefined>;
449
+ /** {@inheritDoc VaultV1Actions.migrateToV2} */
445
450
  migrateToV2(params: {
446
451
  readonly userAddress: Address;
447
452
  readonly sourceVault: AccrualVault;
@@ -290,6 +290,9 @@ class MorphoVaultV1 {
290
290
  }));
291
291
  const now = morpho_ts_1.Time.timestamp();
292
292
  const deadline = deadlineOverride ?? now + morpho_ts_1.Time.s.from.h(2n);
293
+ // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
294
+ // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
295
+ (0, validate_js_1.validateDeadline)(deadline);
293
296
  if (deadline <= now)
294
297
  throw new index_js_3.ExpiredDeadlineError(deadline, now);
295
298
  const vaultExitBundlesV1 = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultExitBundlesV1");
@@ -304,6 +307,8 @@ class MorphoVaultV1 {
304
307
  const allocation = vaultData.allocations.get(marketId);
305
308
  if (allocation?.config.enabled !== true)
306
309
  continue;
310
+ if (allocation.position.supplyShares === 0n)
311
+ continue;
307
312
  const market = allocation.position.market.accrueInterest(now);
308
313
  const available = market.toSupplyAssets(allocation.position.supplyShares);
309
314
  const assigned = assignedByMarket.get(marketId) ?? 0n;
@@ -433,6 +438,7 @@ class MorphoVaultV1 {
433
438
  },
434
439
  };
435
440
  }
441
+ /** {@inheritDoc VaultV1Actions.migrateToV2} */
436
442
  migrateToV2(params) {
437
443
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
438
444
  if (!(0, viem_1.isAddressEqual)(params.sourceVault.address, this.vault)) {
@@ -464,7 +470,13 @@ class MorphoVaultV1 {
464
470
  referralFeePct: params.referralFeePct,
465
471
  referralFeeRecipient: params.referralFeeRecipient,
466
472
  });
467
- const grossAssets = assets ?? params.sourceVault.toAssets(shares ?? 0n, "Down");
473
+ // V1 redeem accrues market interest and performance fees before converting shares.
474
+ const grossAssets = assets ??
475
+ params.sourceVault
476
+ .accrueInterest(params.sourceVault.allocations
477
+ .values()
478
+ .reduce((timestamp, { position }) => blue_sdk_1.MathLib.max(timestamp, position.market.lastUpdate), createdAt))
479
+ .toAssets(shares ?? 0n, "Down");
468
480
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(grossAssets, common.referralFeePct);
469
481
  const maxSharePriceVaultV2 = (0, index_js_2.computeVaultMaxSharePrice)({
470
482
  vaultData: params.targetVault,
@@ -130,10 +130,13 @@ export declare class VaultV1ReallocationData implements InputVaultV1Reallocation
130
130
  * Returned `data` normalizes `vault.publicAllocatorConfig.accruedFee` to the
131
131
  * on-chain `reallocateTo` fee semantics: one fee charge per vault with at
132
132
  * least one computed withdrawal.
133
+ * Sources with zero allocator withdrawal capacity and destinations with no deposit capacity
134
+ * are skipped before projecting source interest.
133
135
  *
134
136
  * @param marketId - Target market to supply with shared liquidity.
135
137
  * @param options - Optional allocator discovery options.
136
138
  * @returns Computed source-market withdrawals and the post-reallocation state.
139
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
137
140
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
138
141
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
139
142
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
@@ -179,6 +182,7 @@ export declare class VaultV1ReallocationData implements InputVaultV1Reallocation
179
182
  * @param marketId - Target market to supply with shared liquidity.
180
183
  * @param options - Optional allocator discovery options.
181
184
  * @returns Computed source-market withdrawals and the post-reallocation state.
185
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
182
186
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
183
187
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
184
188
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
@@ -199,6 +203,7 @@ export declare class VaultV1ReallocationData implements InputVaultV1Reallocation
199
203
  * @param marketId - Target market that would receive the liquidity.
200
204
  * @param options - Optional allocator discovery options.
201
205
  * @returns Total reallocatable assets in loan-token units; `0n` when none is available.
206
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
202
207
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
203
208
  * @deprecated Vault V1 shared-liquidity metrics will be removed in the next major. Use
204
209
  * `VaultV2BlueReallocationData.getPublicReallocationLiquidity`.
@@ -252,6 +257,7 @@ export declare class VaultV1ReallocationData implements InputVaultV1Reallocation
252
257
  * @param utilization - Utilization to bring the market to, scaled by WAD. Defaults to {@link DEFAULT_SUPPLY_TARGET_UTILIZATION}.
253
258
  * @param options - Optional reallocation options (supply target utilization trigger, timestamp, withdrawal caps).
254
259
  * @returns Available liquidity to the given utilization in loan-token units; `0n` when none is available.
260
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
255
261
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
256
262
  * @deprecated Vault V1 shared-liquidity metrics will be removed in the next major. Use
257
263
  * `VaultV2BlueReallocationData.getAvailableLiquidityToUtilization`.
@@ -213,10 +213,13 @@ class VaultV1ReallocationData {
213
213
  * Returned `data` normalizes `vault.publicAllocatorConfig.accruedFee` to the
214
214
  * on-chain `reallocateTo` fee semantics: one fee charge per vault with at
215
215
  * least one computed withdrawal.
216
+ * Sources with zero allocator withdrawal capacity and destinations with no deposit capacity
217
+ * are skipped before projecting source interest.
216
218
  *
217
219
  * @param marketId - Target market to supply with shared liquidity.
218
220
  * @param options - Optional allocator discovery options.
219
221
  * @returns Computed source-market withdrawals and the post-reallocation state.
222
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
220
223
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
221
224
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
222
225
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
@@ -314,6 +317,7 @@ class VaultV1ReallocationData {
314
317
  * @param marketId - Target market to supply with shared liquidity.
315
318
  * @param options - Optional allocator discovery options.
316
319
  * @returns Computed source-market withdrawals and the post-reallocation state.
320
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
317
321
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
318
322
  * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
319
323
  * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
@@ -333,6 +337,7 @@ class VaultV1ReallocationData {
333
337
  * @param marketId - Target market that would receive the liquidity.
334
338
  * @param options - Optional allocator discovery options.
335
339
  * @returns Total reallocatable assets in loan-token units; `0n` when none is available.
340
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
336
341
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
337
342
  * @deprecated Vault V1 shared-liquidity metrics will be removed in the next major. Use
338
343
  * `VaultV2BlueReallocationData.getPublicReallocationLiquidity`.
@@ -389,6 +394,7 @@ class VaultV1ReallocationData {
389
394
  * @param utilization - Utilization to bring the market to, scaled by WAD. Defaults to {@link DEFAULT_SUPPLY_TARGET_UTILIZATION}.
390
395
  * @param options - Optional reallocation options (supply target utilization trigger, timestamp, withdrawal caps).
391
396
  * @returns Available liquidity to the given utilization in loan-token units; `0n` when none is available.
397
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
392
398
  * @throws {@link UnknownReallocationMarketError} when the target market is absent.
393
399
  * @deprecated Vault V1 shared-liquidity metrics will be removed in the next major. Use
394
400
  * `VaultV2BlueReallocationData.getAvailableLiquidityToUtilization`.
@@ -446,25 +452,34 @@ class VaultV1ReallocationData {
446
452
  getLargestVaultWithdrawal({ vault, marketId, withdrawals, defaultMaxWithdrawalUtilization, maxWithdrawalUtilization, timestamp, }) {
447
453
  return (0, morpho_ts_1._try)(() => {
448
454
  const { cap, pendingCap, publicAllocatorConfig } = this.getVaultMarketConfig(vault, marketId);
455
+ const maxIn = publicAllocatorConfig?.maxIn ?? 0n;
449
456
  const validCap = pendingCap.validAt >= timestamp
450
457
  ? blue_sdk_1.MathLib.min(pendingCap.value, cap)
451
458
  : cap;
459
+ if (maxIn === 0n || validCap === 0n)
460
+ return { vault };
452
461
  const suppliable = blue_sdk_1.MathLib.zeroFloorSub(validCap, this.getAccrualPosition(vault, marketId).accrueInterest(timestamp)
453
462
  .supplyAssets);
463
+ if (suppliable === 0n)
464
+ return { vault };
454
465
  const marketWithdrawals = this.getVault(vault)
455
466
  .withdrawQueue.filter((srcMarketId) => srcMarketId !== marketId &&
456
467
  !withdrawals.some((withdrawal) => withdrawal.id === srcMarketId && withdrawal.vault === vault))
457
468
  .map((srcMarketId) => {
458
469
  const withdrawal = (0, morpho_ts_1._try)(() => {
459
- const srcPosition = this.getAccrualPosition(vault, srcMarketId).accrueInterest(timestamp);
460
- const targetUtilizationLiquidity = srcPosition.market.getWithdrawToUtilization(maxWithdrawalUtilization[srcMarketId] ??
461
- defaultMaxWithdrawalUtilization);
462
470
  const srcConfig = this.getVaultMarketConfig(vault, srcMarketId);
463
- if (!srcConfig.enabled)
471
+ const maxOut = srcConfig.publicAllocatorConfig?.maxOut ?? 0n;
472
+ if (!srcConfig.enabled || maxOut === 0n)
473
+ return { id: srcMarketId, assets: 0n };
474
+ const rawSrcPosition = this.getAccrualPosition(vault, srcMarketId);
475
+ if (rawSrcPosition.supplyShares === 0n)
464
476
  return { id: srcMarketId, assets: 0n };
477
+ const srcPosition = rawSrcPosition.accrueInterest(timestamp);
478
+ const targetUtilizationLiquidity = srcPosition.market.getWithdrawToUtilization(maxWithdrawalUtilization[srcMarketId] ??
479
+ defaultMaxWithdrawalUtilization);
465
480
  return {
466
481
  id: srcMarketId,
467
- assets: blue_sdk_1.MathLib.min(srcPosition.supplyAssets, targetUtilizationLiquidity, suppliable, publicAllocatorConfig?.maxIn ?? 0n, srcConfig.publicAllocatorConfig?.maxOut ?? 0n),
482
+ assets: blue_sdk_1.MathLib.min(srcPosition.supplyAssets, targetUtilizationLiquidity, suppliable, maxIn, maxOut),
468
483
  };
469
484
  }, blue_sdk_1.UnknownDataError);
470
485
  return withdrawal ?? { id: srcMarketId, assets: 0n };