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