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

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 (277) hide show
  1. package/MIGRATION-v5-to-v6.md +88 -32
  2. package/README.md +9 -7
  3. package/lib/cjs/abis.d.ts +7 -2844
  4. package/lib/cjs/abis.js +3 -1951
  5. package/lib/cjs/actions/blue/borrow.d.ts +3 -2
  6. package/lib/cjs/actions/blue/borrow.js +3 -2
  7. package/lib/cjs/actions/blue/common.js +1 -9
  8. package/lib/cjs/actions/blue/refinance.d.ts +2 -2
  9. package/lib/cjs/actions/blue/refinance.js +2 -2
  10. package/lib/cjs/actions/blue/repay.d.ts +1 -1
  11. package/lib/cjs/actions/blue/repay.js +1 -1
  12. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  14. package/lib/cjs/actions/blue/supply.d.ts +2 -2
  15. package/lib/cjs/actions/blue/supply.js +2 -2
  16. package/lib/cjs/actions/blue/supplyCollateral.d.ts +2 -2
  17. package/lib/cjs/actions/blue/supplyCollateral.js +2 -2
  18. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +3 -2
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +3 -2
  20. package/lib/cjs/actions/blue/withdraw.d.ts +3 -3
  21. package/lib/cjs/actions/blue/withdraw.js +3 -3
  22. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +2 -2
  23. package/lib/cjs/actions/blue/withdrawCollateral.js +2 -2
  24. package/lib/cjs/actions/bundles/common.d.ts +6 -2
  25. package/lib/cjs/actions/bundles/common.js +31 -5
  26. package/lib/cjs/actions/index.d.ts +0 -1
  27. package/lib/cjs/actions/index.js +0 -1
  28. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -8
  29. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -16
  30. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +5 -6
  31. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +4 -5
  32. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +4 -4
  33. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +4 -5
  34. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +5 -5
  35. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +6 -11
  36. package/lib/cjs/actions/requirements/encode/index.d.ts +0 -1
  37. package/lib/cjs/actions/requirements/encode/index.js +0 -1
  38. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -6
  39. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -6
  40. package/lib/cjs/actions/requirements/index.d.ts +0 -1
  41. package/lib/cjs/actions/requirements/index.js +0 -1
  42. package/lib/cjs/actions/vaultV1/deposit.d.ts +1 -2
  43. package/lib/cjs/actions/vaultV1/deposit.js +1 -2
  44. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +7 -5
  45. package/lib/cjs/actions/vaultV1/inKindRedeem.js +11 -7
  46. package/lib/cjs/actions/vaultV2/deposit.d.ts +1 -2
  47. package/lib/cjs/actions/vaultV2/deposit.js +1 -2
  48. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  49. package/lib/cjs/actions/vaultV2/forceWithdraw.js +3 -3
  50. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +7 -5
  51. package/lib/cjs/actions/vaultV2/inKindRedeem.js +11 -7
  52. package/lib/cjs/augment/AccrualPosition.d.ts +1 -0
  53. package/lib/cjs/augment.d.ts +0 -1
  54. package/lib/cjs/augment.js +0 -1
  55. package/lib/cjs/blue/abis.d.ts +5 -5
  56. package/lib/cjs/blue/abis.js +3 -7
  57. package/lib/cjs/blue/entities.d.ts +10 -8
  58. package/lib/cjs/blue/entities.js +3 -3
  59. package/lib/cjs/blue/errors.d.ts +4 -2
  60. package/lib/cjs/blue/errors.js +3 -1
  61. package/lib/cjs/blue/fetch.d.ts +5 -3
  62. package/lib/cjs/blue/fetch.js +3 -3
  63. package/lib/cjs/blue/types.d.ts +2 -4
  64. package/lib/cjs/blue/utils.d.ts +6 -4
  65. package/lib/cjs/blue/utils.js +3 -3
  66. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  67. package/lib/cjs/client/morphoViemExtension.js +1 -1
  68. package/lib/cjs/constants.d.ts +3 -37
  69. package/lib/cjs/constants.js +1 -39
  70. package/lib/cjs/entities/blue/blue.d.ts +30 -265
  71. package/lib/cjs/entities/blue/blue.js +1 -205
  72. package/lib/cjs/entities/index.d.ts +11 -66
  73. package/lib/cjs/entities/index.js +3 -21
  74. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -2
  75. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -3
  76. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +13 -5
  77. package/lib/cjs/entities/vaultV1/vaultV1.js +16 -10
  78. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +40 -19
  79. package/lib/cjs/entities/vaultV2/vaultV2.js +57 -26
  80. package/lib/cjs/entities/vaultV2BlueReallocationData.js +4 -21
  81. package/lib/cjs/errors.d.ts +5 -47
  82. package/lib/cjs/errors.js +4 -46
  83. package/lib/cjs/fetch.d.ts +5 -17
  84. package/lib/cjs/fetch.js +3 -17
  85. package/lib/cjs/helpers/constant.d.ts +0 -2
  86. package/lib/cjs/helpers/constant.js +0 -2
  87. package/lib/cjs/helpers/index.d.ts +2 -3
  88. package/lib/cjs/helpers/index.js +1 -9
  89. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +11 -5
  90. package/lib/cjs/helpers/slippage.d.ts +1 -103
  91. package/lib/cjs/helpers/slippage.js +0 -150
  92. package/lib/cjs/helpers/utilization.d.ts +12 -10
  93. package/lib/cjs/helpers/utilization.js +27 -12
  94. package/lib/cjs/helpers/validate.d.ts +1 -24
  95. package/lib/cjs/helpers/validate.js +2 -49
  96. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  97. package/lib/cjs/helpers/validateRequirementSpender.js +1 -3
  98. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.d.ts +48 -15
  99. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +48 -15
  100. package/lib/cjs/midnight/errors.d.ts +1 -1
  101. package/lib/cjs/midnight/errors.js +2 -1
  102. package/lib/cjs/types/action.d.ts +17 -65
  103. package/lib/cjs/types/action.js +11 -4
  104. package/lib/cjs/types/error.d.ts +50 -381
  105. package/lib/cjs/types/error.js +64 -395
  106. package/lib/cjs/types/sharedLiquidity.d.ts +1 -117
  107. package/lib/cjs/types.d.ts +2 -18
  108. package/lib/cjs/utils.d.ts +10 -35
  109. package/lib/cjs/utils.js +4 -36
  110. package/lib/esm/abis.d.ts +7 -2844
  111. package/lib/esm/abis.js +7 -1950
  112. package/lib/esm/actions/blue/borrow.d.ts +3 -2
  113. package/lib/esm/actions/blue/borrow.js +3 -2
  114. package/lib/esm/actions/blue/common.js +1 -9
  115. package/lib/esm/actions/blue/refinance.d.ts +2 -2
  116. package/lib/esm/actions/blue/refinance.js +2 -2
  117. package/lib/esm/actions/blue/repay.d.ts +1 -1
  118. package/lib/esm/actions/blue/repay.js +1 -1
  119. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  120. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  121. package/lib/esm/actions/blue/supply.d.ts +2 -2
  122. package/lib/esm/actions/blue/supply.js +2 -2
  123. package/lib/esm/actions/blue/supplyCollateral.d.ts +2 -2
  124. package/lib/esm/actions/blue/supplyCollateral.js +2 -2
  125. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +3 -2
  126. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -2
  127. package/lib/esm/actions/blue/withdraw.d.ts +3 -3
  128. package/lib/esm/actions/blue/withdraw.js +3 -3
  129. package/lib/esm/actions/blue/withdrawCollateral.d.ts +2 -2
  130. package/lib/esm/actions/blue/withdrawCollateral.js +2 -2
  131. package/lib/esm/actions/bundles/common.d.ts +6 -2
  132. package/lib/esm/actions/bundles/common.js +32 -6
  133. package/lib/esm/actions/index.d.ts +0 -1
  134. package/lib/esm/actions/index.js +0 -1
  135. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -8
  136. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +12 -17
  137. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +5 -6
  138. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +4 -5
  139. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +4 -4
  140. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +4 -5
  141. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +5 -5
  142. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +6 -11
  143. package/lib/esm/actions/requirements/encode/index.d.ts +0 -1
  144. package/lib/esm/actions/requirements/encode/index.js +0 -1
  145. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -6
  146. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -6
  147. package/lib/esm/actions/requirements/index.d.ts +0 -1
  148. package/lib/esm/actions/requirements/index.js +0 -1
  149. package/lib/esm/actions/vaultV1/deposit.d.ts +1 -2
  150. package/lib/esm/actions/vaultV1/deposit.js +1 -2
  151. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +7 -5
  152. package/lib/esm/actions/vaultV1/inKindRedeem.js +11 -7
  153. package/lib/esm/actions/vaultV2/deposit.d.ts +1 -2
  154. package/lib/esm/actions/vaultV2/deposit.js +1 -2
  155. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  156. package/lib/esm/actions/vaultV2/forceWithdraw.js +3 -3
  157. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +7 -5
  158. package/lib/esm/actions/vaultV2/inKindRedeem.js +11 -7
  159. package/lib/esm/augment/AccrualPosition.d.ts +1 -0
  160. package/lib/esm/augment.d.ts +0 -1
  161. package/lib/esm/augment.js +0 -1
  162. package/lib/esm/blue/abis.d.ts +5 -5
  163. package/lib/esm/blue/abis.js +5 -5
  164. package/lib/esm/blue/entities.d.ts +10 -8
  165. package/lib/esm/blue/entities.js +5 -3
  166. package/lib/esm/blue/errors.d.ts +4 -2
  167. package/lib/esm/blue/errors.js +4 -2
  168. package/lib/esm/blue/fetch.d.ts +5 -3
  169. package/lib/esm/blue/fetch.js +5 -3
  170. package/lib/esm/blue/types.d.ts +2 -4
  171. package/lib/esm/blue/utils.d.ts +6 -4
  172. package/lib/esm/blue/utils.js +6 -4
  173. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  174. package/lib/esm/client/morphoViemExtension.js +1 -1
  175. package/lib/esm/constants.d.ts +3 -37
  176. package/lib/esm/constants.js +3 -37
  177. package/lib/esm/entities/blue/blue.d.ts +30 -265
  178. package/lib/esm/entities/blue/blue.js +4 -208
  179. package/lib/esm/entities/index.d.ts +11 -66
  180. package/lib/esm/entities/index.js +5 -18
  181. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -2
  182. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -3
  183. package/lib/esm/entities/vaultV1/vaultV1.d.ts +13 -5
  184. package/lib/esm/entities/vaultV1/vaultV1.js +19 -13
  185. package/lib/esm/entities/vaultV2/vaultV2.d.ts +40 -19
  186. package/lib/esm/entities/vaultV2/vaultV2.js +61 -30
  187. package/lib/esm/entities/vaultV2BlueReallocationData.js +2 -19
  188. package/lib/esm/errors.d.ts +5 -47
  189. package/lib/esm/errors.js +5 -47
  190. package/lib/esm/fetch.d.ts +5 -17
  191. package/lib/esm/fetch.js +5 -17
  192. package/lib/esm/helpers/constant.d.ts +0 -2
  193. package/lib/esm/helpers/constant.js +0 -2
  194. package/lib/esm/helpers/index.d.ts +2 -3
  195. package/lib/esm/helpers/index.js +2 -3
  196. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +11 -5
  197. package/lib/esm/helpers/slippage.d.ts +1 -103
  198. package/lib/esm/helpers/slippage.js +1 -147
  199. package/lib/esm/helpers/utilization.d.ts +12 -10
  200. package/lib/esm/helpers/utilization.js +26 -11
  201. package/lib/esm/helpers/validate.d.ts +1 -24
  202. package/lib/esm/helpers/validate.js +2 -48
  203. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  204. package/lib/esm/helpers/validateRequirementSpender.js +1 -3
  205. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.d.ts +48 -15
  206. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +48 -15
  207. package/lib/esm/midnight/errors.d.ts +1 -1
  208. package/lib/esm/midnight/errors.js +1 -1
  209. package/lib/esm/types/action.d.ts +17 -65
  210. package/lib/esm/types/action.js +12 -5
  211. package/lib/esm/types/error.d.ts +50 -381
  212. package/lib/esm/types/error.js +58 -377
  213. package/lib/esm/types/sharedLiquidity.d.ts +1 -117
  214. package/lib/esm/types.d.ts +2 -18
  215. package/lib/esm/utils.d.ts +10 -35
  216. package/lib/esm/utils.js +9 -34
  217. package/package.json +6 -17
  218. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +0 -44
  219. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.js +0 -88
  220. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.d.ts +0 -88
  221. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +0 -152
  222. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +0 -40
  223. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +0 -53
  224. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +0 -57
  225. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +0 -74
  226. package/lib/cjs/actions/requirements/generalAdapter/index.d.ts +0 -3
  227. package/lib/cjs/actions/requirements/generalAdapter/index.js +0 -19
  228. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.d.ts +0 -29
  229. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.js +0 -48
  230. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +0 -58
  231. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +0 -119
  232. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +0 -50
  233. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +0 -45
  234. package/lib/cjs/actions/signatures/index.d.ts +0 -3
  235. package/lib/cjs/actions/signatures/index.js +0 -19
  236. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +0 -11
  237. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +0 -8
  238. package/lib/cjs/bundler/actions.d.ts +0 -797
  239. package/lib/cjs/bundler/actions.js +0 -1371
  240. package/lib/cjs/bundler/index.d.ts +0 -2
  241. package/lib/cjs/bundler/index.js +0 -18
  242. package/lib/cjs/bundler/types.d.ts +0 -235
  243. package/lib/cjs/bundler/types.js +0 -2
  244. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +0 -332
  245. package/lib/cjs/entities/vaultV1ReallocationData.js +0 -557
  246. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +0 -80
  247. package/lib/cjs/helpers/computeVaultV1Reallocations.js +0 -245
  248. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +0 -44
  249. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.js +0 -84
  250. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.d.ts +0 -88
  251. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +0 -148
  252. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +0 -40
  253. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +0 -49
  254. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +0 -57
  255. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +0 -70
  256. package/lib/esm/actions/requirements/generalAdapter/index.d.ts +0 -3
  257. package/lib/esm/actions/requirements/generalAdapter/index.js +0 -3
  258. package/lib/esm/actions/signatures/getBlueAuthorizationAction.d.ts +0 -29
  259. package/lib/esm/actions/signatures/getBlueAuthorizationAction.js +0 -44
  260. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +0 -58
  261. package/lib/esm/actions/signatures/getTokenRequirementActions.js +0 -115
  262. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +0 -50
  263. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +0 -41
  264. package/lib/esm/actions/signatures/index.d.ts +0 -3
  265. package/lib/esm/actions/signatures/index.js +0 -3
  266. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +0 -11
  267. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +0 -7
  268. package/lib/esm/bundler/actions.d.ts +0 -797
  269. package/lib/esm/bundler/actions.js +0 -1368
  270. package/lib/esm/bundler/index.d.ts +0 -2
  271. package/lib/esm/bundler/index.js +0 -2
  272. package/lib/esm/bundler/types.d.ts +0 -235
  273. package/lib/esm/bundler/types.js +0 -1
  274. package/lib/esm/entities/vaultV1ReallocationData.d.ts +0 -332
  275. package/lib/esm/entities/vaultV1ReallocationData.js +0 -559
  276. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +0 -80
  277. package/lib/esm/helpers/computeVaultV1Reallocations.js +0 -241
