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

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 (243) hide show
  1. package/MIGRATION-v5-to-v6.md +404 -0
  2. package/README.md +127 -69
  3. package/lib/cjs/abis.d.ts +210 -0
  4. package/lib/cjs/abis.js +142 -2
  5. package/lib/cjs/actions/blue/borrow.d.ts +62 -61
  6. package/lib/cjs/actions/blue/borrow.js +48 -80
  7. package/lib/cjs/actions/blue/common.d.ts +86 -0
  8. package/lib/cjs/actions/blue/common.js +205 -0
  9. package/lib/cjs/actions/blue/refinance.d.ts +72 -112
  10. package/lib/cjs/actions/blue/refinance.js +97 -199
  11. package/lib/cjs/actions/blue/repay.d.ts +72 -68
  12. package/lib/cjs/actions/blue/repay.js +56 -118
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  14. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +148 -137
  15. package/lib/cjs/actions/blue/supply.d.ts +62 -45
  16. package/lib/cjs/actions/blue/supply.js +94 -70
  17. package/lib/cjs/actions/blue/supplyCollateral.d.ts +63 -40
  18. package/lib/cjs/actions/blue/supplyCollateral.js +52 -69
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -120
  21. package/lib/cjs/actions/blue/withdraw.d.ts +68 -79
  22. package/lib/cjs/actions/blue/withdraw.js +101 -97
  23. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +56 -28
  24. package/lib/cjs/actions/blue/withdrawCollateral.js +45 -50
  25. package/lib/cjs/actions/bundles/common.d.ts +200 -0
  26. package/lib/cjs/actions/bundles/common.js +469 -0
  27. package/lib/cjs/actions/bundles/index.d.ts +3 -0
  28. package/lib/cjs/actions/bundles/index.js +23 -0
  29. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  30. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +125 -0
  31. package/lib/cjs/actions/index.d.ts +2 -1
  32. package/lib/cjs/actions/index.js +1 -0
  33. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  34. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  35. package/lib/cjs/actions/midnight/takeBorrow.d.ts +2 -2
  36. package/lib/cjs/actions/midnight/takeBorrow.js +2 -2
  37. package/lib/cjs/actions/midnight/takeLend.d.ts +2 -2
  38. package/lib/cjs/actions/midnight/takeLend.js +2 -2
  39. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  40. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  41. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  42. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  43. package/lib/cjs/actions/requirements/blue/index.d.ts +1 -0
  44. package/lib/cjs/actions/requirements/blue/index.js +1 -0
  45. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  46. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  47. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  48. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +8 -2
  49. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  50. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +39 -6
  51. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +61 -0
  52. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +123 -0
  53. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  54. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  55. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  56. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  57. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  58. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +6 -4
  59. package/lib/cjs/actions/requirements/getRequirementsApproval.js +6 -4
  60. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  61. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  62. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  63. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +18 -66
  64. package/lib/cjs/actions/vaultV1/deposit.d.ts +73 -57
  65. package/lib/cjs/actions/vaultV1/deposit.js +110 -109
  66. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +43 -66
  67. package/lib/cjs/actions/vaultV1/migrateToV2.js +91 -104
  68. package/lib/cjs/actions/vaultV1/redeem.d.ts +30 -23
  69. package/lib/cjs/actions/vaultV1/redeem.js +56 -33
  70. package/lib/cjs/actions/vaultV1/withdraw.d.ts +58 -24
  71. package/lib/cjs/actions/vaultV1/withdraw.js +86 -34
  72. package/lib/cjs/actions/vaultV2/deposit.d.ts +74 -57
  73. package/lib/cjs/actions/vaultV2/deposit.js +111 -109
  74. package/lib/cjs/actions/vaultV2/redeem.d.ts +30 -24
  75. package/lib/cjs/actions/vaultV2/redeem.js +56 -34
  76. package/lib/cjs/actions/vaultV2/withdraw.d.ts +58 -25
  77. package/lib/cjs/actions/vaultV2/withdraw.js +86 -35
  78. package/lib/cjs/bundler/actions.d.ts +4 -4
  79. package/lib/cjs/bundler/actions.js +4 -4
  80. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  81. package/lib/cjs/client/morphoViemExtension.js +2 -1
  82. package/lib/cjs/entities/blue/blue.d.ts +806 -374
  83. package/lib/cjs/entities/blue/blue.js +449 -696
  84. package/lib/cjs/entities/index.d.ts +2 -0
  85. package/lib/cjs/entities/index.js +15 -0
  86. package/lib/cjs/entities/midnight/midnight.d.ts +2 -2
  87. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +87 -0
  88. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +203 -0
  89. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  90. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +74 -0
  91. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  92. package/lib/cjs/entities/requirements/index.js +17 -0
  93. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +348 -98
  94. package/lib/cjs/entities/vaultV1/vaultV1.js +322 -120
  95. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +221 -68
  96. package/lib/cjs/entities/vaultV2/vaultV2.js +219 -77
  97. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +3 -9
  98. package/lib/cjs/helpers/computeVaultV1Reallocations.js +3 -9
  99. package/lib/cjs/helpers/index.d.ts +2 -1
  100. package/lib/cjs/helpers/index.js +5 -1
  101. package/lib/cjs/helpers/referralFee.d.ts +21 -0
  102. package/lib/cjs/helpers/referralFee.js +35 -0
  103. package/lib/cjs/helpers/slippage.d.ts +90 -1
  104. package/lib/cjs/helpers/slippage.js +123 -0
  105. package/lib/cjs/helpers/validate.d.ts +16 -23
  106. package/lib/cjs/helpers/validate.js +41 -48
  107. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  108. package/lib/cjs/helpers/validateRequirementSpender.js +3 -0
  109. package/lib/cjs/index.d.ts +1 -0
  110. package/lib/cjs/index.js +1 -0
  111. package/lib/cjs/types/action.d.ts +303 -210
  112. package/lib/cjs/types/action.js +29 -2
  113. package/lib/cjs/types/client.d.ts +9 -0
  114. package/lib/cjs/types/error.d.ts +193 -18
  115. package/lib/cjs/types/error.js +267 -24
  116. package/lib/cjs/types/sharedLiquidity.d.ts +0 -7
  117. package/lib/esm/abis.d.ts +210 -0
  118. package/lib/esm/abis.js +140 -0
  119. package/lib/esm/actions/blue/borrow.d.ts +62 -61
  120. package/lib/esm/actions/blue/borrow.js +48 -80
  121. package/lib/esm/actions/blue/common.d.ts +86 -0
  122. package/lib/esm/actions/blue/common.js +193 -0
  123. package/lib/esm/actions/blue/refinance.d.ts +72 -112
  124. package/lib/esm/actions/blue/refinance.js +98 -200
  125. package/lib/esm/actions/blue/repay.d.ts +72 -68
  126. package/lib/esm/actions/blue/repay.js +56 -118
  127. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  128. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  129. package/lib/esm/actions/blue/supply.d.ts +62 -45
  130. package/lib/esm/actions/blue/supply.js +94 -70
  131. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  132. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  133. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  134. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -121
  135. package/lib/esm/actions/blue/withdraw.d.ts +68 -79
  136. package/lib/esm/actions/blue/withdraw.js +100 -96
  137. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  138. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  139. package/lib/esm/actions/bundles/common.d.ts +200 -0
  140. package/lib/esm/actions/bundles/common.js +457 -0
  141. package/lib/esm/actions/bundles/index.d.ts +3 -0
  142. package/lib/esm/actions/bundles/index.js +2 -0
  143. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  144. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +121 -0
  145. package/lib/esm/actions/index.d.ts +2 -1
  146. package/lib/esm/actions/index.js +1 -0
  147. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  148. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  149. package/lib/esm/actions/midnight/takeBorrow.d.ts +2 -2
  150. package/lib/esm/actions/midnight/takeBorrow.js +2 -2
  151. package/lib/esm/actions/midnight/takeLend.d.ts +2 -2
  152. package/lib/esm/actions/midnight/takeLend.js +2 -2
  153. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  154. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  155. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  156. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  157. package/lib/esm/actions/requirements/blue/index.d.ts +1 -0
  158. package/lib/esm/actions/requirements/blue/index.js +1 -0
  159. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  160. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  161. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  162. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -3
  163. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  164. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +40 -7
  165. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +61 -0
  166. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +119 -0
  167. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  168. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  169. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  170. package/lib/esm/actions/requirements/encode/index.js +1 -0
  171. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  172. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +6 -4
  173. package/lib/esm/actions/requirements/getRequirementsApproval.js +6 -4
  174. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  175. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  176. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  177. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +19 -67
  178. package/lib/esm/actions/vaultV1/deposit.d.ts +73 -57
  179. package/lib/esm/actions/vaultV1/deposit.js +112 -111
  180. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +43 -66
  181. package/lib/esm/actions/vaultV1/migrateToV2.js +93 -106
  182. package/lib/esm/actions/vaultV1/redeem.d.ts +30 -23
  183. package/lib/esm/actions/vaultV1/redeem.js +56 -33
  184. package/lib/esm/actions/vaultV1/withdraw.d.ts +58 -24
  185. package/lib/esm/actions/vaultV1/withdraw.js +86 -34
  186. package/lib/esm/actions/vaultV2/deposit.d.ts +74 -57
  187. package/lib/esm/actions/vaultV2/deposit.js +113 -111
  188. package/lib/esm/actions/vaultV2/redeem.d.ts +30 -24
  189. package/lib/esm/actions/vaultV2/redeem.js +56 -34
  190. package/lib/esm/actions/vaultV2/withdraw.d.ts +58 -25
  191. package/lib/esm/actions/vaultV2/withdraw.js +86 -35
  192. package/lib/esm/bundler/actions.d.ts +4 -4
  193. package/lib/esm/bundler/actions.js +4 -4
  194. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  195. package/lib/esm/client/morphoViemExtension.js +2 -1
  196. package/lib/esm/entities/blue/blue.d.ts +806 -374
  197. package/lib/esm/entities/blue/blue.js +455 -702
  198. package/lib/esm/entities/index.d.ts +2 -0
  199. package/lib/esm/entities/index.js +1 -0
  200. package/lib/esm/entities/midnight/midnight.d.ts +2 -2
  201. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +87 -0
  202. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +199 -0
  203. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  204. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +70 -0
  205. package/lib/esm/entities/requirements/index.d.ts +1 -0
  206. package/lib/esm/entities/requirements/index.js +1 -0
  207. package/lib/esm/entities/vaultV1/vaultV1.d.ts +348 -98
  208. package/lib/esm/entities/vaultV1/vaultV1.js +326 -124
  209. package/lib/esm/entities/vaultV2/vaultV2.d.ts +221 -68
  210. package/lib/esm/entities/vaultV2/vaultV2.js +222 -80
  211. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +3 -9
  212. package/lib/esm/helpers/computeVaultV1Reallocations.js +3 -9
  213. package/lib/esm/helpers/index.d.ts +2 -1
  214. package/lib/esm/helpers/index.js +2 -1
  215. package/lib/esm/helpers/referralFee.d.ts +21 -0
  216. package/lib/esm/helpers/referralFee.js +31 -0
  217. package/lib/esm/helpers/slippage.d.ts +90 -1
  218. package/lib/esm/helpers/slippage.js +122 -2
  219. package/lib/esm/helpers/validate.d.ts +16 -23
  220. package/lib/esm/helpers/validate.js +40 -48
  221. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  222. package/lib/esm/helpers/validateRequirementSpender.js +3 -0
  223. package/lib/esm/index.d.ts +1 -0
  224. package/lib/esm/index.js +1 -0
  225. package/lib/esm/types/action.d.ts +303 -210
  226. package/lib/esm/types/action.js +28 -2
  227. package/lib/esm/types/client.d.ts +9 -0
  228. package/lib/esm/types/error.d.ts +193 -18
  229. package/lib/esm/types/error.js +252 -21
  230. package/lib/esm/types/sharedLiquidity.d.ts +0 -7
  231. package/package.json +6 -5
  232. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  233. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  234. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  235. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  236. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  237. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  238. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  239. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  240. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  241. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  242. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  243. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveBundlesTokenRequirements = void 0;
