@morpho-org/morpho-sdk 5.9.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 (141) hide show
  1. package/MIGRATION-v5-to-v6.md +201 -0
  2. package/README.md +58 -40
  3. package/lib/cjs/actions/blue/borrow.d.ts +62 -61
  4. package/lib/cjs/actions/blue/borrow.js +48 -80
  5. package/lib/cjs/actions/blue/common.d.ts +99 -0
  6. package/lib/cjs/actions/blue/common.js +318 -0
  7. package/lib/cjs/actions/blue/refinance.d.ts +72 -112
  8. package/lib/cjs/actions/blue/refinance.js +97 -199
  9. package/lib/cjs/actions/blue/repay.d.ts +72 -68
  10. package/lib/cjs/actions/blue/repay.js +56 -118
  11. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  12. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +148 -137
  13. package/lib/cjs/actions/blue/supply.d.ts +62 -45
  14. package/lib/cjs/actions/blue/supply.js +94 -70
  15. package/lib/cjs/actions/blue/supplyCollateral.d.ts +63 -40
  16. package/lib/cjs/actions/blue/supplyCollateral.js +52 -69
  17. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  18. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -120
  19. package/lib/cjs/actions/blue/withdraw.d.ts +68 -79
  20. package/lib/cjs/actions/blue/withdraw.js +101 -97
  21. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +56 -28
  22. package/lib/cjs/actions/blue/withdrawCollateral.js +45 -50
  23. package/lib/cjs/actions/index.d.ts +1 -1
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  25. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  26. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  27. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +207 -0
  28. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  29. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  30. package/lib/cjs/actions/requirements/blue/index.d.ts +2 -0
  31. package/lib/cjs/actions/requirements/blue/index.js +2 -0
  32. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  33. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  34. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  35. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +7 -2
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -6
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +123 -0
  40. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  41. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  42. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  43. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -4
  44. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -4
  45. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  46. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  47. package/lib/cjs/bundler/actions.d.ts +4 -4
  48. package/lib/cjs/bundler/actions.js +4 -4
  49. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  50. package/lib/cjs/client/morphoViemExtension.js +2 -1
  51. package/lib/cjs/entities/blue/blue.d.ts +806 -374
  52. package/lib/cjs/entities/blue/blue.js +447 -696
  53. package/lib/cjs/entities/index.d.ts +1 -0
  54. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +3 -9
  55. package/lib/cjs/helpers/computeVaultV1Reallocations.js +3 -9
  56. package/lib/cjs/helpers/validate.d.ts +14 -23
  57. package/lib/cjs/helpers/validate.js +30 -48
  58. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  59. package/lib/cjs/helpers/validateRequirementSpender.js +2 -0
  60. package/lib/cjs/types/action.d.ts +146 -162
  61. package/lib/cjs/types/action.js +29 -2
  62. package/lib/cjs/types/client.d.ts +9 -0
  63. package/lib/cjs/types/error.d.ts +141 -14
  64. package/lib/cjs/types/error.js +198 -21
  65. package/lib/cjs/types/sharedLiquidity.d.ts +0 -7
  66. package/lib/esm/actions/blue/borrow.d.ts +62 -61
  67. package/lib/esm/actions/blue/borrow.js +48 -80
  68. package/lib/esm/actions/blue/common.d.ts +99 -0
  69. package/lib/esm/actions/blue/common.js +306 -0
  70. package/lib/esm/actions/blue/refinance.d.ts +72 -112
  71. package/lib/esm/actions/blue/refinance.js +98 -200
  72. package/lib/esm/actions/blue/repay.d.ts +72 -68
  73. package/lib/esm/actions/blue/repay.js +56 -118
  74. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  75. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  76. package/lib/esm/actions/blue/supply.d.ts +62 -45
  77. package/lib/esm/actions/blue/supply.js +94 -70
  78. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  79. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  80. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  81. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -121
  82. package/lib/esm/actions/blue/withdraw.d.ts +68 -79
  83. package/lib/esm/actions/blue/withdraw.js +100 -96
  84. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  85. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  86. package/lib/esm/actions/index.d.ts +1 -1
  87. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  88. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  89. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  90. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +203 -0
  91. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  92. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  93. package/lib/esm/actions/requirements/blue/index.d.ts +2 -0
  94. package/lib/esm/actions/requirements/blue/index.js +2 -0
  95. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  96. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  97. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  98. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +8 -3
  99. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  100. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -7
  101. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  102. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +119 -0
  103. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  104. package/lib/esm/actions/requirements/encode/index.js +1 -0
  105. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  106. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -4
  107. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -4
  108. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  109. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  110. package/lib/esm/bundler/actions.d.ts +4 -4
  111. package/lib/esm/bundler/actions.js +4 -4
  112. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  113. package/lib/esm/client/morphoViemExtension.js +2 -1
  114. package/lib/esm/entities/blue/blue.d.ts +806 -374
  115. package/lib/esm/entities/blue/blue.js +453 -702
  116. package/lib/esm/entities/index.d.ts +1 -0
  117. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +3 -9
  118. package/lib/esm/helpers/computeVaultV1Reallocations.js +3 -9
  119. package/lib/esm/helpers/validate.d.ts +14 -23
  120. package/lib/esm/helpers/validate.js +30 -48
  121. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  122. package/lib/esm/helpers/validateRequirementSpender.js +2 -0
  123. package/lib/esm/types/action.d.ts +146 -162
  124. package/lib/esm/types/action.js +28 -2
  125. package/lib/esm/types/client.d.ts +9 -0
  126. package/lib/esm/types/error.d.ts +141 -14
  127. package/lib/esm/types/error.js +184 -17
  128. package/lib/esm/types/sharedLiquidity.d.ts +0 -7
  129. package/package.json +4 -3
  130. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  131. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  132. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  133. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  134. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  135. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  136. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  137. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  138. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  139. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  140. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  141. 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,135 +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;