@@ -1,245 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.computeReallocations = exports.computeVaultV1Reallocations = void 0;
4
- const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
- const index_js_1 = require("../types/index.js");
6
- const utilization_js_1 = require("./utilization.js");
7
- const validate_js_1 = require("./validate.js");
8
- const groupWithdrawalsByVault = (withdrawals) => {
9
- const groups = [];
10
- const groupsByVault = new Map();
11
- for (const [index, { vault, id, assets }] of withdrawals.entries()) {
12
- if (assets <= 0n)
13
- continue;
14
- let group = groupsByVault.get(vault);
15
- if (group == null) {
16
- group = {
17
- vault,
18
- firstIndex: index,
19
- totalAssets: 0n,
20
- withdrawals: [],
21
- };
22
- groupsByVault.set(vault, group);
23
- groups.push(group);
24
- }
25
- group.totalAssets += assets;
26
- group.withdrawals.push({ id, assets });
27
- }
28
- return groups.sort((a, b) => {
29
- if (a.totalAssets > b.totalAssets)
30
- return -1;
31
- if (a.totalAssets < b.totalAssets)
32
- return 1;
33
- return a.firstIndex - b.firstIndex;
34
- });
35
- };
36
- const capVaultWithdrawals = (withdrawals, assets) => {
37
- const cappedWithdrawals = [];
38
- let remainingAssets = assets;
39
- for (const withdrawal of withdrawals) {
40
- const cappedAssets = blue_sdk_1.MathLib.min(withdrawal.assets, remainingAssets);
41
- /* v8 ignore next: grouped withdrawals and positive reallocation cap keep this defensive guard unreachable. */
42
- if (cappedAssets <= 0n)
43
- continue;
44
- const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
45
- if (existing != null) {
46
- existing.assets += cappedAssets;
47
- }
48
- else {
49
- cappedWithdrawals.push({
50
- id: withdrawal.id,
51
- assets: cappedAssets,
52
- });
53
- }
54
- remainingAssets -= cappedAssets;
55
- if (remainingAssets === 0n)
56
- break;
57
- }
58
- return cappedWithdrawals;
59
- };
60
- /**
61
- * Computes vault reallocations for a `borrow` or `withdraw` on a target market.
62
- *
63
- * First attempts "friendly" reallocations respecting withdrawal utilization
64
- * targets, then falls back to aggressive reallocations (100% withdrawal
65
- * utilization) if liquidity is still insufficient.
66
- *
67
- * Algebra branches on `operation`:
68
- * - `"borrow"`: `S' = S`, `B' = B + amount` (additional borrow demand).
69
- * - `"withdraw"`: `S' = S − amount`, `B' = B` (supply-side shrinkage).
70
- *
71
- * In both cases reallocated assets are added on the supply side; `requiredAssets`
72
- * and `absoluteShortfall` are derived from the operation-specific post-state.
73
- *
74
- * @remarks Pass `options.timestamp` from the same block used to fetch `reallocationData`; when omitted, market accrual falls back to the target market's `lastUpdate`, which can diverge from the source rows' fetch block. Per-market `maxWithdrawalUtilization` overrides apply only to phase 1; phase 2 forces 100% utilization on every source market.
75
- * @param params.reallocationData - The local state containing market, vault, and position data.
76
- * @param params.marketId - The target market to reallocate liquidity into.
77
- * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`).
78
- * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
79
- * @param params.options - Optional reallocation computation options.
80
- * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
81
- * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
82
- * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market — preventing fee-bearing reallocations from being attached to a call that would still revert onchain.
83
- * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets` — the on-chain call would revert regardless of reallocations.
84
- * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
85
- * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
86
- * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
87
- * @example
88
- * ```ts
89
- * import { createPublicClient, http, parseUnits } from "viem";
90
- * import { mainnet } from "viem/chains";
91
- * import { markets, vaults } from "@morpho-org/morpho-test";
92
- * import {
93
- * computeVaultV1Reallocations,
94
- * morphoViemExtension,
95
- * } from "@morpho-org/morpho-sdk";
96
- *
97
- * const client = createPublicClient({
98
- * chain: mainnet,
99
- * transport: http(),
100
- * }).extend(morphoViemExtension());
101
- *
102
- * const marketParams = markets[mainnet.id].usdc_wbtc;
103
- * const market = client.morpho.blue(marketParams, mainnet.id);
104
- * const block = await client.getBlock();
105
- * const reallocationData = await market.getVaultV1ReallocationData({
106
- * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
107
- * block: { number: block.number, timestamp: block.timestamp },
108
- * });
109
- * const borrowAmount = parseUnits("1000", 6);
110
- * const reallocations = computeVaultV1Reallocations({
111
- * reallocationData,
112
- * marketId: marketParams.id,
113
- * operation: "borrow",
114
- * amount: borrowAmount,
115
- * options: { timestamp: block.timestamp },
116
- * });
117
- * // Encode `reallocations` explicitly with
118
- * // BundlerAction.publicAllocatorReallocateTo(...) when composing a low-level bundle.
119
- * // High-level Blue writes accept Vault V2 reallocations only.
120
- * ```
121
- */
122
- const computeVaultV1Reallocations = ({ reallocationData: data, marketId, operation, amount, options, }) => {
123
- if (options?.enabled === false)
124
- return [];
125
- const normalizedOptions = {
126
- ...options,
127
- reallocatableVaults: options?.reallocatableVaults == null
128
- ? undefined
129
- : [...options.reallocatableVaults],
130
- };
131
- // VaultV1ReallocationData does not retain the fetch block; pass that block timestamp
132
- // to compute against the same accrued state, otherwise Market defaults to lastUpdate.
133
- const market = data
134
- .getMarket(marketId)
135
- .accrueInterest(normalizedOptions.timestamp);
136
- // Reject unreachable withdraws before any utilization math: a negative
137
- // post-supply yields a negative utilization that short-circuits the
138
- // utilization gate below and silently returns `[]` — masking a sure revert.
139
- if (operation === "withdraw" && amount > market.totalSupplyAssets) {
140
- throw new index_js_1.ReallocationWithdrawExceedsMarketSupplyError({
141
- marketId,
142
- withdrawAmount: amount,
143
- totalSupplyAssets: market.totalSupplyAssets,
144
- });
145
- }
146
- // Post-state utilization is operation-dependent.
147
- const newTotalBorrowAssets = operation === "borrow"
148
- ? market.totalBorrowAssets + amount
149
- : market.totalBorrowAssets;
150
- const newTotalSupplyAssets = operation === "withdraw"
151
- ? market.totalSupplyAssets - amount
152
- : market.totalSupplyAssets;
153
- const supplyTargetUtilization = (0, utilization_js_1.getSupplyTargetUtilization)(market.params.id, normalizedOptions);
154
- if (blue_sdk_1.MarketUtils.getUtilization({
155
- totalSupplyAssets: newTotalSupplyAssets,
156
- totalBorrowAssets: newTotalBorrowAssets,
157
- }) <= supplyTargetUtilization)
158
- return [];
159
- // Solve: newTotalBorrowAssets / (newTotalSupplyAssets + reallocatedAssets) = supplyTargetUtilization
160
- let requiredAssets = supplyTargetUtilization === 0n
161
- ? blue_sdk_1.MathLib.MAX_UINT_160
162
- : blue_sdk_1.MathLib.wDivDown(newTotalBorrowAssets, supplyTargetUtilization) -
163
- newTotalSupplyAssets;
164
- // Phase 1: "friendly" reallocations respecting withdrawal utilization targets.
165
- const { withdrawals: friendlyWithdrawals, data: friendlyReallocationData } = data.computeVaultV1Reallocations(market.id, normalizedOptions);
166
- const withdrawals = [...friendlyWithdrawals];
167
- const friendlyReallocationMarket = friendlyReallocationData.getMarket(market.id);
168
- // Operation-specific post-friendly check: would the on-chain call still revert?
169
- const friendlyBorrow = operation === "borrow"
170
- ? friendlyReallocationMarket.totalBorrowAssets + amount
171
- : friendlyReallocationMarket.totalBorrowAssets;
172
- const friendlySupply = operation === "withdraw"
173
- ? friendlyReallocationMarket.totalSupplyAssets - amount
174
- : friendlyReallocationMarket.totalSupplyAssets;
175
- if (friendlyBorrow > friendlySupply) {
176
- // Phase 2: "aggressive" — fully withdraw from every market (100% utilization).
177
- requiredAssets = newTotalBorrowAssets - newTotalSupplyAssets;
178
- withdrawals.push(...friendlyReallocationData.computeVaultV1Reallocations(market.id, {
179
- ...normalizedOptions,
180
- defaultMaxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
181
- maxWithdrawalUtilization: {},
182
- }).withdrawals);
183
- }
184
- if (requiredAssets <= 0n)
185
- return [];
186
- // Liquidity strictly required for the on-chain call to succeed.
187
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
188
- ? newTotalBorrowAssets - newTotalSupplyAssets
189
- : 0n;
190
- const reallocations = [];
191
- let totalReallocated = 0n;
192
- let remainingRequiredAssets = requiredAssets;
193
- for (const group of groupWithdrawalsByVault(withdrawals)) {
194
- const reallocatedAssets = blue_sdk_1.MathLib.min(group.totalAssets, remainingRequiredAssets);
195
- /* v8 ignore next: groups with non-positive assets are filtered before this point. */
196
- if (reallocatedAssets <= 0n)
197
- continue;
198
- reallocations.push({
199
- vault: group.vault,
200
- withdrawals: capVaultWithdrawals(group.withdrawals, reallocatedAssets),
201
- });
202
- remainingRequiredAssets -= reallocatedAssets;
203
- totalReallocated += reallocatedAssets;
204
- if (remainingRequiredAssets === 0n)
205
- break;
206
- }
207
- // Refuse fee-bearing partial plans for an unreachable operation.
208
- if (totalReallocated < absoluteShortfall) {
209
- throw new index_js_1.InsufficientSharedLiquidityError({
210
- marketId,
211
- shortfall: absoluteShortfall,
212
- available: totalReallocated,
213
- });
214
- }
215
- // Transform into VaultV1Reallocation[] format.
216
- return reallocations
217
- .filter(({ withdrawals: vaultWithdrawals }) => vaultWithdrawals.length > 0)
218
- .map(({ vault, withdrawals: vaultWithdrawals }) => ({
219
- vault,
220
- fee: (() => {
221
- const config = data.getVault(vault).publicAllocatorConfig;
222
- if (config == null) {
223
- throw new index_js_1.MissingPublicAllocatorConfigError(vault);
224
- }
225
- return config.fee;
226
- })(),
227
- withdrawals: vaultWithdrawals
228
- // Reallocation withdrawals must be sorted by market id in ascending
229
- // order. Normalize first because `MarketId` can be mixed-case hex.
230
- .sort(({ id: idA }, { id: idB }) => (0, validate_js_1.compareMarketIds)(idA, idB))
231
- .map(({ id, assets }) => ({
232
- marketParams: data.getMarket(id).params,
233
- amount: assets,
234
- })),
235
- }));
236
- };
237
- exports.computeVaultV1Reallocations = computeVaultV1Reallocations;
238
- /**
239
- * Deprecated name for the Vault V1 amount-aware reallocation planner.
240
- *
241
- * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
242
- * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
243
- * `VaultV2BlueReallocationData.computeVaultV2BlueReallocations`.
244
- */
245
- exports.computeReallocations = exports.computeVaultV1Reallocations;
@@ -1,44 +0,0 @@
1
- import { type Address } from "@morpho-org/blue-sdk";
2
- import type { PermitRequirementSignature, Requirement } from "../../../types/index.js";
3
- /** Parameters for {@link encodeErc20Permit2Approve}. */
4
- interface EncodeErc20Permit2ApproveParams {
5
- token: Address;
6
- amount: bigint;
7
- chainId: number;
8
- nonce: bigint;
9
- expiration?: bigint;
10
- }
11
- /**
12
- * Builds a Permit2 `Requirement` that, once signed, lets GeneralAdapter1 pull `amount` of `token`
13
- * via the Permit2 contract.
14
- *
15
- * The requirement's `action.typedData` holds the EIP-712 payload so it can be inspected or
16
- * displayed before signing. Deadline defaults to two hours from `Time.timestamp()`.
17
- *
18
- * @param params - Permit2 encoding parameters.
19
- * @param params.token - ERC-20 token address.
20
- * @param params.amount - Permit2 allowance amount (per-call).
21
- * @param params.chainId - Target chain id.
22
- * @param params.nonce - The user's current Permit2 nonce for `(token, GeneralAdapter1)`.
23
- * @param params.expiration - Permit2-managed allowance expiration timestamp.
24
- * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
25
- * `sign(client, userAddress)` produces the deep-frozen signature.
26
- * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
27
- * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
28
- * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
29
- * @example
30
- * ```ts
31
- * import { encodeErc20Permit2Approve } from "@morpho-org/morpho-sdk";
32
- *
33
- * const requirement = encodeErc20Permit2Approve({
34
- * token: USDC,
35
- * amount: 1_000_000n,
36
- * chainId: 1,
37
- * nonce: 0n,
38
- * expiration: 281_474_976_710_655n, // MAX_UINT_48 (2^48 - 1, effectively indefinite)
39
- * });
40
- * // requirement satisfies Requirement
41
- * ```
42
- */
43
- export declare const encodeErc20Permit2Approve: (params: EncodeErc20Permit2ApproveParams) => Requirement<PermitRequirementSignature>;
44
- export {};
@@ -1,84 +0,0 @@
1
- import { getChainAddresses, MathLib } from "@morpho-org/blue-sdk";
2
- import { getPermit2PermitTypedData } from "@morpho-org/blue-sdk-viem";
3
- import { deepFreeze, Time } from "@morpho-org/morpho-ts";
4
- import { signAndVerifyTypedData } from "../../../helpers/signAndVerifyTypedData.js";
5
- /**
6
- * Builds a Permit2 `Requirement` that, once signed, lets GeneralAdapter1 pull `amount` of `token`
7
- * via the Permit2 contract.
8
- *
9
- * The requirement's `action.typedData` holds the EIP-712 payload so it can be inspected or
10
- * displayed before signing. Deadline defaults to two hours from `Time.timestamp()`.
11
- *
12
- * @param params - Permit2 encoding parameters.
13
- * @param params.token - ERC-20 token address.
14
- * @param params.amount - Permit2 allowance amount (per-call).
15
- * @param params.chainId - Target chain id.
16
- * @param params.nonce - The user's current Permit2 nonce for `(token, GeneralAdapter1)`.
17
- * @param params.expiration - Permit2-managed allowance expiration timestamp.
18
- * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
19
- * `sign(client, userAddress)` produces the deep-frozen signature.
20
- * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
21
- * @throws {AddressMismatchError} from `sign()` when the client account differs from `userAddress`.
22
- * @throws {InvalidSignatureError} from `sign()` when EIP-712 verification fails.
23
- * @example
24
- * ```ts
25
- * import { encodeErc20Permit2Approve } from "@morpho-org/morpho-sdk";
26
- *
27
- * const requirement = encodeErc20Permit2Approve({
28
- * token: USDC,
29
- * amount: 1_000_000n,
30
- * chainId: 1,
31
- * nonce: 0n,
32
- * expiration: 281_474_976_710_655n, // MAX_UINT_48 (2^48 - 1, effectively indefinite)
33
- * });
34
- * // requirement satisfies Requirement
35
- * ```
36
- */
37
- export const encodeErc20Permit2Approve = (params) => {
38
- const { token, amount, chainId, nonce, expiration = MathLib.MAX_UINT_48, } = params;
39
- const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
40
- const now = Time.timestamp();
41
- const deadline = now + Time.s.from.h(2n);
42
- // Permit2 AllowanceTransfer signs over `PermitSingle` (token, spender, expiration, nonce), which
43
- // does not include the owner, so the payload is fully determined at build time.
44
- const typedData = deepFreeze(getPermit2PermitTypedData({
45
- spender: generalAdapter1,
46
- allowance: amount,
47
- erc20: token,
48
- nonce: Number(nonce),
49
- deadline,
50
- expiration: Number(expiration),
51
- }, chainId));
52
- const action = {
53
- type: "permit2",
54
- args: {
55
- spender: generalAdapter1,
56
- amount,
57
- deadline,
58
- expiration,
59
- },
60
- typedData,
61
- };
62
- return {
63
- action,
64
- async sign(client, userAddress) {
65
- const signature = await signAndVerifyTypedData({
66
- client,
67
- userAddress,
68
- typedData,
69
- });
70
- return deepFreeze({
71
- args: {
72
- owner: userAddress,
73
- signature,
74
- deadline,
75
- amount,
76
- asset: token,
77
- expiration,
78
- nonce,
79
- },
80
- action,
81
- });
82
- },
83
- };
84
- };
@@ -1,88 +0,0 @@
1
- import { type Address } from "@morpho-org/blue-sdk";
2
- import { type Client } from "viem";
3
- import type { Bundler3TokenSignatureRequirement, ERC20ApprovalAction, Transaction } from "../../../types/index.js";
4
- /** Shared parameters for GeneralAdapter1 token requirement resolution. */
5
- export type GetGeneralAdapterRequirementsBaseParams = {
6
- address: Address;
7
- chainId: number;
8
- supportDeployless?: boolean;
9
- args: {
10
- amount: bigint;
11
- from: Address;
12
- };
13
- };
14
- /** Parameters for {@link getGeneralAdapterRequirements}. */
15
- export type GetGeneralAdapterRequirementsParams = (GetGeneralAdapterRequirementsBaseParams & {
16
- /** Signature-based approvals are not supported. Classic approval (transaction) will be used. */
17
- supportSignature: false;
18
- }) | (GetGeneralAdapterRequirementsBaseParams & {
19
- /** Signature-based approvals are supported. Will try permit (EIP-2612), else fallback to permit2. */
20
- supportSignature: true;
21
- /**
22
- * Prefer the ERC-2612 simple-permit path when the SDK detects support.
23
- * Leave unset or set to `false` to force the Permit2 fallback when a token is known to be
24
- * incompatible despite passing the SDK's shallow nonce probe.
25
- */
26
- useSimplePermit?: boolean;
27
- });
28
- /**
29
- * Resolves the approval requirements an integrator must satisfy before a bundled action pulls
30
- * tokens through `GeneralAdapter1`.
31
- *
32
- * Reads the minimum token allowance / nonce state needed from the chain, then picks one of three
33
- * flows:
34
- *
35
- * 1. **`supportSignature: false`** — classic ERC-20 `approve` transaction (or no-op when the
36
- * direct allowance is already large enough).
37
- * 2. **`supportSignature: true` + EIP-2612 nonce detected + `useSimplePermit`** — single permit
38
- * signature against the token itself. DAI is excluded from this branch (its non-standard
39
- * permit signature is incompatible) and falls through to Permit2 even with
40
- * `useSimplePermit: true`.
41
- * 3. **`supportSignature: true`, default** — Permit2 flow: classic approval to the Permit2
42
- * contract (if needed), followed by a Permit2 signature against `GeneralAdapter1`.
43
- *
44
- * The simple-permit compatibility check is intentionally shallow: when requested, it probes
45
- * whether the token exposes a readable ERC-2612 `nonces(owner)` value.
46
- * Leaving `useSimplePermit` unset, or passing `false`, is the caller escape hatch for tokens
47
- * that expose `nonces` but are still incompatible with the SDK's ERC-2612 encoder. This opt-out
48
- * has proven useful in the past, but the SDK does not encode a token-specific example here.
49
- * DAI is handled as a built-in version of that incompatibility: it exposes `nonces(owner)` but is
50
- * always routed to Permit2/classic approval instead of DAI-specific permit signing.
51
- *
52
- * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
53
- * @param params - Requirement resolution parameters.
54
- * @param params.address - ERC-20 token address.
55
- * @param params.chainId - Chain id; must match `viemClient.chain.id`.
56
- * @param params.args.amount - Required token amount. Returns `[]` when zero.
57
- * @param params.args.from - Account that will grant the approval.
58
- * @param params.supportSignature - Whether the integrator can collect a signature; controls
59
- * permit / permit2 vs. classic approval.
60
- * @param params.supportDeployless - Whether ERC-2612 permit metadata reads may use deployless multicall.
61
- * @param params.useSimplePermit - When `supportSignature` is `true`, prefer EIP-2612 permit if
62
- * the nonce probe detects support. Leave unset or pass `false` to force the Permit2 fallback
63
- * for tokens known to be incompatible despite passing that probe.
64
- * @returns Promise resolving to an array of either deep-frozen approval transactions or
65
- * `Requirement` objects (signature requirements with a `sign()` method). Empty when `amount`
66
- * is zero or when the classic-approval path can reuse sufficient direct allowance.
67
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`. No other typed
68
- * error is reachable through this entry point: the values passed into
69
- * `getRequirementsApproval` always satisfy `approvalAmount >= spendAmount` (direct path uses
70
- * `approvalAmount === spendAmount === amount`; Permit2 path uses `MAX_UINT_160`), so
71
- * `ApprovalAmountLessThanSpendAmountError` cannot fire from here.
72
- * @example
73
- * ```ts
74
- * import { createPublicClient, http } from "viem";
75
- * import { mainnet } from "viem/chains";
76
- * import { getGeneralAdapterRequirements } from "@morpho-org/morpho-sdk";
77
- *
78
- * const client = createPublicClient({ chain: mainnet, transport: http() });
79
- * const requirements = await getGeneralAdapterRequirements(client, {
80
- * address: USDC,
81
- * chainId: 1,
82
- * supportSignature: true,
83
- * args: { amount: 1_000_000n, from: user },
84
- * });
85
- * // requirements satisfies (Readonly<Transaction<ERC20ApprovalAction>> | Bundler3TokenSignatureRequirement)[]
86
- * ```
87
- */
88
- export declare const getGeneralAdapterRequirements: (viemClient: Client, params: GetGeneralAdapterRequirementsParams) => Promise<(Readonly<Transaction<ERC20ApprovalAction>> | Bundler3TokenSignatureRequirement)[]>;
@@ -1,148 +0,0 @@
1
- import { getChainAddresses } from "@morpho-org/blue-sdk";
2
- import { erc2612Abi, permit2Abi } from "@morpho-org/blue-sdk-viem";
3
- import { isDefined } from "@morpho-org/morpho-ts";
4
- import { erc20Abi, isAddressEqual } from "viem";
5
- import { readContract } from "viem/actions";
6
- import { ChainIdMismatchError } from "../../../types/index.js";
7
- import { getRequirementsApproval } from "../getRequirementsApproval.js";
8
- import { getGeneralAdapterRequirementsPermit } from "./getGeneralAdapterRequirementsPermit.js";
9
- import { getGeneralAdapterRequirementsPermit2 } from "./getGeneralAdapterRequirementsPermit2.js";
10
- /**
11
- * Resolves the approval requirements an integrator must satisfy before a bundled action pulls
12
- * tokens through `GeneralAdapter1`.
13
- *
14
- * Reads the minimum token allowance / nonce state needed from the chain, then picks one of three
15
- * flows:
16
- *
17
- * 1. **`supportSignature: false`** — classic ERC-20 `approve` transaction (or no-op when the
18
- * direct allowance is already large enough).
19
- * 2. **`supportSignature: true` + EIP-2612 nonce detected + `useSimplePermit`** — single permit
20
- * signature against the token itself. DAI is excluded from this branch (its non-standard
21
- * permit signature is incompatible) and falls through to Permit2 even with
22
- * `useSimplePermit: true`.
23
- * 3. **`supportSignature: true`, default** — Permit2 flow: classic approval to the Permit2
24
- * contract (if needed), followed by a Permit2 signature against `GeneralAdapter1`.
25
- *
26
- * The simple-permit compatibility check is intentionally shallow: when requested, it probes
27
- * whether the token exposes a readable ERC-2612 `nonces(owner)` value.
28
- * Leaving `useSimplePermit` unset, or passing `false`, is the caller escape hatch for tokens
29
- * that expose `nonces` but are still incompatible with the SDK's ERC-2612 encoder. This opt-out
30
- * has proven useful in the past, but the SDK does not encode a token-specific example here.
31
- * DAI is handled as a built-in version of that incompatibility: it exposes `nonces(owner)` but is
32
- * always routed to Permit2/classic approval instead of DAI-specific permit signing.
33
- *
34
- * @param viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
35
- * @param params - Requirement resolution parameters.
36
- * @param params.address - ERC-20 token address.
37
- * @param params.chainId - Chain id; must match `viemClient.chain.id`.
38
- * @param params.args.amount - Required token amount. Returns `[]` when zero.
39
- * @param params.args.from - Account that will grant the approval.
40
- * @param params.supportSignature - Whether the integrator can collect a signature; controls
41
- * permit / permit2 vs. classic approval.
42
- * @param params.supportDeployless - Whether ERC-2612 permit metadata reads may use deployless multicall.
43
- * @param params.useSimplePermit - When `supportSignature` is `true`, prefer EIP-2612 permit if
44
- * the nonce probe detects support. Leave unset or pass `false` to force the Permit2 fallback
45
- * for tokens known to be incompatible despite passing that probe.
46
- * @returns Promise resolving to an array of either deep-frozen approval transactions or
47
- * `Requirement` objects (signature requirements with a `sign()` method). Empty when `amount`
48
- * is zero or when the classic-approval path can reuse sufficient direct allowance.
49
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`. No other typed
50
- * error is reachable through this entry point: the values passed into
51
- * `getRequirementsApproval` always satisfy `approvalAmount >= spendAmount` (direct path uses
52
- * `approvalAmount === spendAmount === amount`; Permit2 path uses `MAX_UINT_160`), so
53
- * `ApprovalAmountLessThanSpendAmountError` cannot fire from here.
54
- * @example
55
- * ```ts
56
- * import { createPublicClient, http } from "viem";
57
- * import { mainnet } from "viem/chains";
58
- * import { getGeneralAdapterRequirements } from "@morpho-org/morpho-sdk";
59
- *
60
- * const client = createPublicClient({ chain: mainnet, transport: http() });
61
- * const requirements = await getGeneralAdapterRequirements(client, {
62
- * address: USDC,
63
- * chainId: 1,
64
- * supportSignature: true,
65
- * args: { amount: 1_000_000n, from: user },
66
- * });
67
- * // requirements satisfies (Readonly<Transaction<ERC20ApprovalAction>> | Bundler3TokenSignatureRequirement)[]
68
- * ```
69
- */
70
- export const getGeneralAdapterRequirements = async (viemClient, params) => {
71
- const { address, chainId, supportSignature, args: { amount, from }, } = params;
72
- if (viemClient.chain?.id !== chainId) {
73
- throw new ChainIdMismatchError(viemClient.chain?.id, chainId);
74
- }
75
- if (amount === 0n) {
76
- return [];
77
- }
78
- const { permit2, dai, bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
79
- if (supportSignature) {
80
- const { useSimplePermit } = params;
81
- const isDai = isDefined(dai) && isAddressEqual(address, dai);
82
- if (useSimplePermit && !isDai) {
83
- const erc2612Nonce = await readContract(viemClient, {
84
- abi: erc2612Abi,
85
- address,
86
- functionName: "nonces",
87
- args: [from],
88
- }).catch(() => undefined);
89
- if (isDefined(erc2612Nonce)) {
90
- // Do not skip this exact permit because a previous ERC-20 allowance is already enough.
91
- // ERC-2612 overwrites the allowance, and the bundle spends exactly `amount`, so signing
92
- // the pulled amount leaves no residual direct allowance after inclusion.
93
- return getGeneralAdapterRequirementsPermit(viemClient, {
94
- token: address,
95
- owner: from,
96
- chainId,
97
- args: { amount },
98
- nonce: erc2612Nonce,
99
- supportDeployless: params.supportDeployless,
100
- });
101
- }
102
- }
103
- if (permit2) {
104
- // Do not check the existing Permit2-managed amount/expiration. Permit2 allowance signatures
105
- // overwrite the tuple, and the bundle spends exactly `amount`, so a fresh exact signature
106
- // leaves no residual Permit2 allowance. The tuple is still read because Permit2 requires
107
- // its nonce in the signed allowance payload.
108
- const [permit2Erc20Allowance, [, , permit2Nonce]] = await Promise.all([
109
- readContract(viemClient, {
110
- abi: erc20Abi,
111
- address,
112
- functionName: "allowance",
113
- args: [from, permit2],
114
- }),
115
- readContract(viemClient, {
116
- abi: permit2Abi,
117
- address: permit2,
118
- functionName: "allowance",
119
- args: [from, address, generalAdapter1],
120
- }),
121
- ]);
122
- return getGeneralAdapterRequirementsPermit2({
123
- address,
124
- chainId,
125
- permit2,
126
- args: { amount },
127
- erc20Allowances: { permit2: permit2Erc20Allowance },
128
- permit2Nonce: BigInt(permit2Nonce),
129
- });
130
- }
131
- }
132
- const generalAdapterAllowance = await readContract(viemClient, {
133
- abi: erc20Abi,
134
- address,
135
- functionName: "allowance",
136
- args: [from, generalAdapter1],
137
- });
138
- return getRequirementsApproval({
139
- address,
140
- chainId,
141
- args: {
142
- spendAmount: amount,
143
- approvalAmount: amount,
144
- spender: generalAdapter1,
145
- },
146
- allowances: generalAdapterAllowance,
147
- });
148
- };
@@ -1,40 +0,0 @@
1
- import type { Address, Client } from "viem";
2
- /**
3
- * Computes the EIP-2612 permit `Requirement` an integrator must sign so that `GeneralAdapter1`
4
- * can pull `amount` of `token`.
5
- *
6
- * @param viemClient - Connected viem `Client` (used by the returned `Requirement.sign()`).
7
- * @param params.token - ERC-20 token address (must support EIP-2612).
8
- * @param params.owner - Account that owns the tokens and signs the permit.
9
- * @param params.chainId - The chain the bundle targets.
10
- * @param params.args.amount - Required token amount.
11
- * @param params.nonce - The owner's current EIP-2612 nonce on `token`.
12
- * @param params.supportDeployless - Whether to fetch token metadata via deployless multicall.
13
- * @returns A single-element array containing the exact-amount `Requirement` to sign.
14
- * @example
15
- * ```ts
16
- * import { createWalletClient, http } from "viem";
17
- * import { mainnet } from "viem/chains";
18
- * import { getGeneralAdapterRequirementsPermit } from "@morpho-org/morpho-sdk";
19
- *
20
- * const client = createWalletClient({ chain: mainnet, transport: http() });
21
- * const reqs = await getGeneralAdapterRequirementsPermit(client, {
22
- * token: USDC, // an ERC-2612-compatible token; DAI is excluded by getGeneralAdapterRequirements
23
- * owner,
24
- * chainId: 1,
25
- * args: { amount: 1_000_000n },
26
- * nonce: 0n,
27
- * });
28
- * // reqs satisfies Requirement[]
29
- * ```
30
- */
31
- export declare const getGeneralAdapterRequirementsPermit: (viemClient: Client, params: {
32
- token: Address;
33
- owner: Address;
34
- chainId: number;
35
- args: {
36
- amount: bigint;
37
- };
38
- nonce: bigint;
39
- supportDeployless?: boolean;
40
- }) => Promise<import("../../../index.js").Requirement<import("../../../index.js").Erc2612RequirementSignature, undefined>[]>;