@morpho-org/morpho-sdk 5.8.0 → 6.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/MIGRATION-v5-to-v6.md +201 -0
  2. package/README.md +62 -40
  3. package/lib/cjs/abis.d.ts +543 -0
  4. package/lib/cjs/abis.js +738 -0
  5. package/lib/cjs/actions/blue/borrow.d.ts +62 -58
  6. package/lib/cjs/actions/blue/borrow.js +48 -80
  7. package/lib/cjs/actions/blue/common.d.ts +99 -0
  8. package/lib/cjs/actions/blue/common.js +318 -0
  9. package/lib/cjs/actions/blue/refinance.d.ts +72 -107
  10. package/lib/cjs/actions/blue/refinance.js +97 -197
  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 -86
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -119
  21. package/lib/cjs/actions/blue/withdraw.d.ts +68 -78
  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/index.d.ts +1 -1
  26. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  27. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  28. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  29. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +207 -0
  30. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  31. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  32. package/lib/cjs/actions/requirements/blue/index.d.ts +2 -0
  33. package/lib/cjs/actions/requirements/blue/index.js +2 -0
  34. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  35. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +7 -2
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -6
  40. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  41. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +123 -0
  42. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  43. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  44. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  45. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -4
  46. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -4
  47. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  48. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  49. package/lib/cjs/blue/types.d.ts +3 -1
  50. package/lib/cjs/blue/utils.d.ts +3 -1
  51. package/lib/cjs/blue/utils.js +1 -0
  52. package/lib/cjs/bundler/actions.d.ts +6 -4
  53. package/lib/cjs/bundler/actions.js +6 -4
  54. package/lib/cjs/bundler/types.d.ts +10 -1
  55. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  56. package/lib/cjs/client/morphoViemExtension.js +2 -1
  57. package/lib/cjs/entities/blue/blue.d.ts +817 -360
  58. package/lib/cjs/entities/blue/blue.js +455 -698
  59. package/lib/cjs/entities/index.d.ts +1 -0
  60. package/lib/cjs/entities/vaultV1/vaultV1.js +4 -12
  61. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +18 -3
  62. package/lib/cjs/entities/vaultV1ReallocationData.js +11 -1
  63. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -18
  64. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +7 -10
  65. package/lib/cjs/helpers/computeVaultV1Reallocations.js +7 -10
  66. package/lib/cjs/helpers/validate.d.ts +16 -23
  67. package/lib/cjs/helpers/validate.js +32 -48
  68. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  69. package/lib/cjs/helpers/validateRequirementSpender.js +2 -0
  70. package/lib/cjs/types/action.d.ts +146 -162
  71. package/lib/cjs/types/action.js +29 -2
  72. package/lib/cjs/types/client.d.ts +9 -0
  73. package/lib/cjs/types/error.d.ts +173 -18
  74. package/lib/cjs/types/error.js +230 -25
  75. package/lib/cjs/types/sharedLiquidity.d.ts +20 -4
  76. package/lib/cjs/types.d.ts +3 -1
  77. package/lib/cjs/utils.d.ts +3 -1
  78. package/lib/cjs/utils.js +1 -0
  79. package/lib/esm/abis.d.ts +543 -0
  80. package/lib/esm/abis.js +737 -0
  81. package/lib/esm/actions/blue/borrow.d.ts +62 -58
  82. package/lib/esm/actions/blue/borrow.js +48 -80
  83. package/lib/esm/actions/blue/common.d.ts +99 -0
  84. package/lib/esm/actions/blue/common.js +306 -0
  85. package/lib/esm/actions/blue/refinance.d.ts +72 -107
  86. package/lib/esm/actions/blue/refinance.js +98 -198
  87. package/lib/esm/actions/blue/repay.d.ts +72 -68
  88. package/lib/esm/actions/blue/repay.js +56 -118
  89. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  90. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  91. package/lib/esm/actions/blue/supply.d.ts +62 -45
  92. package/lib/esm/actions/blue/supply.js +94 -70
  93. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  94. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  95. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -86
  96. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -120
  97. package/lib/esm/actions/blue/withdraw.d.ts +68 -78
  98. package/lib/esm/actions/blue/withdraw.js +100 -96
  99. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  100. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  101. package/lib/esm/actions/index.d.ts +1 -1
  102. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  103. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  104. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  105. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +203 -0
  106. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  107. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  108. package/lib/esm/actions/requirements/blue/index.d.ts +2 -0
  109. package/lib/esm/actions/requirements/blue/index.js +2 -0
  110. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  111. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  112. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  113. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +8 -3
  114. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  115. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -7
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +119 -0
  118. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  119. package/lib/esm/actions/requirements/encode/index.js +1 -0
  120. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  121. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -4
  122. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -4
  123. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  124. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  125. package/lib/esm/blue/types.d.ts +3 -1
  126. package/lib/esm/blue/utils.d.ts +3 -1
  127. package/lib/esm/blue/utils.js +3 -1
  128. package/lib/esm/bundler/actions.d.ts +6 -4
  129. package/lib/esm/bundler/actions.js +6 -4
  130. package/lib/esm/bundler/types.d.ts +10 -1
  131. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  132. package/lib/esm/client/morphoViemExtension.js +2 -1
  133. package/lib/esm/entities/blue/blue.d.ts +817 -360
  134. package/lib/esm/entities/blue/blue.js +461 -704
  135. package/lib/esm/entities/index.d.ts +1 -0
  136. package/lib/esm/entities/vaultV1/vaultV1.js +4 -12
  137. package/lib/esm/entities/vaultV1ReallocationData.d.ts +18 -3
  138. package/lib/esm/entities/vaultV1ReallocationData.js +13 -2
  139. package/lib/esm/entities/vaultV2/vaultV2.js +7 -19
  140. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +7 -10
  141. package/lib/esm/helpers/computeVaultV1Reallocations.js +7 -10
  142. package/lib/esm/helpers/validate.d.ts +16 -23
  143. package/lib/esm/helpers/validate.js +32 -48
  144. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  145. package/lib/esm/helpers/validateRequirementSpender.js +2 -0
  146. package/lib/esm/types/action.d.ts +146 -162
  147. package/lib/esm/types/action.js +28 -2
  148. package/lib/esm/types/client.d.ts +9 -0
  149. package/lib/esm/types/error.d.ts +173 -18
  150. package/lib/esm/types/error.js +216 -21
  151. package/lib/esm/types/sharedLiquidity.d.ts +20 -4
  152. package/lib/esm/types.d.ts +3 -1
  153. package/lib/esm/utils.d.ts +3 -1
  154. package/lib/esm/utils.js +3 -1
  155. package/package.json +7 -6
  156. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  157. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  158. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  159. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  160. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  161. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  162. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  163. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  164. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  165. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  166. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  167. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -0,0 +1,306 @@
