@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
@@ -1,109 +1,105 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueReallocationPlan, type BlueSupplyCollateralBorrowAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueBundlesV1TokenRequirementSignature, type BlueSupplyCollateralBorrowAction, type Metadata, type Transaction, type VaultV2BlueReallocation } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupplyCollateralBorrow}. */
5
5
  export interface BlueSupplyCollateralBorrowParams {
6
- market: {
6
+ /** Chain and scoped Morpho Blue market. */
7
+ readonly market: {
7
8
  readonly chainId: number;
8
9
  readonly marketParams: MarketParams;
9
10
  };
10
- args: DepositAmountArgs & {
11
- /** Amount of loan asset to borrow after the collateral is supplied. */
12
- borrowAmount: bigint;
13
- /** Address whose Morpho collateral and borrow positions are credited. */
14
- onBehalf: Address;
15
- /** Address that receives the borrowed assets. */
16
- receiver: Address;
17
- /** Minimum borrow share price (in ray). Protects against share price manipulation. */
18
- minSharePrice: bigint;
19
- /** Optional pre-signed permit/permit2 approval for the collateral transfer. */
20
- requirementSignature?: PermitRequirementSignature;
21
- /** Homogeneous Vault V1 or Vault V2 reallocations to execute before borrowing. */
22
- reallocations?: BlueReallocationPlan;
23
- /**
24
- * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
25
- * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
26
- * standalone `setAuthorization` transaction.
27
- */
28
- authorizationSignature?: AuthorizationRequirementSignature;
11
+ /** Direct BlueBundlesV1 combined-operation arguments. */
12
+ readonly args: {
13
+ /** User whose collateral and debt position is changed. */
14
+ readonly userAddress: Address;
15
+ /** Gross collateral supplied; zero selects a pure borrow. */
16
+ readonly collateralAssets: bigint;
17
+ /** Loan assets borrowed; zero selects a pure collateral supply. */
18
+ readonly borrowAssets: bigint;
19
+ /** Maximum post-operation LTV enforced by BlueBundlesV1. */
20
+ readonly maxLtv: bigint;
21
+ /** Full native collateral funding; must equal `collateralAssets`. */
22
+ readonly nativeAmount?: bigint;
23
+ /** Optional validated Vault V2 BluePublicAllocator reallocations. */
24
+ readonly reallocations?: Iterable<VaultV2BlueReallocation>;
25
+ /** Final call deadline in Unix seconds. */
26
+ readonly deadline: bigint;
27
+ /** Optional WAD-scaled referral fee, strictly below 100%. */
28
+ readonly referralFeePct?: bigint;
29
+ /** Recipient required when `referralFeePct` is positive. */
30
+ readonly referralFeeRecipient?: Address;
31
+ /** Optional collateral ERC-2612 or Permit2 SignatureTransfer result. */
32
+ readonly requirementSignature?: BlueBundlesV1TokenRequirementSignature;
33
+ /** Optional Morpho authorization signature for BlueBundlesV1. */
34
+ readonly authorizationSignature?: AuthorizationRequirementSignature;
29
35
  };
30
- metadata?: Metadata;
36
+ /** Optional transaction metadata suffix. */
37
+ readonly metadata?: Metadata;
31
38
  }
32
39
  /**
33
- * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
40
+ * Encodes a direct BlueBundlesV1 collateral supply and/or borrow transaction.
34
41
  *
35
- * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
36
- * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
37
- * never both. When `nativeAmount > 0`, native ETH is wrapped via
38
- * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
39
- * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
40
- * collateral and loan tokens match, one combined pull funds both collateral and penalties through
41
- * `GeneralAdapter1`.
42
+ * Reallocations are Vault V2-only and require a borrow leg. Penalties and referral fees reduce
43
+ * borrow proceeds. This route has no Bundler3 share-price bound or `slippageTolerance` input.
42
44
  *
43
- * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
44
- * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
45
- *
46
- * Zero loss: all collateral reaches Morpho, all borrowed tokens reach the receiver. No dust left
47
- * in bundler or adapter.
48
- *
49
- * @param params.market.chainId - The chain the market lives on.
50
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
51
- * @param params.args.amount - Amount of ERC-20 collateral to supply. At least one of `amount` or
52
- * `nativeAmount` must be positive. Defaults to `0n`.
53
- * @param params.args.borrowAmount - Loan asset amount to borrow.
54
- * @param params.args.onBehalf - Address whose Morpho position is credited with the collateral.
55
- * @param params.args.receiver - Address that receives the borrowed assets.
56
- * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
57
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
58
- * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
59
- * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
60
- * collateral supply. Requires the collateral token to be the chain's wNative.
61
- * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
62
- * execute between the supply and borrow legs.
63
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
64
- * a `setAuthorizationWithSig` call is prepended to the bundle.
65
- * @param params.metadata - Optional analytics metadata attached to the bundle.
66
- * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
67
- * `data`, and the typed `action` discriminator the simulation layer consumes.
68
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
69
- * penalty is negative.
70
- * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
71
- * zero, or any reallocation withdrawal amount is non-positive.
72
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
73
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
74
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
75
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
76
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
77
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
78
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
79
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
80
- * token is not the chain's wNative.
81
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
82
- * is provided and the signed asset differs from `marketParams.collateralToken`.
83
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
84
- * is provided and the signed amount differs from the total ERC-20 funding amount.
85
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
86
- * signature is missing its expiration.
87
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
88
- * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
89
- * the target market.
90
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
91
- * sorted by market id.
45
+ * @param params - Combined-operation encoding parameters.
46
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
47
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
48
+ * @param params.args.userAddress - User whose position is changed.
49
+ * @param params.args.collateralAssets - Gross collateral supplied, or zero.
50
+ * @param params.args.borrowAssets - Loan assets borrowed, or zero.
51
+ * @param params.args.maxLtv - Maximum post-operation LTV.
52
+ * @param params.args.nativeAmount - Exclusive native collateral funding.
53
+ * @param params.args.reallocations - Vault V2 reallocations executed before borrowing.
54
+ * @param params.args.deadline - Final call deadline in Unix seconds.
55
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
56
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
57
+ * @param params.args.requirementSignature - Optional collateral token signature.
58
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
59
+ * @param params.metadata - Optional transaction metadata.
60
+ * @returns A deep-frozen `Readonly<Transaction<BlueSupplyCollateralBorrowAction>>`
61
+ * whose `to` address is BlueBundlesV1 and whose `action` records the normalized inputs.
62
+ * @throws {NegativeInputError} when an amount, `maxLtv`, native value, or fee is negative.
63
+ * @throws {NonPositiveInputError} when both operation legs are zero, the deadline is not positive,
64
+ * or a reallocation amount is not positive.
65
+ * @throws {ReallocationsRequireBorrowError} when reallocations accompany no borrow.
66
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its ABI bound.
67
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
68
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
69
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
70
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
71
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the target market.
72
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
73
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
74
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
75
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another token.
76
+ * @throws {UnexpectedRequirementSignatureError} when a signature is supplied for an inactive leg.
77
+ * @throws {DepositOwnerMismatchError} when a signed owner differs from `userAddress`.
78
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the collateral token.
79
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `collateralAssets`.
80
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
81
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be bound safely.
82
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
83
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
92
84
  * @example
93
85
  * ```ts
86
+ * import { markets } from "@morpho-org/morpho-test";
94
87
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
88
+ * import { maxUint256, zeroAddress } from "viem";
89
+ * import { mainnet } from "viem/chains";
95
90
  *
91
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
96
92
  * const tx = blueSupplyCollateralBorrow({
97
- * market: { chainId: 1, marketParams },
93
+ * market: { chainId: mainnet.id, marketParams },
98
94
  * args: {
99
- * amount: 1_000_000_000_000_000_000n,
100
- * borrowAmount: 500_000_000n,
101
- * onBehalf: borrower,
102
- * receiver: borrower,
103
- * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinBorrowSharePrice` from market state + slippage tolerance
95
+ * userAddress: zeroAddress,
96
+ * collateralAssets: 1_000_000_000_000_000_000n,
97
+ * borrowAssets: 0n,
98
+ * maxLtv: maxUint256,
99
+ * deadline: 1_900_000_000n,
104
100
  * },
105
101
  * });
106
102
  * // tx satisfies Readonly<Transaction<BlueSupplyCollateralBorrowAction>>
107
103
  * ```
108
104
  */
109
- export declare const blueSupplyCollateralBorrow: ({ market: { chainId, marketParams }, args: { amount, borrowAmount, onBehalf, receiver, minSharePrice, requirementSignature, nativeAmount, reallocations, authorizationSignature, }, metadata, }: BlueSupplyCollateralBorrowParams) => Readonly<Transaction<BlueSupplyCollateralBorrowAction>>;
105
+ export declare const blueSupplyCollateralBorrow: (params: BlueSupplyCollateralBorrowParams) => Readonly<Transaction<BlueSupplyCollateralBorrowAction>>;
@@ -1,153 +1,167 @@
1
- import { deepFreeze } from "@morpho-org/morpho-ts";
2
- import { isAddressEqual } from "viem";
3
- import { BundlerAction } from "../../bundler/index.js";
4
- import { addTransactionMetadata } from "../../helpers/index.js";
5
- import { NegativeInputError, NonPositiveInputError, } from "../../types/index.js";
6
- import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
7
- import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
8
- import { buildBlueReallocationActions } from "./buildReallocationActions.js";
1
+ import { encodeFunctionData } from "viem";
2
+ import { blueBundlesV1Abi } from "../../abis.js";
3
+ import { validateUint256Field } from "../../helpers/validate.js";
4
+ import { InputExceedsMaxError, NonPositiveInputError, ReallocationsRequireBorrowError, UnexpectedRequirementSignatureError, } from "../../types/index.js";
5
+ import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1SignedAuthorization, getBlueBundlesV1TokenPermit, normalizeBlueBundlesV1CommonParams, validateBlueBundlesV1NativeFunding, } from "./common.js";
9
6
  /**
10
- * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
7
+ * Encodes a direct BlueBundlesV1 collateral supply and/or borrow transaction.
11
8
  *
12
- * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
13
- * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
14
- * never both. When `nativeAmount > 0`, native ETH is wrapped via
15
- * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
16
- * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
17
- * collateral and loan tokens match, one combined pull funds both collateral and penalties through
18
- * `GeneralAdapter1`.
9
+ * Reallocations are Vault V2-only and require a borrow leg. Penalties and referral fees reduce
10
+ * borrow proceeds. This route has no Bundler3 share-price bound or `slippageTolerance` input.
19
11
  *
20
- * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
21
- * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
22
- *
23
- * Zero loss: all collateral reaches Morpho, all borrowed tokens reach the receiver. No dust left
24
- * in bundler or adapter.
25
- *
26
- * @param params.market.chainId - The chain the market lives on.
27
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
28
- * @param params.args.amount - Amount of ERC-20 collateral to supply. At least one of `amount` or
29
- * `nativeAmount` must be positive. Defaults to `0n`.
30
- * @param params.args.borrowAmount - Loan asset amount to borrow.
31
- * @param params.args.onBehalf - Address whose Morpho position is credited with the collateral.
32
- * @param params.args.receiver - Address that receives the borrowed assets.
33
- * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
34
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
35
- * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
36
- * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
37
- * collateral supply. Requires the collateral token to be the chain's wNative.
38
- * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
39
- * execute between the supply and borrow legs.
40
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
41
- * a `setAuthorizationWithSig` call is prepended to the bundle.
42
- * @param params.metadata - Optional analytics metadata attached to the bundle.
43
- * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
44
- * `data`, and the typed `action` discriminator the simulation layer consumes.
45
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
46
- * penalty is negative.
47
- * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
48
- * zero, or any reallocation withdrawal amount is non-positive.
49
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
50
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
51
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
52
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
53
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
54
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
55
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
56
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
57
- * token is not the chain's wNative.
58
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
59
- * is provided and the signed asset differs from `marketParams.collateralToken`.
60
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
61
- * is provided and the signed amount differs from the total ERC-20 funding amount.
62
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
63
- * signature is missing its expiration.
64
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
65
- * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
66
- * the target market.
67
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
68
- * sorted by market id.
12
+ * @param params - Combined-operation encoding parameters.
13
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
14
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
15
+ * @param params.args.userAddress - User whose position is changed.
16
+ * @param params.args.collateralAssets - Gross collateral supplied, or zero.
17
+ * @param params.args.borrowAssets - Loan assets borrowed, or zero.
18
+ * @param params.args.maxLtv - Maximum post-operation LTV.
19
+ * @param params.args.nativeAmount - Exclusive native collateral funding.
20
+ * @param params.args.reallocations - Vault V2 reallocations executed before borrowing.
21
+ * @param params.args.deadline - Final call deadline in Unix seconds.
22
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
23
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
24
+ * @param params.args.requirementSignature - Optional collateral token signature.
25
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
26
+ * @param params.metadata - Optional transaction metadata.
27
+ * @returns A deep-frozen `Readonly<Transaction<BlueSupplyCollateralBorrowAction>>`
28
+ * whose `to` address is BlueBundlesV1 and whose `action` records the normalized inputs.
29
+ * @throws {NegativeInputError} when an amount, `maxLtv`, native value, or fee is negative.
30
+ * @throws {NonPositiveInputError} when both operation legs are zero, the deadline is not positive,
31
+ * or a reallocation amount is not positive.
32
+ * @throws {ReallocationsRequireBorrowError} when reallocations accompany no borrow.
33
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its ABI bound.
34
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
35
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
36
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
37
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
38
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the target market.
39
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
40
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
41
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
42
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another token.
43
+ * @throws {UnexpectedRequirementSignatureError} when a signature is supplied for an inactive leg.
44
+ * @throws {DepositOwnerMismatchError} when a signed owner differs from `userAddress`.
45
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the collateral token.
46
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `collateralAssets`.
47
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
48
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be bound safely.
49
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
50
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
69
51
  * @example
70
52
  * ```ts
53
+ * import { markets } from "@morpho-org/morpho-test";
71
54
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
55
+ * import { maxUint256, zeroAddress } from "viem";
56
+ * import { mainnet } from "viem/chains";
72
57
  *
58
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
73
59
  * const tx = blueSupplyCollateralBorrow({
74
- * market: { chainId: 1, marketParams },
60
+ * market: { chainId: mainnet.id, marketParams },
75
61
  * args: {
76
- * amount: 1_000_000_000_000_000_000n,
77
- * borrowAmount: 500_000_000n,
78
- * onBehalf: borrower,
79
- * receiver: borrower,
80
- * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinBorrowSharePrice` from market state + slippage tolerance
62
+ * userAddress: zeroAddress,
63
+ * collateralAssets: 1_000_000_000_000_000_000n,
64
+ * borrowAssets: 0n,
65
+ * maxLtv: maxUint256,
66
+ * deadline: 1_900_000_000n,
81
67
  * },
82
68
  * });
83
69
  * // tx satisfies Readonly<Transaction<BlueSupplyCollateralBorrowAction>>
84
70
  * ```
85
71
  */
86
- export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: { amount = 0n, borrowAmount, onBehalf, receiver, minSharePrice, requirementSignature, nativeAmount, reallocations, authorizationSignature, }, metadata, }) => {
87
- if (amount < 0n) {
88
- throw new NegativeInputError("amount", amount);
72
+ export const blueSupplyCollateralBorrow = (params) => {
73
+ const { chainId, marketParams } = params.market;
74
+ const { userAddress, collateralAssets, borrowAssets, maxLtv, requirementSignature, authorizationSignature, } = params.args;
75
+ for (const [field, value] of [
76
+ ["collateralAssets", collateralAssets],
77
+ ["borrowAssets", borrowAssets],
78
+ ["maxLtv", maxLtv],
79
+ ]) {
80
+ validateUint256Field(field, value);
89
81
  }
90
- if (nativeAmount !== undefined && nativeAmount < 0n) {
91
- throw new NegativeInputError("nativeAmount", nativeAmount);
82
+ if (collateralAssets === 0n && borrowAssets === 0n) {
83
+ throw new NonPositiveInputError("collateralAssets or borrowAssets", 0n);
92
84
  }
93
- if (borrowAmount <= 0n) {
94
- throw new NonPositiveInputError("borrowAmount", borrowAmount);
85
+ const reallocations = [...(params.args.reallocations ?? [])];
86
+ if (borrowAssets === 0n && reallocations.length > 0) {
87
+ throw new ReallocationsRequireBorrowError();
95
88
  }
96
- if (minSharePrice < 0n) {
97
- throw new NegativeInputError("minSharePrice", minSharePrice);
89
+ if (collateralAssets === 0n && requirementSignature != null) {
90
+ throw new UnexpectedRequirementSignatureError(requirementSignature.action.type);
98
91
  }
99
- const totalCollateral = amount + (nativeAmount ?? 0n);
100
- if (totalCollateral === 0n) {
101
- throw new NonPositiveInputError("totalCollateral", totalCollateral);
92
+ if (borrowAssets === 0n && authorizationSignature != null) {
93
+ throw new UnexpectedRequirementSignatureError("authorization");
102
94
  }
103
- const usesSharedFundingToken = isAddressEqual(marketParams.collateralToken, marketParams.loanToken);
104
- const reallocationResult = buildBlueReallocationActions({
95
+ const common = {
96
+ chainId,
97
+ userAddress,
98
+ deadline: params.args.deadline,
99
+ referralFeePct: params.args.referralFeePct,
100
+ referralFeeRecipient: params.args.referralFeeRecipient,
101
+ metadata: params.metadata,
102
+ };
103
+ const { referralFeePct, referralFeeRecipient } = normalizeBlueBundlesV1CommonParams(common);
104
+ const value = validateBlueBundlesV1NativeFunding({
105
105
  chainId,
106
- reallocations,
107
- targetMarketParams: marketParams,
108
- penaltyFundingSource: usesSharedFundingToken
109
- ? "generalAdapter1"
110
- : "initiator",
106
+ token: marketParams.collateralToken,
107
+ fundedAmount: collateralAssets,
108
+ nativeAmount: params.args.nativeAmount,
109
+ requirementSignature,
111
110
  });
112
- const erc20FundingAmount = amount + (usesSharedFundingToken ? reallocationResult.penaltyAssets : 0n);
113
- const actions = [];
114
- if (authorizationSignature) {
115
- actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
116
- }
117
- actions.push(...buildAssetFundingActions({
111
+ const collateralPermit = getBlueBundlesV1TokenPermit({
118
112
  chainId,
119
- asset: marketParams.collateralToken,
120
- erc20Amount: erc20FundingAmount,
121
- nativeAmount: nativeAmount ?? 0n,
113
+ userAddress,
114
+ token: marketParams.collateralToken,
115
+ amount: collateralAssets,
122
116
  requirementSignature,
123
- }));
124
- actions.push({
125
- type: "morphoSupplyCollateral",
126
- args: [marketParams, totalCollateral, onBehalf, [], false],
127
117
  });
128
- actions.push(...reallocationResult.actions);
129
- actions.push({
130
- type: "morphoBorrow",
131
- args: [marketParams, borrowAmount, 0n, minSharePrice, receiver, false],
118
+ const signedAuthorization = getBlueBundlesV1SignedAuthorization({
119
+ chainId,
120
+ userAddress,
121
+ authorizationSignature,
132
122
  });
133
- let tx = BundlerAction.encodeBundle(chainId, actions);
134
- if (metadata) {
135
- tx = addTransactionMetadata(tx, metadata);
123
+ const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, marketParams);
124
+ const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
125
+ if (reallocationPenaltyAssets > borrowAssets) {
126
+ throw new InputExceedsMaxError({
127
+ field: "reallocationPenaltyAssets",
128
+ value: reallocationPenaltyAssets,
129
+ max: borrowAssets,
130
+ });
136
131
  }
137
- return deepFreeze({
138
- ...tx,
132
+ return finalizeBlueBundlesV1Transaction({
133
+ common,
134
+ value,
135
+ data: encodeFunctionData({
136
+ abi: blueBundlesV1Abi,
137
+ functionName: "blueBundlesV1SupplyCollateralAndBorrow",
138
+ args: [
139
+ marketParams,
140
+ collateralAssets,
141
+ borrowAssets,
142
+ maxLtv,
143
+ collateralPermit,
144
+ signedAuthorization,
145
+ publicAllocations,
146
+ referralFeePct,
147
+ referralFeeRecipient,
148
+ params.args.deadline,
149
+ ],
150
+ }),
139
151
  action: {
140
152
  type: "blueSupplyCollateralBorrow",
141
153
  args: {
142
154
  market: marketParams.id,
143
- collateralAmount: totalCollateral,
144
- borrowAmount,
145
- minSharePrice,
146
- onBehalf,
147
- receiver,
148
- nativeAmount,
149
- reallocationFee: reallocationResult.fee,
150
- reallocationPenaltyAssets: reallocationResult.penaltyAssets,
155
+ collateralAssets,
156
+ borrowAssets,
157
+ maxLtv,
158
+ onBehalf: userAddress,
159
+ nativeAmount: value > 0n ? value : undefined,
160
+ reallocations: publicAllocations.length,
161
+ reallocationPenaltyAssets,
162
+ referralFeePct,
163
+ referralFeeRecipient,
164
+ deadline: params.args.deadline,
151
165
  },
152
166
  },
153
167
  });