4
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
+ const viem_1 = require("viem");
6
+ const validate_js_1 = require("../../helpers/validate.js");
7
+ const validateRequirementSpender_js_1 = require("../../helpers/validateRequirementSpender.js");
8
+ const index_js_1 = require("../../types/index.js");
9
+ const index_js_2 = require("../requirements/encode/index.js");
10
+ const getRequirementsApproval_js_1 = require("../requirements/getRequirementsApproval.js");
11
+ /**
12
+ * Resolves pre-fetched allowance and Permit2 nonce state into ordered bundles requirements.
13
+ *
14
+ * `spender` is validated against the chain registry's fixed bundles deployments, and the
15
+ * SignatureTransfer branch resolves canonical Permit2 from that same registry, so no caller can
16
+ * route an approval or a signed pull to an address the SDK does not know.
17
+ *
18
+ * The SignatureTransfer branch always places any ERC-20 approval to canonical Permit2 before the
19
+ * one-time signature requirement.
20
+ *
21
+ * @param params - Funding values, expected bundles spender, and pre-fetched state.
22
+ * @param params.token - ERC-20 token funded by the operation.
23
+ * @param params.spender - Registered fixed bundles contract that pulls the token; must be the
24
+ * chain's BlueBundlesV1 or VaultBundlesV1 deployment.
25
+ * @param params.owner - Account funding the operation and owning the Permit2 nonce bitmap.
26
+ * @param params.chainId - Target chain id used to resolve supported approval spenders and canonical Permit2.
27
+ * @param params.amount - Exact pull amount in the token's smallest unit; zero returns no requirements.
28
+ * @param params.deadline - Signature expiration as a Unix timestamp in seconds.
29
+ * @param params.state - Prefetched state for either classic approval or Permit2 SignatureTransfer.
30
+ * @param params.state.type - `approval` for a direct allowance or `permit2SignatureTransfer` for a signed pull.
31
+ * @param params.state.allowance - In the approval branch, current token allowance from `owner` to `spender`.
32
+ * @param params.state.approvalAmount - In the approval branch, allowance to set if needed; must cover `amount`.
33
+ * @param params.state.permit2Allowance - In the SignatureTransfer branch, current token allowance from `owner` to canonical Permit2.
34
+ * @param params.state.permit2Nonce - In the SignatureTransfer branch, caller-selected unused uint256 unordered nonce.
35
+ * @param params.state.nonceBitmap - In the SignatureTransfer branch, owner's Permit2 bitmap word at `permit2Nonce >> 8n`.
36
+ * @returns Ordered approval transactions and/or a Permit2 SignatureTransfer requirement.
37
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
38
+ * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not the chain's registered
39
+ * BlueBundlesV1 or VaultBundlesV1 deployment, including for a zero-amount request.
40
+ * @throws {NegativeInputError} when an amount or Permit2 nonce is negative.
41
+ * @throws {InputExceedsMaxError} when `amount` or the Permit2 nonce exceeds uint256.
42
+ * @throws {Permit2SignatureTransferNonceAlreadyUsedError} when the selected nonce bit is set.
43
+ * @throws {ApprovalAmountLessThanSpendAmountError} when a classic approval cannot cover the pull.
44
+ * @throws {UnknownAddressError} when the SignatureTransfer branch runs on a chain without canonical Permit2.
45
+ * @example
46
+ * ```ts
47
+ * import { resolveBundlesTokenRequirements } from "@morpho-org/morpho-sdk";
48
+ * import { getChainAddress } from "@morpho-org/morpho-ts";
49
+ * import { zeroAddress } from "viem";
50
+ *
51
+ * const requirements = resolveBundlesTokenRequirements({
52
+ * token: zeroAddress,
53
+ * spender: getChainAddress(1, "bundles.vaultBundlesV1"),
54
+ * owner: zeroAddress,
55
+ * chainId: 1,
56
+ * amount: 1_000_000n,
57
+ * deadline: 1_900_000_000n,
58
+ * state: { type: "approval", allowance: 1_000_000n, approvalAmount: 1_000_000n },
59
+ * });
60
+ * // requirements is empty because the allowance already covers the amount.
61
+ * ```
62
+ */
63
+ const resolveBundlesTokenRequirements = (params) => {
64
+ (0, validateRequirementSpender_js_1.validateRequirementSpender)({
65
+ chainId: params.chainId,
66
+ spender: params.spender,
67
+ allowed: ["blueBundlesV1", "vaultBundlesV1"],
68
+ });
69
+ // Reject invalid pulls before an approval encoder can cap the requested amount.
70
+ (0, validate_js_1.validateUint256Field)("amount", params.amount);
71
+ if (params.amount === 0n)
72
+ return [];
73
+ if (params.state.type === "approval") {
74
+ if (params.state.approvalAmount < params.amount) {
75
+ throw new index_js_1.ApprovalAmountLessThanSpendAmountError();
76
+ }
77
+ return (0, getRequirementsApproval_js_1.getRequirementsApproval)({
78
+ address: params.token,
79
+ chainId: params.chainId,
80
+ args: {
81
+ // Compare against the bounded pull to avoid redundant approvals and USDT zero-resets.
82
+ spender: params.spender,
83
+ spendAmount: params.amount,
84
+ approvalAmount: params.state.approvalAmount,
85
+ },
86
+ allowances: params.state.allowance,
87
+ });
88
+ }
89
+ if (params.state.permit2Nonce < 0n) {
90
+ throw new index_js_1.NegativeInputError("permit2Nonce", params.state.permit2Nonce);
91
+ }
92
+ if (params.state.permit2Nonce > viem_1.maxUint256) {
93
+ throw new index_js_1.InputExceedsMaxError({
94
+ field: "permit2Nonce",
95
+ value: params.state.permit2Nonce,
96
+ max: viem_1.maxUint256,
97
+ });
98
+ }
99
+ const bitPosition = params.state.permit2Nonce & 255n;
100
+ if ((params.state.nonceBitmap & (1n << bitPosition)) !== 0n) {
101
+ throw new index_js_1.Permit2SignatureTransferNonceAlreadyUsedError(params.owner, params.state.permit2Nonce);
102
+ }
103
+ const permit2 = (0, morpho_ts_1.getChainAddress)(params.chainId, "permit2");
104
+ return [
105
+ ...(0, getRequirementsApproval_js_1.getRequirementsApproval)({
106
+ address: params.token,
107
+ chainId: params.chainId,
108
+ args: {
109
+ spender: permit2,
110
+ spendAmount: params.amount,
111
+ approvalAmount: viem_1.maxUint256,
112
+ },
113
+ allowances: params.state.permit2Allowance,
114
+ }),
115
+ (0, index_js_2.encodeErc20Permit2SignatureTransfer)({
116
+ token: params.token,
117
+ spender: params.spender,
118
+ amount: params.amount,
119
+ chainId: params.chainId,
120
+ nonce: params.state.permit2Nonce,
121
+ deadline: params.deadline,
122
+ }),
123
+ ];
124
+ };
125
+ exports.resolveBundlesTokenRequirements = resolveBundlesTokenRequirements;
@@ -1,8 +1,9 @@
1
- export type { BlueActions } from "../entities/blue/index.js";
1
+ export type { BlueActions, BlueTokenRequirementsParams, } from "../entities/blue/index.js";
2
2
  export type { MidnightActions } from "../entities/midnight/index.js";