1
+ import { MarketParams, MathLib, VaultV2BluePublicAllocatorConfigUtils, } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
+ import { compactSignatureToSignature, encodeAbiParameters, isAddressEqual, maxUint256, parseCompactSignature, parseSignature, size, zeroAddress, zeroHash, } from "viem";
4
+ import { addTransactionMetadata, validateNativeAsset, } from "../../helpers/index.js";
5
+ import { validateVaultV2BlueReallocations } from "../../helpers/validate.js";
6
+ import { AmbiguousRequirementSignaturesError, BlueBundlesV1RequirementSignatureMismatchError, DepositAmountMismatchError, DepositAssetMismatchError, DepositOwnerMismatchError, DepositSpenderMismatchError, InputExceedsMaxError, MissingReferralFeeRecipientError, NativeFundingAmountMismatchError, NegativeInputError, NonPositiveInputError, ReallocationLoanTokenMismatchError, selectRequirementSignatures, UnexpectedRequirementSignatureError, } from "../../types/index.js";
7
+ /**
8
+ * BlueBundlesV1 token-permit discriminator carried in the encoded permit struct: `none` (0) skips
9
+ * the pull, `erc2612` (1) is an ERC-2612 permit, `permit2TransferFrom` (2) is a Permit2
10
+ * SignatureTransfer. Named so a transposed literal can't silently route a permit to the wrong branch.
11
+ * @internal
12
+ */
13
+ const BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND = {
14
+ none: 0,
15
+ erc2612: 1,
16
+ permit2TransferFrom: 2,
17
+ };
18
+ const EMPTY_TOKEN_PERMIT = {
19
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.none,
20
+ data: "0x",
21
+ };
22
+ const EMPTY_SIGNED_AUTHORIZATION = {
23
+ signature: { v: 0, r: zeroHash, s: zeroHash },
24
+ nonce: 0n,
25
+ deadline: 0n,
26
+ };
27
+ /** @internal */
28
+ export const normalizeBlueBundlesV1CommonParams = (params) => {
29
+ if (params.deadline <= 0n) {
30
+ throw new NonPositiveInputError("deadline", params.deadline);
31
+ }
32
+ if (params.deadline > maxUint256) {
33
+ throw new InputExceedsMaxError({
34
+ field: "deadline",
35
+ value: params.deadline,
36
+ max: maxUint256,
37
+ });
38
+ }
39
+ const referralFeePct = params.referralFeePct ?? 0n;
40
+ if (referralFeePct < 0n) {
41
+ throw new NegativeInputError("referralFeePct", referralFeePct);
42
+ }
43
+ if (referralFeePct >= MathLib.WAD) {
44
+ throw new InputExceedsMaxError({
45
+ field: "referralFeePct",
46
+ value: referralFeePct,
47
+ max: MathLib.WAD - 1n,
48
+ });
49
+ }
50
+ if (referralFeePct > 0n &&
51
+ (params.referralFeeRecipient == null ||
52
+ isAddressEqual(params.referralFeeRecipient, zeroAddress))) {
53
+ throw new MissingReferralFeeRecipientError();
54
+ }
55
+ return {
56
+ referralFeePct,
57
+ referralFeeRecipient: params.referralFeeRecipient ?? zeroAddress,
58
+ };
59
+ };
60
+ /** @internal */
61
+ export const validateBlueBundlesV1NativeFunding = (params) => {
62
+ const nativeAmount = params.nativeAmount ?? 0n;
63
+ if (nativeAmount < 0n) {
64
+ throw new NegativeInputError("nativeAmount", nativeAmount);
65
+ }
66
+ if (nativeAmount === 0n)
67
+ return 0n;
68
+ validateNativeAsset(params.chainId, params.token);
69
+ if (nativeAmount !== params.fundedAmount) {
70
+ throw new NativeFundingAmountMismatchError(nativeAmount, params.fundedAmount);
71
+ }
72
+ if (params.requirementSignature != null) {
73
+ throw new UnexpectedRequirementSignatureError(params.requirementSignature.action.type);
74
+ }
75
+ return nativeAmount;
76
+ };
77
+ /** @internal */
78
+ export const getBlueBundlesV1TokenPermit = (params) => {
79
+ const { requirementSignature } = params;
80
+ if (requirementSignature == null)
81
+ return EMPTY_TOKEN_PERMIT;
82
+ const spender = getChainAddress(params.chainId, "bundles.blueBundlesV1");
83
+ if (!isAddressEqual(requirementSignature.args.owner, params.userAddress)) {
84
+ throw new DepositOwnerMismatchError(params.userAddress, requirementSignature.args.owner);
85
+ }
86
+ if (!isAddressEqual(requirementSignature.args.asset, params.token)) {
87
+ throw new DepositAssetMismatchError(params.token, requirementSignature.args.asset);
88
+ }
89
+ if (requirementSignature.args.amount !== params.amount) {
90
+ throw new DepositAmountMismatchError(params.amount, requirementSignature.args.amount);
91
+ }
92
+ if (!isAddressEqual(requirementSignature.action.args.spender, spender)) {
93
+ throw new DepositSpenderMismatchError(spender, requirementSignature.action.args.spender);
94
+ }
95
+ if (requirementSignature.action.args.amount !== params.amount) {
96
+ throw new DepositAmountMismatchError(params.amount, requirementSignature.action.args.amount);
97
+ }
98
+ if (requirementSignature.action.args.deadline !==
99
+ requirementSignature.args.deadline) {
100
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
101
+ field: "deadline",
102
+ expected: String(requirementSignature.args.deadline),
103
+ actual: String(requirementSignature.action.args.deadline),
104
+ });
105
+ }
106
+ if (requirementSignature.action.type === "permit2TransferFrom") {
107
+ return {
108
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.permit2TransferFrom,
109
+ data: encodeAbiParameters([
110
+ { type: "uint256", name: "nonce" },
111
+ { type: "uint256", name: "deadline" },
112
+ { type: "bytes", name: "signature" },
113
+ ], [
114
+ requirementSignature.args.nonce,
115
+ requirementSignature.args.deadline,
116
+ requirementSignature.args.signature,
117
+ ]),
118
+ };
119
+ }
120
+ if (requirementSignature.action.type !== "permit") {
121
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
122
+ field: "type",
123
+ expected: "permit or permit2TransferFrom",
124
+ actual: requirementSignature.action.type,
125
+ });
126
+ }
127
+ const serializedSignature = requirementSignature.args.signature;
128
+ let parsed;
129
+ try {
130
+ parsed =
131
+ size(serializedSignature) === 64
132
+ ? compactSignatureToSignature(parseCompactSignature(serializedSignature))
133
+ : parseSignature(serializedSignature);
134
+ }
135
+ catch (cause) {
136
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
137
+ field: "signature",
138
+ expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
139
+ actual: serializedSignature,
140
+ cause,
141
+ });
142
+ }
143
+ const v = parsed.v ??
144
+ (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
145
+ if (v == null) {
146
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
147
+ field: "signature",
148
+ expected: "a signature containing v or yParity",
149
+ actual: serializedSignature,
150
+ });
151
+ }
152
+ return {
153
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.erc2612,
154
+ data: encodeAbiParameters([
155
+ { type: "uint256", name: "deadline" },
156
+ { type: "uint8", name: "v" },
157
+ { type: "bytes32", name: "r" },
158
+ { type: "bytes32", name: "s" },
159
+ ], [requirementSignature.args.deadline, Number(v), parsed.r, parsed.s]),
160
+ };
161
+ };
162
+ /** @internal */
163
+ export const getBlueBundlesV1SignedAuthorization = (params) => {
164
+ const { authorizationSignature } = params;
165
+ if (authorizationSignature == null)
166
+ return EMPTY_SIGNED_AUTHORIZATION;
167
+ const authorized = getChainAddress(params.chainId, "bundles.blueBundlesV1");
168
+ if (!isAddressEqual(authorizationSignature.args.owner, params.userAddress)) {
169
+ throw new DepositOwnerMismatchError(params.userAddress, authorizationSignature.args.owner);
170
+ }
171
+ if (!isAddressEqual(authorizationSignature.args.authorized, authorized)) {
172
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
173
+ field: "authorized",
174
+ expected: authorized,
175
+ actual: authorizationSignature.args.authorized,
176
+ });
177
+ }
178
+ if (!isAddressEqual(authorizationSignature.action.args.authorized, authorized)) {
179
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
180
+ field: "authorized",
181
+ expected: authorized,
182
+ actual: authorizationSignature.action.args.authorized,
183
+ });
184
+ }
185
+ if (!authorizationSignature.args.isAuthorized) {
186
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
187
+ field: "isAuthorized",
188
+ expected: "true",
189
+ actual: String(authorizationSignature.args.isAuthorized),
190
+ });
191
+ }
192
+ if (!authorizationSignature.action.args.isAuthorized) {
193
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
194
+ field: "isAuthorized",
195
+ expected: "true",
196
+ actual: String(authorizationSignature.action.args.isAuthorized),
197
+ });
198
+ }
199
+ if (authorizationSignature.action.args.deadline !==
200
+ authorizationSignature.args.deadline) {
201
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
202
+ field: "deadline",
203
+ expected: String(authorizationSignature.args.deadline),
204
+ actual: String(authorizationSignature.action.args.deadline),
205
+ });
206
+ }
207
+ const serializedSignature = authorizationSignature.args.signature;
208
+ let parsed;
209
+ try {
210
+ parsed =
211
+ size(serializedSignature) === 64
212
+ ? compactSignatureToSignature(parseCompactSignature(serializedSignature))
213
+ : parseSignature(serializedSignature);
214
+ }
215
+ catch (cause) {
216
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
217
+ field: "signature",
218
+ expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
219
+ actual: serializedSignature,
220
+ cause,
221
+ });
222
+ }
223
+ const v = parsed.v ??
224
+ (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
225
+ if (v == null) {
226
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
227
+ field: "signature",
228
+ expected: "a signature containing v or yParity",
229
+ actual: serializedSignature,
230
+ });
231
+ }
232
+ return {
233
+ signature: { v: Number(v), r: parsed.r, s: parsed.s },
234
+ nonce: authorizationSignature.args.nonce,
235
+ deadline: authorizationSignature.args.deadline,
236
+ };
237
+ };
238
+ /** @internal */
239
+ export const getBlueBundlesV1PublicAllocations = (reallocations, targetMarketParams) => {
240
+ validateVaultV2BlueReallocations(reallocations, targetMarketParams.id);
241
+ // Hoisted out of the map: idle sources all reference the same synthetic idle market, whose
242
+ // construction eagerly hashes the market id — computing it once per call instead of per entry.
243
+ const idleMarketParams = MarketParams.idle(targetMarketParams.loanToken);
244
+ return reallocations.map((reallocation) => {
245
+ if (reallocation.from.type === "market" &&
246
+ !isAddressEqual(reallocation.from.marketParams.loanToken, targetMarketParams.loanToken)) {
247
+ throw new ReallocationLoanTokenMismatchError(targetMarketParams.loanToken, reallocation.from.marketParams.loanToken);
248
+ }
249
+ return {
250
+ vault: reallocation.vault,
251
+ adapter: reallocation.to.adapter,
252
+ marketParams: targetMarketParams,
253
+ fromIdle: reallocation.from.type === "idle",
254
+ sourceAdapter: reallocation.from.type === "market"
255
+ ? reallocation.from.adapter
256
+ : zeroAddress,
257
+ sourceMarketParams: reallocation.from.type === "market"
258
+ ? reallocation.from.marketParams
259
+ : idleMarketParams,
260
+ assets: reallocation.assets,
261
+ penalty: reallocation.penalty,
262
+ };
263
+ });
264
+ };
265
+ /** @internal */
266
+ export const getBlueBundlesV1PenaltyAssets = (reallocations) => reallocations.reduce((total, reallocation) => total +
267
+ VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
268
+ /** @internal */
269
+ export const getBlueBundlesV1ReferralFeeAssets = (assets, referralFeePct) => referralFeePct === 0n
270
+ ? 0n
271
+ : MathLib.mulDivDown(assets, referralFeePct, MathLib.WAD - referralFeePct);
272
+ /** @internal */
273
+ export const selectBlueBundlesV1RequirementSignatures = (signatures, accepts) => {
274
+ const { permit, permit2TransferFrom, authorization } = selectRequirementSignatures(signatures, {
275
+ permit: accepts.token,
276
+ permit2TransferFrom: accepts.token,
277
+ authorization: accepts.authorization,
278
+ });
279
+ if (permit?.action.type === "permit2") {
280
+ throw new BlueBundlesV1RequirementSignatureMismatchError({
281
+ field: "type",
282
+ expected: "permit or permit2TransferFrom",
283
+ actual: permit.action.type,
284
+ });
285
+ }
286
+ if (permit != null && permit2TransferFrom != null) {
287
+ throw new AmbiguousRequirementSignaturesError("permit", 2);
288
+ }
289
+ return {
290
+ token: permit ??
291
+ permit2TransferFrom,
292
+ authorization,
293
+ };
294
+ };
295
+ /** @internal */
296
+ export const finalizeBlueBundlesV1Transaction = (params) => {
297
+ let transaction = {
298
+ to: getChainAddress(params.common.chainId, "bundles.blueBundlesV1"),
299
+ value: params.value,
300
+ data: params.data,
301
+ };
302
+ if (params.common.metadata != null) {
303
+ transaction = addTransactionMetadata(transaction, params.common.metadata);
304
+ }
305
+ return deepFreeze({ ...transaction, action: params.action });
306
+ };
@@ -1,130 +1,95 @@
1
- import { type MarketParams } from "@morpho-org/blue-sdk";
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueReallocationPlan, type BlueRefinanceAction, type Metadata, type Transaction } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueRefinanceAction, type Metadata, type Transaction, type VaultV2BlueReallocation } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRefinance}. */
5
5
  export interface BlueRefinanceParams {
6
- source: {
6
+ /** Chain plus source and destination Morpho Blue markets. */
7
+ readonly market: {
7
8
  readonly chainId: number;
8
- readonly marketParams: MarketParams;
9
+ readonly sourceMarketParams: MarketParams;
10
+ readonly destinationMarketParams: MarketParams;
9
11
  };
10
- target: {
11
- readonly marketParams: MarketParams;
12
- };
13
- args: {
14
- /** Address whose position is refinanced from the source to the target market. */
15
- user: Address;
16
- /** Amount of collateral moved from the source market to the target market. */
17
- collateralAmount: bigint;
18
- /**
19
- * Loan assets to borrow on the target. Assets mode: the exact borrow (exclusive with
20
- * `borrowShares`). Shares mode: the positive overshoot covering accrual + slippage; omitting it
21
- * throws {@link RefinanceSharesMissingBorrowAssetsError}.
22
- */
23
- borrowAssets?: bigint;
24
- /** Source borrow shares to repay (immune to mid-tx accrual); exclusive with `borrowAssets`. */
25
- borrowShares?: bigint;
26
- /** Minimum borrow share price on the target market (in ray). */
27
- minBorrowSharePrice: bigint;
28
- /** Maximum repay share price on the source market (in ray); must be > 0 when a repay leg exists. */
29
- maxRepaySharePrice: bigint;
30
- /** Homogeneous Vault V1 or Vault V2 reallocations into the target market. */
31
- targetReallocations?: BlueReallocationPlan;
12
+ /** Direct BlueBundlesV1 full-position migration arguments. */
13
+ readonly args: {
32
14
  /**
33
- * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
34
- * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
35
- * standalone `setAuthorization` transaction.
15
+ * Intended user used to bind an optional Morpho authorization and action metadata. This value is
16
+ * not encoded; the caller must send from the same account because BlueBundlesV1 always migrates
17
+ * `msg.sender`.
36
18
  */
37
- authorizationSignature?: AuthorizationRequirementSignature;
19
+ readonly userAddress: Address;
20
+ /** Maximum destination LTV enforced by BlueBundlesV1. */
21
+ readonly maxLtv: bigint;
22
+ /** Optional Vault V2 reallocations into the destination market. */
23
+ readonly reallocations?: Iterable<VaultV2BlueReallocation>;
24
+ /** Final call deadline in Unix seconds. */
25
+ readonly deadline: bigint;
26
+ /** Optional WAD-scaled referral fee, strictly below 100%. */
27
+ readonly referralFeePct?: bigint;
28
+ /** Recipient required when `referralFeePct` is positive. */
29
+ readonly referralFeeRecipient?: Address;
30
+ /** Optional Morpho authorization signature for BlueBundlesV1. */
31
+ readonly authorizationSignature?: AuthorizationRequirementSignature;
38
32
  };
39
- metadata?: Metadata;
33
+ /** Optional transaction metadata suffix. */
34
+ readonly metadata?: Metadata;
40
35
  }
41
36
  /**
42
- * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
43
- * chain that shares the same loan and collateral tokens.
44
- *
45
- * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
46
- * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
47
- * target, repays the source, then withdraws the source collateral to settle the transfer.
48
- *
49
- * Bundle shape (callback contents depend on borrow mode):
50
- *
51
- * ```text
52
- * // optional targetReallocations run first:
53
- * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
54
- *
55
- * morphoSupplyCollateral(target, collateralAmount, user, [
56
- * // omitted in collat-only mode
57
- * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
58
- * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
59
- * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
60
- * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
61
- * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
62
- * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
63
- * morphoWithdrawCollateral(source, collateralAmount, GA1),
64
- * ])
65
- * ```
66
- *
67
- * Borrow modes:
68
- *
69
- * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
70
- * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
71
- * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
72
- * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
73
- * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
37
+ * Encodes a direct BlueBundlesV1 full borrow-position migration transaction.
74
38
  *
75
- * Prerequisite: GA1 must be authorized on Blue — the entity's `getRequirements()` returns the
76
- * `setAuthorization` transaction when needed.
39
+ * BlueBundlesV1 reads and moves the user's complete live source debt and collateral. Source and
40
+ * destination must use identical tokens, and referral fees plus allocator penalties increase the
41
+ * destination debt. Partial and collateral-only migration are not supported.
77
42
  *
78
- * @param params.source.chainId - The chain both markets live on.
79
- * @param params.source.marketParams - Source market params (the position being closed).
80
- * @param params.target.marketParams - Target market params; must share both tokens with the source.
81
- * @param params.args.user - Position owner on both markets.
82
- * @param params.args.collateralAmount - Amount of collateral to migrate.
83
- * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
84
- * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
85
- * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
86
- * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
87
- * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
88
- * target, run before the supply leg. V1 fees add to `tx.value`; V2 penalties are paid in the target loan token.
89
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
90
- * a `setAuthorizationWithSig` call is prepended to the bundle.
91
- * @param params.metadata - Optional analytics metadata appended to `tx.data`.
92
- * @returns A deep-frozen `Transaction<BlueRefinanceAction>`.
93
- * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
94
- * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
95
- * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
96
- * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
97
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
98
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
99
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
100
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
101
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
102
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
103
- * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
104
- * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
105
- * @throws {RefinanceSameMarketError} when source and target market ids are equal.
106
- * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
107
- * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
108
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
109
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
110
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
43
+ * @param params - Migration encoding parameters.
44
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
45
+ * @param params.market.sourceMarketParams - Source market scoped by the Blue entity.
46
+ * @param params.market.destinationMarketParams - Distinct compatible destination market.
47
+ * @param params.args.userAddress - Intended user used to bind an optional Morpho authorization and
48
+ * action metadata. This value is not encoded; the caller must send from the same account because
49
+ * BlueBundlesV1 always migrates `msg.sender`.
50
+ * @param params.args.maxLtv - Maximum destination LTV.
51
+ * @param params.args.reallocations - Vault V2 reallocations into the destination.
52
+ * @param params.args.deadline - Final call deadline in Unix seconds.
53
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
54
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
55
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
56
+ * @param params.metadata - Optional transaction metadata.
57
+ * @returns A deep-frozen `Readonly<Transaction<BlueRefinanceAction>>` whose
58
+ * `to` address is BlueBundlesV1 and whose `action` records the normalized migration inputs.
59
+ * @throws {RefinanceSameMarketError} when source and destination IDs match.
60
+ * @throws {RefinanceTokenMismatchError} when their loan or collateral tokens differ.
61
+ * @throws {NegativeInputError} when `maxLtv`, a referral fee, or a reallocation penalty is negative.
62
+ * @throws {NonPositiveInputError} when the deadline or a reallocation amount is not positive.
63
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its ABI bound.
64
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
65
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
66
+ * @throws {InvalidReallocationShapeError} when a reallocation entry is not a valid Vault V2 reallocation.
67
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
68
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
69
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the destination market.
70
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
71
+ * @throws {DepositOwnerMismatchError} when the signed authorization owner differs from `userAddress`.
72
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when authorization cannot be bound safely.
73
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
74
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
111
75
  * @example
112
76
  * ```ts
77
+ * import { markets } from "@morpho-org/morpho-test";
113
78
  * import { blueRefinance } from "@morpho-org/morpho-sdk";
79
+ * import { zeroAddress } from "viem";
80
+ * import { mainnet } from "viem/chains";
114
81
  *
82
+ * const sourceMarketParams = markets[mainnet.id].eth_wstEth_2;
83
+ * const destinationMarketParams = markets[mainnet.id].eth_wstEth;
115
84
  * const tx = blueRefinance({
116
- * source: { chainId: 1, marketParams: sourceParams },
117
- * target: { marketParams: targetParams },
85
+ * market: { chainId: mainnet.id, sourceMarketParams, destinationMarketParams },
118
86
  * args: {
119
- * user: borrower,
120
- * collateralAmount: 1_000_000_000_000_000_000n,
121
- * borrowShares: 500_000_000_000n,
122
- * borrowAssets: 501_000_000n, // overshoot computed by entity layer
123
- * minBorrowSharePrice: 0n,
124
- * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
87
+ * userAddress: zeroAddress,
88
+ * maxLtv: 850000000000000000n,
89
+ * deadline: 1_900_000_000n,
125
90
  * },
126
91
  * });
127
92
  * // tx satisfies Readonly<Transaction<BlueRefinanceAction>>
128
93
  * ```
129
94
  */
130
- export declare const blueRefinance: ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets, borrowShares, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, authorizationSignature, }, metadata, }: BlueRefinanceParams) => Readonly<Transaction<BlueRefinanceAction>>;
95
+ export declare const blueRefinance: (params: BlueRefinanceParams) => Readonly<Transaction<BlueRefinanceAction>>;