@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
@@ -1,10 +1,10 @@
1
1
  import { MarketParams, MathLib, VaultV2BluePublicAllocatorConfigUtils, } from "@morpho-org/blue-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { compactSignatureToSignature, isAddressEqual, parseCompactSignature, parseSignature, size, zeroAddress, zeroHash, } from "viem";
3
+ import { isAddressEqual, zeroAddress, zeroHash, } from "viem";
4
4
  import { addTransactionMetadata, validateNativeAsset, } from "../../helpers/index.js";
5
5
  import { validateVaultV2BlueReallocations } from "../../helpers/validate.js";
6
6
  import { AmbiguousRequirementSignaturesError, BundlesRequirementSignatureMismatchError, DepositOwnerMismatchError, NativeFundingAmountMismatchError, NegativeInputError, ReallocationLoanTokenMismatchError, selectRequirementSignatures, UnexpectedRequirementSignatureError, } from "../../types/index.js";
7
- import { normalizeBundlesCommonParams } from "../bundles/common.js";
7
+ import { normalizeBundlesCommonParams, normalizeBundlesSignature, } from "../bundles/common.js";
8
8
  import { getBundlesTokenPermit, } from "../bundles/index.js";
9
9
  const EMPTY_SIGNED_AUTHORIZATION = {
10
10
  signature: { v: 0, r: zeroHash, s: zeroHash },
@@ -91,33 +91,12 @@ export const getBlueBundlesV1SignedAuthorization = (params) => {
91
91
  actual: String(authorizationSignature.action.args.deadline),
92
92
  });
93
93
  }
94
- const serializedSignature = authorizationSignature.args.signature;
95
- let parsed;
96
- try {
97
- parsed =
98
- size(serializedSignature) === 64
99
- ? compactSignatureToSignature(parseCompactSignature(serializedSignature))
100
- : parseSignature(serializedSignature);
101
- }
102
- catch (cause) {
103
- throw new BundlesRequirementSignatureMismatchError({
104
- field: "signature",
105
- expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
106
- actual: serializedSignature,
107
- cause,
108
- });
109
- }
110
- const v = parsed.v ??
111
- (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
112
- if (v == null) {
113
- throw new BundlesRequirementSignatureMismatchError({
114
- field: "signature",
115
- expected: "a signature containing v or yParity",
116
- actual: serializedSignature,
117
- });
118
- }
94
+ const signature = normalizeBundlesSignature(authorizationSignature.args.signature, (details) => new BundlesRequirementSignatureMismatchError({
95
+ field: "signature",
96
+ ...details,
97
+ }));
119
98
  return {
120
- signature: { v: Number(v), r: parsed.r, s: parsed.s },
99
+ signature,
121
100
  nonce: authorizationSignature.args.nonce,
122
101
  deadline: authorizationSignature.args.deadline,
123
102
  };
@@ -1,6 +1,7 @@
1
- import { encodeFunctionData, maxUint256 } from "viem";
1
+ import { encodeFunctionData } from "viem";
2
2
  import { blueBundlesV1Abi } from "../../abis.js";
3
- import { InputExceedsMaxError, NonPositiveInputError, } from "../../types/index.js";
3
+ import { validateUint256Field } from "../../helpers/validate.js";
4
+ import { NonPositiveInputError } from "../../types/index.js";
4
5
  import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1TokenPermit, normalizeBlueBundlesV1CommonParams, validateBlueBundlesV1NativeFunding, } from "./common.js";