3
3
  export type { VaultV1Actions } from "../entities/vaultV1/index.js";
4
4
  export type { VaultV2Actions } from "../entities/vaultV2/index.js";
5
5
  export * from "./blue/index.js";
6
+ export * from "./bundles/index.js";
6
7
  export * from "./midnight/index.js";
7
8
  export * from "./requirements/index.js";
8
9
  export * from "./signatures/index.js";
@@ -15,6 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./blue/index.js"), exports);
18
+ __exportStar(require("./bundles/index.js"), exports);
18
19
  __exportStar(require("./midnight/index.js"), exports);
19
20
  __exportStar(require("./requirements/index.js"), exports);
20
21
  __exportStar(require("./signatures/index.js"), exports);
@@ -40,8 +40,8 @@ export interface MidnightSupplyCollateralTakeBorrowParams extends MidnightTakeBo
40
40
  * chainId: 8453,
41
41
  * market: marketData.params,
42
42
  * collateralAssets: 2_000_000n,
43
- * loanAssets: BigInt(quote.data.availableAssets),
44
- * maxUnits: BigInt(quote.data.availableUnits),
43
+ * loanAssets: 1_000_000n,
44
+ * maxUnits: 1_100_000n,
45
45
  * taker: borrower,
46
46
  * takeableOffers: quote.data.takeableOffers,