12
+ /** Direct BlueBundlesV1 full-position migration arguments. */
13
+ readonly args: {
30
14
  /**
31
- * Homogeneous Vault V1 or Vault V2 reallocations into the target market.
32
- * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 for new integrations.
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`.
33
18
  */
34
- targetReallocations?: BlueReallocationPlan;
35
- /**
36
- * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
37
- * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
38
- * standalone `setAuthorization` transaction.
39
- */
40
- 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;
41
32
  };
42
- metadata?: Metadata;
33
+ /** Optional transaction metadata suffix. */
34
+ readonly metadata?: Metadata;
43
35
  }
44
36
  /**
45
- * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
46
- * chain that shares the same loan and collateral tokens.
47
- *
48
- * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
49
- * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
50
- * target, repays the source, then withdraws the source collateral to settle the transfer.
51
- *
52
- * Bundle shape (callback contents depend on borrow mode):
53
- *
54
- * ```text
55
- * // optional targetReallocations run first:
56
- * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
57
- *
58
- * morphoSupplyCollateral(target, collateralAmount, user, [
59
- * // omitted in collat-only mode
60
- * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
61
- * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
62
- * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
63
- * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
64
- * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
65
- * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
66
- * morphoWithdrawCollateral(source, collateralAmount, GA1),
67
- * ])
68
- * ```
69
- *
70
- * Borrow modes:
71
- *
72
- * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
73
- * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
74
- * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
75
- * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
76
- * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
37
+ * Encodes a direct BlueBundlesV1 full borrow-position migration transaction.
77
38
  *
78
- * Prerequisite: GA1 must be authorized on Blue — the entity's `getRequirements()` returns the
79
- * `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.
80
42
  *
81
- * @param params.source.chainId - The chain both markets live on.
82
- * @param params.source.marketParams - Source market params (the position being closed).
83
- * @param params.target.marketParams - Target market params; must share both tokens with the source.
84
- * @param params.args.user - Position owner on both markets.
85
- * @param params.args.collateralAmount - Amount of collateral to migrate.
86
- * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
87
- * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
88
- * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
89
- * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
90
- * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
91
- * target, run before the supply leg. Vault V1 inputs are deprecated for high-level Blue writes;
92
- * use Vault V2 for new integrations. V1 fees add to `tx.value`; V2 penalties are paid in the
93
- * target loan token.
94
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
95
- * a `setAuthorizationWithSig` call is prepended to the bundle.
96
- * @param params.metadata - Optional analytics metadata appended to `tx.data`.
97
- * @returns A deep-frozen `Transaction<BlueRefinanceAction>`.
98
- * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
99
- * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
100
- * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
101
- * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
102
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
103
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
104
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
105
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
106
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
107
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
108
- * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
109
- * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
110
- * @throws {RefinanceSameMarketError} when source and target market ids are equal.
111
- * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
112
- * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
113
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
114
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
115
- * @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.
116
75
  * @example
117
76
  * ```ts
77
+ * import { markets } from "@morpho-org/morpho-test";
118
78
  * import { blueRefinance } from "@morpho-org/morpho-sdk";
79
+ * import { zeroAddress } from "viem";
80
+ * import { mainnet } from "viem/chains";
119
81
  *
82
+ * const sourceMarketParams = markets[mainnet.id].eth_wstEth_2;
83
+ * const destinationMarketParams = markets[mainnet.id].eth_wstEth;
120
84
  * const tx = blueRefinance({
121
- * source: { chainId: 1, marketParams: sourceParams },
122
- * target: { marketParams: targetParams },
85
+ * market: { chainId: mainnet.id, sourceMarketParams, destinationMarketParams },
123
86
  * args: {
124
- * user: borrower,
125
- * collateralAmount: 1_000_000_000_000_000_000n,
126
- * borrowShares: 500_000_000_000n,
127
- * borrowAssets: 501_000_000n, // overshoot computed by entity layer
128
- * minBorrowSharePrice: 0n,
129
- * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
87
+ * userAddress: zeroAddress,
88
+ * maxLtv: 850000000000000000n,
89
+ * deadline: 1_900_000_000n,
130
90
  * },
131
91
  * });
132
92
  * // tx satisfies Readonly<Transaction<BlueRefinanceAction>>
133
93
  * ```
134
94
  */
135
- 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>>;