5
6
  /**
6
7
  * Encodes a direct BlueBundlesV1 loan-asset supply transaction.
@@ -61,13 +62,7 @@ export const blueSupply = (params) => {
61
62
  if (assets <= 0n) {
62
63
  throw new NonPositiveInputError("assets", assets);
63
64
  }
64
- if (assets > maxUint256) {
65
- throw new InputExceedsMaxError({
66
- field: "assets",
67
- value: assets,
68
- max: maxUint256,
69
- });
70
- }
65
+ validateUint256Field("assets", assets);
71
66
  const common = {
72
67
  chainId,
73
68
  userAddress,
@@ -123,8 +123,21 @@ export declare const getBundlesTokenPermit: (params: {
123
123
  readonly amount: bigint;
124
124
  readonly requirementSignature?: TokenRequirementSignature;
125
125
  }) => BundlesTokenPermit;
126
- /** @internal Normalizes a compact or serialized ECDSA signature for bundles permit tuples. */
127
- export declare const normalizeBundlesSignature: (serializedSignature: Hex) => {
126
+ /**
127
+ * Normalizes a compact or serialized ECDSA signature for bundles permit tuples.
128
+ *
129
+ * @internal
130
+ *
131
+ * @param serializedSignature - Compact or serialized ECDSA signature.
132
+ * @param onInvalid - Error factory used when parsing or extracting the recovery identifier fails.
133
+ * @returns The normalized signature tuple.
134
+ * @throws {BundlesPermitMismatchError} when the signature is malformed.
135
+ */
136
+ export declare const normalizeBundlesSignature: (serializedSignature: Hex, onInvalid?: (details: {
137
+ readonly expected: string;
138
+ readonly actual: Hex;
139
+ readonly cause?: unknown;
140
+ }) => Error) => {
128
141
  readonly v: number;
129
142
  readonly r: Hex;
130
143
  readonly s: Hex;
@@ -188,6 +201,23 @@ export declare const selectBundlesSharesRequirementSignature: (signatures: reado
188
201
  readonly requiredShareAllowance: bigint | undefined;
189
202
  readonly expectedRequirement?: PermitAction;
190
203
  }) => Erc2612RequirementSignature | undefined;
204
+ /**
205
+ * Selects the ERC-2612 vault-share permit for one exit from its immutable operation fields alone.
206
+ *
207
+ * @internal
208
+ *
209
+ * @param signatures - Signatures passed to the operation's `buildTx` function.
210
+ * @param expected - Immutable spender, amount, and deadline required by the operation.
211
+ * @returns The matching ERC-2612 signature, or `undefined` when no signature is supplied.
212
+ * @throws {BundlesPermitMismatchError} when the signature is not ERC-2612 or its spender, amount or
213
+ * deadline differ from the operation's. The nonce is not checked here: it is onchain state the
214
+ * vault's `permit` verifies at execution.
215
+ */
216
+ export declare const selectBundlesSharesPermitSignature: (signatures: readonly RequirementSignature[] | undefined, expected: {
217
+ readonly spender: Address;
218
+ readonly amount: bigint;
219
+ readonly deadline: bigint;
220
+ }) => Erc2612RequirementSignature | undefined;
191
221
  /** @internal Returns the exact referral fee deducted from a fixed gross asset amount. */
192
222
  export declare const getBundlesReferralFeeAssets: (assets: bigint, referralFeePct: bigint) => bigint;
193
223
  /** @internal Finalizes a direct VaultBundlesV1 transaction with metadata and immutable action data. */
@@ -1,8 +1,9 @@
1
1
  import { MathLib } from "@morpho-org/blue-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
- import { compactSignatureToSignature, encodeAbiParameters, isAddressEqual, maxUint256, parseCompactSignature, parseSignature, size, zeroAddress, zeroHash, } from "viem";
3
+ import { compactSignatureToSignature, encodeAbiParameters, isAddressEqual, parseCompactSignature, parseSignature, size, zeroHash, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
- import { AmbiguousRequirementSignaturesError, BundlesPermitMismatchError, BundlesRequirementSignatureMismatchError, DepositAmountMismatchError, DepositAssetMismatchError, DepositOwnerMismatchError, DepositSpenderMismatchError, InputExceedsMaxError, MixedBundlesFundingError, NegativeInputError, NonPositiveInputError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, selectRequirementSignatures, UnexpectedRequirementSignatureError, } from "../../types/index.js";
5
+ import { validateDeadline, validateReferralFee, } from "../../helpers/validate.js";
6
+ import { AmbiguousRequirementSignaturesError, BundlesPermitMismatchError, BundlesRequirementSignatureMismatchError, DepositAmountMismatchError, DepositAssetMismatchError, DepositOwnerMismatchError, DepositSpenderMismatchError, MixedBundlesFundingError, NegativeInputError, NonPositiveInputError, selectRequirementSignatures, UnexpectedRequirementSignatureError, } from "../../types/index.js";
6
7
  /** Numeric permit kinds consumed by `TokenLib.pullToken`. */
7
8
  export const BundlesPermitKind = {
8
9
  None: 0,
@@ -27,32 +28,12 @@ const EMPTY_TOKEN_PERMIT = {
27
28
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no recipient.
28
29
  */
29
30
  export const normalizeBundlesCommonParams = (params) => {
30
- if (params.deadline <= 0n) {
31
- throw new NonPositiveInputError("deadline", params.deadline);
32
- }
33
- if (params.deadline > maxUint256) {
34
- throw new InputExceedsMaxError({
35
- field: "deadline",
36
- value: params.deadline,
37
- max: maxUint256,
38
- });
39
- }
40
- const referralFeePct = params.referralFeePct ?? 0n;
41
- if (referralFeePct < 0n) {
42
- throw new NegativeInputError("referralFeePct", referralFeePct);
43
- }
44
- if (referralFeePct >= MathLib.WAD) {
45
- throw new ReferralFeePctExceededError(referralFeePct);
46
- }
47
- if (referralFeePct > 0n &&
48
- (params.referralFeeRecipient == null ||
49
- isAddressEqual(params.referralFeeRecipient, zeroAddress))) {
50
- throw new ReferralFeeRecipientMissingError();
51
- }
31
+ validateDeadline(params.deadline);
32
+ const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
52
33
  return {
53
34
  deadline: params.deadline,
54
35
  referralFeePct,
55
- referralFeeRecipient: params.referralFeeRecipient ?? zeroAddress,
36
+ referralFeeRecipient,
56
37
  };
57
38
  };
58
39
  /**
@@ -198,8 +179,17 @@ export const getBundlesTokenPermit = (params) => {
198
179
  ]),
199
180
  };
200
181
  };
201
- /** @internal Normalizes a compact or serialized ECDSA signature for bundles permit tuples. */
202
- export const normalizeBundlesSignature = (serializedSignature) => {
182
+ /**
183
+ * Normalizes a compact or serialized ECDSA signature for bundles permit tuples.
184
+ *
185
+ * @internal
186
+ *
187
+ * @param serializedSignature - Compact or serialized ECDSA signature.
188
+ * @param onInvalid - Error factory used when parsing or extracting the recovery identifier fails.
189
+ * @returns The normalized signature tuple.
190
+ * @throws {BundlesPermitMismatchError} when the signature is malformed.
191
+ */
192
+ export const normalizeBundlesSignature = (serializedSignature, onInvalid = (details) => new BundlesPermitMismatchError({ field: "signature", ...details })) => {
203
193
  let parsed;
204
194
  try {
205
195
  parsed =
@@ -208,8 +198,7 @@ export const normalizeBundlesSignature = (serializedSignature) => {
208
198
  : parseSignature(serializedSignature);
209
199
  }
210
200
  catch (cause) {
211
- throw new BundlesPermitMismatchError({
212
- field: "signature",
201
+ throw onInvalid({
213
202
  expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
214
203
  actual: serializedSignature,
215
204
  cause,
@@ -218,8 +207,7 @@ export const normalizeBundlesSignature = (serializedSignature) => {
218
207
  const normalizedV = parsed.v ??
219
208
  (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
220
209
  if (normalizedV == null) {
221
- throw new BundlesPermitMismatchError({
222
- field: "signature",
210
+ throw onInvalid({
223
211
  expected: "a signature containing v or yParity",
224
212
  actual: serializedSignature,
225
213
  });
@@ -441,6 +429,55 @@ export const selectBundlesSharesRequirementSignature = (signatures, prepared) =>
441
429
  validatePreparedBundlesRequirementSignature(selectedPermit, prepared.expectedRequirement);
442
430
  return selectedPermit;
443
431
  };
432
+ /**
433
+ * Selects the ERC-2612 vault-share permit for one exit from its immutable operation fields alone.
434
+ *
435
+ * @internal
436
+ *
437
+ * @param signatures - Signatures passed to the operation's `buildTx` function.
438
+ * @param expected - Immutable spender, amount, and deadline required by the operation.
439
+ * @returns The matching ERC-2612 signature, or `undefined` when no signature is supplied.
440
+ * @throws {BundlesPermitMismatchError} when the signature is not ERC-2612 or its spender, amount or
441
+ * deadline differ from the operation's. The nonce is not checked here: it is onchain state the
442
+ * vault's `permit` verifies at execution.
443
+ */
444
+ export const selectBundlesSharesPermitSignature = (signatures, expected) => {
445
+ const { permit } = selectRequirementSignatures(signatures, { permit: true });
446
+ if (permit == null)
447
+ return undefined;
448
+ const { action } = permit;
449
+ if (action.type !== "permit") {
450
+ throw new BundlesPermitMismatchError({
451
+ field: "type",
452
+ expected: "permit",
453
+ actual: action.type,
454
+ });
455
+ }
456
+ if (!isAddressEqual(action.args.spender, expected.spender)) {
457
+ throw new BundlesPermitMismatchError({
458
+ field: "spender",
459
+ expected: expected.spender,
460
+ actual: action.args.spender,
461
+ });
462
+ }
463
+ if (permit.args.amount !== expected.amount ||
464
+ action.args.amount !== expected.amount) {
465
+ throw new BundlesPermitMismatchError({
466
+ field: "amount",
467
+ expected: String(expected.amount),
468
+ actual: String(permit.args.amount),
469
+ });
470
+ }
471
+ if (permit.args.deadline !== expected.deadline ||
472
+ action.args.deadline !== expected.deadline) {
473
+ throw new BundlesPermitMismatchError({
474
+ field: "deadline",
475
+ expected: String(expected.deadline),
476
+ actual: String(permit.args.deadline),
477
+ });
478
+ }
479
+ return { args: permit.args, action };
480
+ };
444
481
  /** @internal Returns the exact referral fee deducted from a fixed gross asset amount. */
445
482
  export const getBundlesReferralFeeAssets = (assets, referralFeePct) => MathLib.mulDivDown(assets, referralFeePct, MathLib.WAD);
446
483
  /** @internal Finalizes a direct VaultBundlesV1 transaction with metadata and immutable action data. */
@@ -28,6 +28,9 @@ import { type AuthorizationRequirementSignature, type BlueAuthorizationAction, t
28
28
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
29
29
  * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
30
30
  * GeneralAdapter1 nor its BlueBundlesV1 operator.
31
+ * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
32
+ * @throws {InputExceedsMaxError} when a provided `deadline` exceeds `uint256`.
33
+ * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
31
34
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
32
35
  * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
33
36
  * @example
@@ -1,8 +1,9 @@
1
1
  import { getChainAddresses } from "@morpho-org/blue-sdk";
2
2
  import { blueAbi } from "@morpho-org/blue-sdk-viem";
3
3
  import { deepFreeze, Time } from "@morpho-org/morpho-ts";
4
- import { encodeFunctionData, isAddressEqual, maxUint256, publicActions, } from "viem";
5
- import { ChainIdMismatchError, ExpiredDeadlineError, InputExceedsMaxError, NonPositiveInputError, UnsupportedAuthorizationOperatorError, } from "../../../types/index.js";
4
+ import { encodeFunctionData, isAddressEqual, publicActions, } from "viem";
5
+ import { validateDeadline } from "../../../helpers/validate.js";
6
+ import { ChainIdMismatchError, ExpiredDeadlineError, UnsupportedAuthorizationOperatorError, } from "../../../types/index.js";
6
7
  import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureAuthorization.js";
7
8
  /**
8
9
  * Resolves whether a supported operator needs Blue authorization for the given user, and returns
@@ -31,6 +32,9 @@ import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureA
31
32
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
32
33
  * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
33
34
  * GeneralAdapter1 nor its BlueBundlesV1 operator.
35
+ * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
36
+ * @throws {InputExceedsMaxError} when a provided `deadline` exceeds `uint256`.
37
+ * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
34
38
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
35
39
  * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
36
40
  * @example
@@ -77,16 +81,7 @@ export const getBlueAuthorizationRequirement = async (params) => {
77
81
  // one before the RPC reads so the caller never signs an authorization that cannot be encoded
78
82
  // or would revert on-chain. An omitted deadline defaults downstream to two hours from now.
79
83
  if (params.deadline != null) {
80
- if (params.deadline <= 0n) {
81
- throw new NonPositiveInputError("deadline", params.deadline);
82
- }
83
- if (params.deadline > maxUint256) {
84
- throw new InputExceedsMaxError({
85
- field: "deadline",
86
- value: params.deadline,
87
- max: maxUint256,
88
- });
89
- }
84
+ validateDeadline(params.deadline);
90
85
  const timestamp = Time.timestamp();
91
86
  if (params.deadline <= timestamp) {
92
87
  throw new ExpiredDeadlineError(params.deadline, timestamp);
@@ -114,6 +109,7 @@ export const getBlueAuthorizationRequirement = async (params) => {
114
109
  return null;
115
110
  }
116
111
  return encodeBlueSignatureAuthorization(viemClient, {
112
+ owner: userAddress,
117
113
  authorized,
118
114
  chainId,
119
115
  nonce,
@@ -1,2 +1 @@
1
1
  export * from "./getBlueAuthorizationRequirement.js";
2
- export * from "./getUnusedPermit2Nonce.js";
@@ -1,2 +1 @@
1
1
  export * from "./getBlueAuthorizationRequirement.js";
2
- export * from "./getUnusedPermit2Nonce.js";
@@ -1,13 +1,15 @@
1
1
  import type { Address } from "@morpho-org/blue-sdk";
2
- import { type Client } from "viem";
2
+ import type { Client } from "viem";
3
3
  import { type AuthorizationRequirementSignature, type Requirement } from "../../../types/index.js";
4
4
  /** Parameters for {@link encodeBlueSignatureAuthorization}. */
5
5
  interface EncodeBlueSignatureAuthorizationParams {
6
+ /** Account granting the authorization and signing it (the Morpho `authorizer`). */
7
+ owner: Address;
6
8
  /** Operator to authorize on Morpho, such as GeneralAdapter1 or BlueBundlesV1. */
7
9
  authorized: Address;
8
10
  /** Target chain id; must match `viemClient.chain.id`. */
9
11
  chainId: number;
10
- /** The signer's current Morpho authorization nonce. */
12
+ /** The owner's current Morpho authorization nonce. */
11
13
  nonce: bigint;
12
14
  /** Whether to grant (`true`, default) or revoke (`false`) the authorization. */
13
15
  isAuthorized?: boolean;
@@ -21,23 +23,27 @@ interface EncodeBlueSignatureAuthorizationParams {
21
23
  *
22
24
  * The returned `Requirement.sign()` produces the EIP-712 signature over Morpho's `Authorization`
23
25
  * typed data, verifies it against the connected account, and returns a deep-frozen
24
- * `RequirementSignature` the selected transaction route consumes. Deadline defaults to two hours
25
- * from `Time.timestamp()`.
26
+ * `RequirementSignature` the selected transaction route consumes. The requirement's
27
+ * `action.typedData` holds that EIP-712 payload so it can be inspected or displayed before signing.
28
+ * Deadline defaults to two hours from `Time.timestamp()`.
26
29
  *
27
30
  * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
28
31
  * @param params - Authorization encoding parameters.
32
+ * @param params.owner - Account granting the authorization and signing it (the Morpho `authorizer`).
29
33
  * @param params.authorized - Operator to authorize, such as GeneralAdapter1 or BlueBundlesV1.
30
34
  * @param params.chainId - Target chain id.
31
- * @param params.nonce - The signer's current Morpho authorization nonce.
35
+ * @param params.nonce - The owner's current Morpho authorization nonce.
32
36
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
33
37
  * @param params.deadline - Optional signature deadline in seconds.
34
- * @returns A `Requirement` whose `sign(client, userAddress)` produces the deep-frozen signature.
38
+ * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
39
+ * `sign(client, userAddress)` produces the deep-frozen signature.
35
40
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
36
41
  * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
37
42
  * @throws {InputExceedsMaxError} when a provided `deadline` exceeds `uint256`.
38
43
  * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
39
44
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
40
- * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
45
+ * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
46
+ * client account differs from `userAddress`.
41
47
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
42
48
  * @example
43
49
  * ```ts
@@ -47,11 +53,12 @@ interface EncodeBlueSignatureAuthorizationParams {
47
53
  *
48
54
  * const client = createWalletClient({ chain: mainnet, transport: http() });
49
55
  * const requirement = await encodeBlueSignatureAuthorization(client, {
56
+ * owner,
50
57
  * authorized: generalAdapter1,
51
58
  * chainId: 1,
52
59
  * nonce: 0n,
53
60
  * });
54
- * // requirement satisfies Requirement
61
+ * // Inspect the EIP-712 payload (requirement.action.typedData) or sign via requirement.sign(...).
55
62
  * ```
56
63
  */
57
64
  export declare const encodeBlueSignatureAuthorization: (viemClient: Client, params: EncodeBlueSignatureAuthorizationParams) => Promise<Requirement<AuthorizationRequirementSignature>>;
@@ -1,8 +1,8 @@
1
1
  import { getAuthorizationTypedData } from "@morpho-org/blue-sdk-viem";
2
2
  import { deepFreeze, Time } from "@morpho-org/morpho-ts";
3
- import { maxUint256 } from "viem";
4
3
  import { signAndVerifyTypedData } from "../../../helpers/signAndVerifyTypedData.js";
5
- import { ChainIdMismatchError, ExpiredDeadlineError, InputExceedsMaxError, NonPositiveInputError, } from "../../../types/index.js";
4
+ import { validateDeadline, validateUserAddress, } from "../../../helpers/validate.js";
5
+ import { ChainIdMismatchError, ExpiredDeadlineError, } from "../../../types/index.js";
6
6
  /**
7
7
  * Builds a Morpho authorization `Requirement` that, once signed, lets `authorized` operate on
8
8
  * Morpho on the signer's behalf. Bundler3 consumes the result through `setAuthorizationWithSig`;
@@ -10,23 +10,27 @@ import { ChainIdMismatchError, ExpiredDeadlineError, InputExceedsMaxError, NonPo
10
10
  *
11
11
  * The returned `Requirement.sign()` produces the EIP-712 signature over Morpho's `Authorization`
12
12
  * typed data, verifies it against the connected account, and returns a deep-frozen
13
- * `RequirementSignature` the selected transaction route consumes. Deadline defaults to two hours
14
- * from `Time.timestamp()`.
13
+ * `RequirementSignature` the selected transaction route consumes. The requirement's
14
+ * `action.typedData` holds that EIP-712 payload so it can be inspected or displayed before signing.
15
+ * Deadline defaults to two hours from `Time.timestamp()`.
15
16
  *
16
17
  * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
17
18
  * @param params - Authorization encoding parameters.
19
+ * @param params.owner - Account granting the authorization and signing it (the Morpho `authorizer`).
18
20
  * @param params.authorized - Operator to authorize, such as GeneralAdapter1 or BlueBundlesV1.
19
21
  * @param params.chainId - Target chain id.
20
- * @param params.nonce - The signer's current Morpho authorization nonce.
22
+ * @param params.nonce - The owner's current Morpho authorization nonce.
21
23
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
22
24
  * @param params.deadline - Optional signature deadline in seconds.
23
- * @returns A `Requirement` whose `sign(client, userAddress)` produces the deep-frozen signature.
25
+ * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
26
+ * `sign(client, userAddress)` produces the deep-frozen signature.
24
27
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
25
28
  * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
26
29
  * @throws {InputExceedsMaxError} when a provided `deadline` exceeds `uint256`.
27
30
  * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
28
31
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
29
- * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
32
+ * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
33
+ * client account differs from `userAddress`.
30
34
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
31
35
  * @example
32
36
  * ```ts
@@ -36,15 +40,16 @@ import { ChainIdMismatchError, ExpiredDeadlineError, InputExceedsMaxError, NonPo
36
40
  *
37
41
  * const client = createWalletClient({ chain: mainnet, transport: http() });
38
42
  * const requirement = await encodeBlueSignatureAuthorization(client, {
43
+ * owner,
39
44
  * authorized: generalAdapter1,
40
45
  * chainId: 1,
41
46
  * nonce: 0n,
42
47
  * });
43
- * // requirement satisfies Requirement
48
+ * // Inspect the EIP-712 payload (requirement.action.typedData) or sign via requirement.sign(...).
44
49
  * ```
45
50
  */
46
51
  export const encodeBlueSignatureAuthorization = async (viemClient, params) => {
47
- const { authorized, chainId, nonce, isAuthorized = true } = params;
52
+ const { owner, authorized, chainId, nonce, isAuthorized = true } = params;
48
53
  if (viemClient.chain?.id !== chainId) {
49
54
  throw new ChainIdMismatchError(viemClient.chain?.id, chainId);
50
55
  }
@@ -54,30 +59,25 @@ export const encodeBlueSignatureAuthorization = async (viemClient, params) => {
54
59
  // `getBlueAuthorizationRequirement` resolver guards. An omitted deadline defaults to two hours
55
60
  // from now and is always valid.
56
61
  if (params.deadline != null) {
57
- if (params.deadline <= 0n) {
58
- throw new NonPositiveInputError("deadline", params.deadline);
59
- }
60
- if (params.deadline > maxUint256) {
61
- throw new InputExceedsMaxError({
62
- field: "deadline",
63
- value: params.deadline,
64
- max: maxUint256,
65
- });
66
- }
62
+ validateDeadline(params.deadline);
67
63
  const timestamp = Time.timestamp();
68
64
  if (params.deadline <= timestamp) {
69
65
  throw new ExpiredDeadlineError(params.deadline, timestamp);
70
66
  }
71
67
  }
72
68
  const deadline = params.deadline ?? Time.timestamp() + Time.s.from.h(2n);
69
+ const typedData = deepFreeze(getAuthorizationTypedData({ authorizer: owner, authorized, isAuthorized, nonce, deadline }, chainId));
73
70
  const action = {
74
71
  type: "authorization",
75
72
  args: { authorized, isAuthorized, deadline },
73
+ typedData,
76
74
  };
77
75
  return {
78
76
  action,
79
77
  async sign(client, userAddress) {
80
- const typedData = getAuthorizationTypedData({ authorizer: userAddress, authorized, isAuthorized, nonce, deadline }, chainId);
78
+ // The authorizer is fixed at build time (the fetched nonce is owner-specific), so a different
79
+ // signer cannot produce a valid authorization for it.
80
+ validateUserAddress(userAddress, owner);
81
81
  const signature = await signAndVerifyTypedData({
82
82
  client,
83
83
  userAddress,
@@ -85,7 +85,7 @@ export const encodeBlueSignatureAuthorization = async (viemClient, params) => {
85
85
  });
86
86
  return deepFreeze({
87
87
  args: {
88
- owner: userAddress,
88
+ owner,
89
89
  authorized,
90
90
  isAuthorized,
91
91
  nonce,
@@ -1,9 +1,11 @@
1
1
  import type { Address } from "@morpho-org/blue-sdk";
2
- import { type Client } from "viem";
2
+ import type { Client } from "viem";
3
3
  import { type Erc2612RequirementSignature, type Requirement } from "../../../types/index.js";
4
4
  /** Parameters for {@link encodeErc20Permit}. */
5
5
  interface EncodeErc20PermitParams {
6
6
  token: Address;
7
+ /** Account that owns the tokens and signs the permit. */
8
+ owner: Address;
7
9
  spender: Address;
8
10
  amount: bigint;
9
11
  chainId: number;
@@ -17,20 +19,23 @@ interface EncodeErc20PermitParams {
17
19
  *
18
20
  * Reads token metadata via `fetchToken`. The returned `Requirement.sign()` produces the EIP-712
19
21
  * signature, verifies it against the connected account, and returns a `RequirementSignature`
20
- * the selected transaction route can consume. Deadline defaults to two hours from
21
- * `Time.timestamp()`.
22
+ * the selected transaction route can consume. The requirement's `action.typedData` holds that
23
+ * EIP-712 payload so it can be inspected or displayed before signing. Deadline defaults to two
24
+ * hours from `Time.timestamp()`.
22
25
  *
23
26
  * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
24
27
  * @param params - Permit encoding parameters.
25
28
  * @param params.token - ERC-20 token address (must support EIP-2612).
29
+ * @param params.owner - Account that owns the tokens and signs the permit.
26
30
  * @param params.spender - Permit spender. Must be GeneralAdapter1, MidnightBundles,
27
31
  * VaultBundlesV1, or BlueBundlesV1 for the chain.
28
32
  * @param params.amount - Permit allowance amount.
29
33
  * @param params.chainId - Target chain id.
30
- * @param params.nonce - The user's current EIP-2612 nonce on `token`.
34
+ * @param params.nonce - The owner's current EIP-2612 nonce on `token`.
31
35
  * @param params.supportDeployless - Whether `fetchToken` should use deployless multicall.
32
36
  * @param params.deadline - Signature expiration timestamp. Defaults to two hours from now.
33
- * @returns A `Requirement` whose `sign(client, userAddress)` produces the deep-frozen signature.
37
+ * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
38
+ * `sign(client, userAddress)` produces the deep-frozen signature.
34
39
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
35
40
  * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
36
41
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not GeneralAdapter1,
@@ -40,7 +45,8 @@ interface EncodeErc20PermitParams {
40
45
  * @throws {ExpiredDeadlineError} when an explicit `deadline` is positive but not in the future.
41
46
  * @throws {viem.BaseError} when the token metadata read fails with no fallback left.
42
47
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
43
- * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
48
+ * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
49
+ * client account differs from `userAddress`.
44
50
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
45
51
  * @example
46
52
  * ```ts
@@ -51,12 +57,15 @@ interface EncodeErc20PermitParams {
51
57
  * const client = createWalletClient({ chain: mainnet, transport: http() });
52
58
  * const requirement = await encodeErc20Permit(client, {
53
59
  * token: USDC, // Must implement standard ERC-2612. DAI is routed through Permit2 by requirement helpers.
60
+ * owner,
54
61
  * spender: generalAdapter1,
55
62
  * amount: 1_000_000n,
56
63
  * chainId: 1,
57
64
  * nonce: 0n,
58
65
  * });
59
- * // requirement satisfies Requirement
66
+ * // Inspect the EIP-712 payload, then sign via the requirement:
67
+ * const typedData = requirement.action.typedData;
68
+ * const signed = await requirement.sign(client, owner);
60
69
  * ```
61
70
  */
62
71
  export declare const encodeErc20Permit: (viemClient: Client, params: EncodeErc20PermitParams) => Promise<Requirement<Erc2612RequirementSignature>>;