47
47
  * deadline: maxUint256,
@@ -44,8 +44,8 @@ const types_js_1 = require("./types.js");
44
44
  * chainId: 8453,
45
45
  * market: marketData.params,
46
46
  * collateralAssets: 2_000_000n,
47
- * loanAssets: BigInt(quote.data.availableAssets),
48
- * maxUnits: BigInt(quote.data.availableUnits),
47
+ * loanAssets: 1_000_000n,
48
+ * maxUnits: 1_100_000n,
49
49
  * taker: borrower,
50
50
  * takeableOffers: quote.data.takeableOffers,
51
51
  * deadline: maxUint256,
@@ -46,8 +46,8 @@ export interface MidnightTakeBorrowParams {
46
46
  * const tx = midnightTakeBorrow({
47
47
  * chainId: 8453,
48
48
  * market: marketData.params,
49
- * loanAssets: BigInt(quote.data.availableAssets),
50
- * maxUnits: BigInt(quote.data.availableUnits),
49
+ * loanAssets: 1_000_000n,
50
+ * maxUnits: 1_100_000n,
51
51
  * taker: borrower,
52
52
  * takeableOffers: quote.data.takeableOffers,
53
53
  * deadline: maxUint256,
@@ -40,8 +40,8 @@ const index_js_2 = require("../../types/index.js");
40
40
  * const tx = midnightTakeBorrow({
41
41
  * chainId: 8453,
42
42
  * market: marketData.params,
43
- * loanAssets: BigInt(quote.data.availableAssets),
44
- * maxUnits: BigInt(quote.data.availableUnits),
43
+ * loanAssets: 1_000_000n,
44
+ * maxUnits: 1_100_000n,
45
45
  * taker: borrower,
46
46
  * takeableOffers: quote.data.takeableOffers,
47
47
  * deadline: maxUint256,
@@ -46,8 +46,8 @@ export interface MidnightTakeLendParams {
46
46
  * const tx = midnightTakeLend({
47
47
  * chainId: 8453,
48
48
  * market: marketData.params,
49
- * assets: BigInt(quote.data.availableAssets),
50
- * minUnits: BigInt(quote.data.availableUnits),
49
+ * assets: 1_000_000n,
50
+ * minUnits: 900_000n,
51
51
  * taker: lender,
52
52
  * takeableOffers: quote.data.takeableOffers,
53
53
  * deadline: maxUint256,
@@ -41,8 +41,8 @@ const types_js_1 = require("./types.js");
41
41
  * const tx = midnightTakeLend({
42
42
  * chainId: 8453,
43
43
  * market: marketData.params,
44
- * assets: BigInt(quote.data.availableAssets),
45
- * minUnits: BigInt(quote.data.availableUnits),
44
+ * assets: 1_000_000n,
45
+ * minUnits: 900_000n,
46
46
  * taker: lender,
47
47
  * takeableOffers: quote.data.takeableOffers,
48
48
  * deadline: maxUint256,
@@ -2,48 +2,60 @@ import type { Client } from "viem";
2
2
  import { type Address } from "viem";
3
3
  import { type AuthorizationRequirementSignature, type BlueAuthorizationAction, type Requirement, type Transaction } from "../../../types/index.js";
4
4
  /**
5
- * Resolves whether `GeneralAdapter1` needs Blue authorization for the given user, and returns
5
+ * Resolves whether a supported operator needs Blue authorization for the given user, and returns
6
6
  * the requirement to satisfy it when it does.
7
7
  *
8
- * Reads `Morpho.isAuthorized(userAddress, generalAdapter1)` on the target chain. Required before
9
- * any bundled Blue path that operates on behalf of the user (`borrow`, `withdraw`,
10
- * `supplyCollateralBorrow`, `repayWithdrawCollateral`, `refinance`).
8
+ * Reads `Morpho.isAuthorized(userAddress, authorized)` on the target chain.
11
9
  *
12
10
  * - When `supportSignature` is falsy (default), returns the
13
- * `setAuthorization(generalAdapter1, true)` transaction the user submits before the bundle.
11
+ * `setAuthorization(authorized, true)` transaction the user submits before the operation.
14
12
  * - When `supportSignature` is `true`, reads the user's Morpho `nonce` and returns a signable
15
- * `Requirement`; the signed authorization is folded into the bundle via
16
- * `setAuthorizationWithSig`, removing the standalone transaction.
13
+ * `Requirement`. The selected route consumes the result: Bundler3 emits
14
+ * `setAuthorizationWithSig`, while BlueBundlesV1 embeds its signed-authorization struct.
17
15
  *
18
16
  * @param params.viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
19
- * @param params.chainId - Target chain id (used to resolve Morpho and `GeneralAdapter1`).
20
- * @param params.userAddress - The user that must authorize `GeneralAdapter1`.
17
+ * @param params.chainId - Target chain id used to resolve Morpho and the default GeneralAdapter1.
18
+ * @param params.userAddress - The user granting authorization.
19
+ * @param params.authorized - Operator to authorize. Defaults to GeneralAdapter1; direct Blue
20
+ * writes pass the registered BlueBundlesV1 deployment. Must be the chain's registered
21
+ * GeneralAdapter1 or BlueBundlesV1 operator.
22
+ * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
21
23
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
22
- * transaction so authorization can be bundled via `setAuthorizationWithSig`.
24
+ * transaction so the destination route can consume the signed authorization.
23
25
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
24
26
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
25
27
  * place.
26
28
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
29
+ * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
30
+ * GeneralAdapter1 nor its BlueBundlesV1 operator.
31
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
32
+ * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
27
33
  * @example
28
34
  * ```ts
29
- * import { createPublicClient, http } from "viem";
35
+ * import { createPublicClient, http, zeroAddress } from "viem";
30
36
  * import { mainnet } from "viem/chains";
31
37
  * import { getBlueAuthorizationRequirement } from "@morpho-org/morpho-sdk";
38
+ * import { getChainAddress } from "@morpho-org/morpho-ts";
32
39
  *
33
40
  * const client = createPublicClient({ chain: mainnet, transport: http() });
41
+ * const blueBundlesV1 = getChainAddress(mainnet.id, "bundles.blueBundlesV1");
34
42
  * const requirement = await getBlueAuthorizationRequirement({
35
43
  * viemClient: client,
36
- * chainId: 1,
37
- * userAddress: borrower,
44
+ * chainId: mainnet.id,
45
+ * userAddress: zeroAddress,
38
46
  * supportSignature: true,
47
+ * authorized: blueBundlesV1,
48
+ * deadline: 1_900_000_000n,
39
49
  * });
40
50
  * // requirement is null when already authorized, a Requirement when supportSignature is true,
41
51
  * // otherwise Readonly<Transaction<BlueAuthorizationAction>>
42
52
  * ```
43
53
  */
44
54
  export declare const getBlueAuthorizationRequirement: (params: {
45
- viemClient: Client;
46
- chainId: number;
47
- userAddress: Address;
48
- supportSignature?: boolean;
55
+ readonly viemClient: Client;
56
+ readonly chainId: number;
57
+ readonly userAddress: Address;
58
+ readonly supportSignature?: boolean;
59
+ readonly authorized?: Address;
60
+ readonly deadline?: bigint;
49
61
  }) => Promise<Readonly<Transaction<BlueAuthorizationAction>> | Requirement<AuthorizationRequirementSignature> | null>;
@@ -8,40 +8,50 @@ const viem_1 = require("viem");
8
8
  const index_js_1 = require("../../../types/index.js");
9
9
  const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSignatureAuthorization.js");
10
10
  /**
11
- * Resolves whether `GeneralAdapter1` needs Blue authorization for the given user, and returns
11
+ * Resolves whether a supported operator needs Blue authorization for the given user, and returns
12
12
  * the requirement to satisfy it when it does.
13
13
  *
14
- * Reads `Morpho.isAuthorized(userAddress, generalAdapter1)` on the target chain. Required before
15
- * any bundled Blue path that operates on behalf of the user (`borrow`, `withdraw`,
16
- * `supplyCollateralBorrow`, `repayWithdrawCollateral`, `refinance`).
14
+ * Reads `Morpho.isAuthorized(userAddress, authorized)` on the target chain.
17
15
  *
18
16
  * - When `supportSignature` is falsy (default), returns the
19
- * `setAuthorization(generalAdapter1, true)` transaction the user submits before the bundle.
17
+ * `setAuthorization(authorized, true)` transaction the user submits before the operation.
20
18
  * - When `supportSignature` is `true`, reads the user's Morpho `nonce` and returns a signable
21
- * `Requirement`; the signed authorization is folded into the bundle via
22
- * `setAuthorizationWithSig`, removing the standalone transaction.
19
+ * `Requirement`. The selected route consumes the result: Bundler3 emits
20
+ * `setAuthorizationWithSig`, while BlueBundlesV1 embeds its signed-authorization struct.
23
21
  *
24
22
  * @param params.viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
25
- * @param params.chainId - Target chain id (used to resolve Morpho and `GeneralAdapter1`).
26
- * @param params.userAddress - The user that must authorize `GeneralAdapter1`.
23
+ * @param params.chainId - Target chain id used to resolve Morpho and the default GeneralAdapter1.
24
+ * @param params.userAddress - The user granting authorization.
25
+ * @param params.authorized - Operator to authorize. Defaults to GeneralAdapter1; direct Blue
26
+ * writes pass the registered BlueBundlesV1 deployment. Must be the chain's registered
27
+ * GeneralAdapter1 or BlueBundlesV1 operator.
28
+ * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
27
29
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
28
- * transaction so authorization can be bundled via `setAuthorizationWithSig`.
30
+ * transaction so the destination route can consume the signed authorization.
29
31
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
30
32
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
31
33
  * place.
32
34
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
35
+ * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
36
+ * GeneralAdapter1 nor its BlueBundlesV1 operator.
37
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
38
+ * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
33
39
  * @example
34
40
  * ```ts
35
- * import { createPublicClient, http } from "viem";
41
+ * import { createPublicClient, http, zeroAddress } from "viem";
36
42
  * import { mainnet } from "viem/chains";
37
43
  * import { getBlueAuthorizationRequirement } from "@morpho-org/morpho-sdk";
44
+ * import { getChainAddress } from "@morpho-org/morpho-ts";
38
45
  *
39
46
  * const client = createPublicClient({ chain: mainnet, transport: http() });
47
+ * const blueBundlesV1 = getChainAddress(mainnet.id, "bundles.blueBundlesV1");
40
48
  * const requirement = await getBlueAuthorizationRequirement({
41
49
  * viemClient: client,
42
- * chainId: 1,
43
- * userAddress: borrower,
50
+ * chainId: mainnet.id,
51
+ * userAddress: zeroAddress,
44
52
  * supportSignature: true,
53
+ * authorized: blueBundlesV1,
54
+ * deadline: 1_900_000_000n,
45
55
  * });
46
56
  * // requirement is null when already authorized, a Requirement when supportSignature is true,
47
57
  * // otherwise Readonly<Transaction<BlueAuthorizationAction>>
@@ -52,9 +62,39 @@ const getBlueAuthorizationRequirement = async (params) => {
52
62
  if (viemClient.chain?.id !== chainId) {
53
63
  throw new index_js_1.ChainIdMismatchError(viemClient.chain?.id, chainId);
54
64
  }
55
- const { morpho, bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
65
+ const { morpho, bundler3: { generalAdapter1 }, bundles, } = (0, blue_sdk_1.getChainAddresses)(chainId);
66
+ const authorized = params.authorized ?? generalAdapter1;
67
+ // The SDK only ever authorizes the chain's registered GeneralAdapter1 or BlueBundlesV1 operator;
68
+ // reject any other override so a misconfigured `authorized` cannot grant an arbitrary address
69
+ // control over the user's Morpho positions.
70
+ const supportedOperators = [generalAdapter1];
71
+ if (bundles?.blueBundlesV1 != null) {
72
+ supportedOperators.push(bundles.blueBundlesV1);
73
+ }
74
+ if (!supportedOperators.some((operator) => (0, viem_1.isAddressEqual)(operator, authorized))) {
75
+ throw new index_js_1.UnsupportedAuthorizationOperatorError(authorized, chainId);
76
+ }
56
77
  const pc = viemClient.extend(viem_1.publicActions);
57
78
  if (supportSignature) {
79
+ // The forwarded deadline is only consumed on the signable path; reject an invalid or expired
80
+ // one before the RPC reads so the caller never signs an authorization that cannot be encoded
81
+ // or would revert on-chain. An omitted deadline defaults downstream to two hours from now.
82
+ if (params.deadline != null) {
83
+ if (params.deadline <= 0n) {
84
+ throw new index_js_1.NonPositiveInputError("deadline", params.deadline);
85
+ }
86
+ if (params.deadline > viem_1.maxUint256) {
87
+ throw new index_js_1.InputExceedsMaxError({
88
+ field: "deadline",
89
+ value: params.deadline,
90
+ max: viem_1.maxUint256,
91
+ });
92
+ }
93
+ const timestamp = morpho_ts_1.Time.timestamp();
94
+ if (params.deadline <= timestamp) {
95
+ throw new index_js_1.ExpiredDeadlineError(params.deadline, timestamp);
96
+ }
97
+ }
58
98
  // The signable path needs the user's Morpho nonce; fetch it alongside the
59
99
  // authorization status so both reads share a round-trip (batched into a
60
100
  // single multicall when the client enables batching) instead of
@@ -64,7 +104,7 @@ const getBlueAuthorizationRequirement = async (params) => {
64
104
  address: morpho,
65
105
  abi: blue_sdk_viem_1.blueAbi,
66
106
  functionName: "isAuthorized",
67
- args: [userAddress, generalAdapter1],
107
+ args: [userAddress, authorized],
68
108
  }),
69
109
  pc.readContract({
70
110
  address: morpho,
@@ -77,16 +117,17 @@ const getBlueAuthorizationRequirement = async (params) => {
77
117
  return null;
78
118
  }
79
119
  return (0, encodeBlueSignatureAuthorization_js_1.encodeBlueSignatureAuthorization)(viemClient, {
80
- authorized: generalAdapter1,
120
+ authorized,
81
121
  chainId,
82
122
  nonce,
123
+ deadline: params.deadline,
83
124
  });
84
125
  }
85
126
  const isAuthorized = await pc.readContract({
86
127
  address: morpho,
87
128
  abi: blue_sdk_viem_1.blueAbi,
88
129
  functionName: "isAuthorized",
89
- args: [userAddress, generalAdapter1],
130
+ args: [userAddress, authorized],
90
131
  });
91
132
  if (isAuthorized) {
92
133
  return null;
@@ -96,13 +137,13 @@ const getBlueAuthorizationRequirement = async (params) => {
96
137
  data: (0, viem_1.encodeFunctionData)({
97
138
  abi: blue_sdk_viem_1.blueAbi,
98
139
  functionName: "setAuthorization",
99
- args: [generalAdapter1, true],
140
+ args: [authorized, true],
100
141
  }),
101
142
  value: 0n,
102
143
  action: {
103
144
  type: "blueAuthorization",
104
145
  args: {
105
- authorized: generalAdapter1,
146
+ authorized,
106
147
  isAuthorized: true,
107
148
  },
108
149
  },
@@ -0,0 +1,48 @@
1
+ import { type Address, type Client } from "viem";
2
+ /** Parameters for {@link getUnusedPermit2Nonce}. */
3
+ export interface GetUnusedPermit2NonceParams {
4
+ /** Account that will sign the Permit2 SignatureTransfer. */
5
+ readonly owner: Address;
6
+ /** Target chain id; must match the connected client chain. */
7
+ readonly chainId: number;
8
+ /** Lowest nonce to consider; defaults to 0. */
9
+ readonly startNonce?: bigint;
10
+ }
11
+ /**
12
+ * Finds the lowest unused Permit2 unordered nonce for `owner`, ready to pass as `permit2Nonce` to
13
+ * {@link getBundlesTokenRequirements} or as `nonce` to {@link encodeErc20Permit2SignatureTransfer}.
14
+ *
15
+ * Permit2 SignatureTransfer consumes an unordered 256-bit nonce; a nonce is free when its bit in
16
+ * `nonceBitmap(owner, word)` is unset. This scans consecutive bitmap words starting at `startNonce`
17
+ * (one RPC read per 256 nonces) and returns the first free nonce, so integrators do not reimplement
18
+ * the scan. Concurrent flows for the same owner should advance `startNonce` (or read once, then
19
+ * partition locally) so two signatures never race on the same owner-global nonce.
20
+ *
21
+ * @param viemClient - Connected viem client used for the bitmap reads.
22
+ * @param params - Lookup parameters.
23
+ * @param params.owner - Account that will sign the SignatureTransfer.
24
+ * @param params.chainId - Target chain id; must match the client chain.
25
+ * @param params.startNonce - Lowest nonce to consider; defaults to 0.
26
+ * @returns The lowest unused Permit2 nonce at or after `startNonce`.
27
+ * @throws {ChainIdMismatchError} when the connected client targets another chain.
28
+ * @throws {NegativeInputError} when `startNonce` is negative.
29
+ * @throws {InputExceedsMaxError} when `startNonce` exceeds `uint256`.
30
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
31
+ * @throws {UnknownAddressError} when the chain has no registered canonical Permit2 deployment.
32
+ * @throws {viem.BaseError} when a Permit2 nonce-bitmap RPC read fails.
33
+ * @throws {NoUnusedPermit2NonceError} when every nonce at or after `startNonce` is consumed.
34
+ * @example
35
+ * ```ts
36
+ * import { createPublicClient, http, zeroAddress } from "viem";
37
+ * import { mainnet } from "viem/chains";
38
+ * import { getUnusedPermit2Nonce } from "@morpho-org/morpho-sdk";
39
+ *
40
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
41
+ * const permit2Nonce = await getUnusedPermit2Nonce(client, {
42
+ * owner: zeroAddress,
43
+ * chainId: mainnet.id,
44
+ * });
45
+ * // permit2Nonce satisfies bigint
46
+ * ```
47
+ */
48
+ export declare const getUnusedPermit2Nonce: (viemClient: Client, params: GetUnusedPermit2NonceParams) => Promise<bigint>;
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getUnusedPermit2Nonce = void 0;
4
+ const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const viem_1 = require("viem");
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");
11
+ /** Highest Permit2 nonce-bitmap word index; each word covers 256 unordered nonces. */
12
+ const MAX_PERMIT2_NONCE_WORD = viem_1.maxUint256 >> 8n;
13
+ /**
14
+ * Finds the lowest unused Permit2 unordered nonce for `owner`, ready to pass as `permit2Nonce` to
15
+ * {@link getBundlesTokenRequirements} or as `nonce` to {@link encodeErc20Permit2SignatureTransfer}.
16
+ *
17
+ * Permit2 SignatureTransfer consumes an unordered 256-bit nonce; a nonce is free when its bit in
18
+ * `nonceBitmap(owner, word)` is unset. This scans consecutive bitmap words starting at `startNonce`
19
+ * (one RPC read per 256 nonces) and returns the first free nonce, so integrators do not reimplement
20
+ * the scan. Concurrent flows for the same owner should advance `startNonce` (or read once, then
21
+ * partition locally) so two signatures never race on the same owner-global nonce.
22
+ *
23
+ * @param viemClient - Connected viem client used for the bitmap reads.
24
+ * @param params - Lookup parameters.
25
+ * @param params.owner - Account that will sign the SignatureTransfer.
26
+ * @param params.chainId - Target chain id; must match the client chain.
27
+ * @param params.startNonce - Lowest nonce to consider; defaults to 0.
28
+ * @returns The lowest unused Permit2 nonce at or after `startNonce`.
29
+ * @throws {ChainIdMismatchError} when the connected client targets another chain.
30
+ * @throws {NegativeInputError} when `startNonce` is negative.
31
+ * @throws {InputExceedsMaxError} when `startNonce` exceeds `uint256`.
32
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
33
+ * @throws {UnknownAddressError} when the chain has no registered canonical Permit2 deployment.
34
+ * @throws {viem.BaseError} when a Permit2 nonce-bitmap RPC read fails.
35
+ * @throws {NoUnusedPermit2NonceError} when every nonce at or after `startNonce` is consumed.
36
+ * @example
37
+ * ```ts
38
+ * import { createPublicClient, http, zeroAddress } from "viem";
39
+ * import { mainnet } from "viem/chains";
40
+ * import { getUnusedPermit2Nonce } from "@morpho-org/morpho-sdk";
41
+ *
42
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
43
+ * const permit2Nonce = await getUnusedPermit2Nonce(client, {
44
+ * owner: zeroAddress,
45
+ * chainId: mainnet.id,
46
+ * });
47
+ * // permit2Nonce satisfies bigint
48
+ * ```
49
+ */
50
+ const getUnusedPermit2Nonce = async (viemClient, params) => {
51
+ (0, index_js_1.validateChainId)(viemClient.chain?.id, params.chainId);
52
+ const startNonce = params.startNonce ?? 0n;
53
+ (0, validate_js_1.validateUint256Field)("startNonce", startNonce);
54
+ const permit2 = (0, morpho_ts_1.getChainAddress)(params.chainId, "permit2");
55
+ const startWord = startNonce >> 8n;
56
+ for (let word = startWord; word <= MAX_PERMIT2_NONCE_WORD; word++) {
57
+ const bitmap = await (0, actions_1.readContract)(viemClient, {
58
+ abi: blue_sdk_viem_1.permit2Abi,
59
+ address: permit2,
60
+ functionName: "nonceBitmap",
61
+ args: [params.owner, word],
62
+ });
63
+ const firstBit = word === startWord ? startNonce & 255n : 0n;
64
+ for (let bit = firstBit; bit <= 255n; bit++) {
65
+ if ((bitmap & (1n << bit)) === 0n) {
66
+ return (word << 8n) | bit;
67
+ }
68
+ }
69
+ }
70
+ throw new index_js_2.NoUnusedPermit2NonceError(params.owner, startNonce);
71
+ };
72
+ exports.getUnusedPermit2Nonce = getUnusedPermit2Nonce;
@@ -1 +1,2 @@
1
1
  export * from "./getBlueAuthorizationRequirement.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("./getBlueAuthorizationRequirement.js"), exports);
18
+ __exportStar(require("./getUnusedPermit2Nonce.js"), exports);
@@ -1,9 +1,9 @@
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 to authorize on Morpho (GeneralAdapter1). */
6
+ /** Operator to authorize on Morpho, such as GeneralAdapter1 or BlueBundlesV1. */
7
7
  authorized: Address;
8
8
  /** Target chain id; must match `viemClient.chain.id`. */
9
9
  chainId: number;
@@ -16,23 +16,26 @@ interface EncodeBlueSignatureAuthorizationParams {
16
16
  }
17
17
  /**
18
18
  * Builds a Morpho authorization `Requirement` that, once signed, lets `authorized` operate on
19
- * Morpho on the signer's behalf through `setAuthorizationWithSig` — the offchain-signature
20
- * alternative to a standalone `setAuthorization` transaction.
19
+ * Morpho on the signer's behalf. Bundler3 consumes the result through `setAuthorizationWithSig`;
20
+ * BlueBundlesV1 embeds the same signed authorization in its direct-call struct.
21
21
  *
22
22
  * The returned `Requirement.sign()` produces the EIP-712 signature over Morpho's `Authorization`
23
23
  * typed data, verifies it against the connected account, and returns a deep-frozen
24
- * `RequirementSignature` the bundler action helpers consume. Deadline defaults to two hours from
25
- * `Time.timestamp()`.
24
+ * `RequirementSignature` the selected transaction route consumes. Deadline defaults to two hours
25
+ * from `Time.timestamp()`.
26
26
  *
27
27
  * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
28
28
  * @param params - Authorization encoding parameters.
29
- * @param params.authorized - Account to authorize (GeneralAdapter1).
29
+ * @param params.authorized - Operator to authorize, such as GeneralAdapter1 or BlueBundlesV1.
30
30
  * @param params.chainId - Target chain id.
31
31
  * @param params.nonce - The signer's current Morpho authorization nonce.
32
32
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
33
33
  * @param params.deadline - Optional signature deadline in seconds.
34
34
  * @returns A `Requirement` whose `sign(client, userAddress)` produces the deep-frozen signature.
35
35
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
36
+ * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
37
+ * @throws {InputExceedsMaxError} when a provided `deadline` exceeds `uint256`.
38
+ * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
36
39
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
37
40
  * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
38
41
  * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.