@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
@@ -1,113 +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
- /**
22
- * Homogeneous Vault V1 or Vault V2 reallocations to execute before borrowing.
23
- * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 for new integrations.
24
- */
25
- reallocations?: BlueReallocationPlan;
26
- /**
27
- * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
28
- * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
29
- * standalone `setAuthorization` transaction.
30
- */
31
- 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;
32
35
  };
33
- metadata?: Metadata;
36
+ /** Optional transaction metadata suffix. */
37
+ readonly metadata?: Metadata;
34
38
  }
35
39
  /**
36
- * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
40
+ * Encodes a direct BlueBundlesV1 collateral supply and/or borrow transaction.
37
41
  *
38
- * Routed through bundler3: collateral funding → `morphoSupplyCollateral` → optional Public
39
- * Allocator calls → `morphoBorrow`. Each plan contains either V1 or V2 entries,
40
- * never both. When `nativeAmount > 0`, native ETH is wrapped via
41
- * `GeneralAdapter1.wrapNative()` before the supply leg. V1 fees add to
42
- * `tx.value`; V2 penalties are paid in the target loan token and donated to the vaults. When the
43
- * collateral and loan tokens match, one combined pull funds both collateral and penalties through
44
- * `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.
45
44
  *
46
- * Prerequisite: `GeneralAdapter1` must be authorized on Morpho to borrow on behalf of the user.
47
- * Use `getRequirements()` on the entity to check and obtain the authorization transaction.
48
- *
49
- * Zero loss: all collateral reaches Morpho, all borrowed tokens reach the receiver. No dust left
50
- * in bundler or adapter.
51
- *
52
- * @param params.market.chainId - The chain the market lives on.
53
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
54
- * @param params.args.amount - Amount of ERC-20 collateral to supply. At least one of `amount` or
55
- * `nativeAmount` must be positive. Defaults to `0n`.
56
- * @param params.args.borrowAmount - Loan asset amount to borrow.
57
- * @param params.args.onBehalf - Address whose Morpho position is credited with the collateral.
58
- * @param params.args.receiver - Address that receives the borrowed assets.
59
- * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
60
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
61
- * collateral funding. When collateral and loan tokens match, its amount includes V2 penalties.
62
- * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
63
- * collateral supply. Requires the collateral token to be the chain's wNative.
64
- * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
65
- * execute between the supply and borrow legs. Vault V1 inputs are deprecated; use Vault V2 for
66
- * new integrations.
67
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
68
- * a `setAuthorizationWithSig` call is prepended to the bundle.
69
- * @param params.metadata - Optional analytics metadata attached to the bundle.
70
- * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
71
- * `data`, and the typed `action` discriminator the simulation layer consumes.
72
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
73
- * penalty is negative.
74
- * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
75
- * zero, or any reallocation withdrawal amount is non-positive.
76
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
77
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
78
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
79
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
80
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
81
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
82
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
83
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
84
- * token is not the chain's wNative.
85
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
86
- * is provided and the signed asset differs from `marketParams.collateralToken`.
87
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
88
- * is provided and the signed amount differs from the total ERC-20 funding amount.
89
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
90
- * signature is missing its expiration.
91
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
92
- * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
93
- * the target market.
94
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
95
- * 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.
96
84
  * @example
97
85
  * ```ts
86
+ * import { markets } from "@morpho-org/morpho-test";
98
87
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
88
+ * import { maxUint256, zeroAddress } from "viem";
89
+ * import { mainnet } from "viem/chains";
99
90
  *
91
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
100
92
  * const tx = blueSupplyCollateralBorrow({
101
- * market: { chainId: 1, marketParams },
93
+ * market: { chainId: mainnet.id, marketParams },
102
94
  * args: {
103
- * amount: 1_000_000_000_000_000_000n,
104
- * borrowAmount: 500_000_000n,
105
- * onBehalf: borrower,
106
- * receiver: borrower,
107
- * 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,
108
100
  * },
109
101
  * });
110
102
  * // tx satisfies Readonly<Transaction<BlueSupplyCollateralBorrowAction>>
111
103
  * ```
112
104
  */
113
- 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,157 +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. Vault V1 inputs are deprecated; use Vault V2 for
43
- * new integrations.
44
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
45
- * a `setAuthorizationWithSig` call is prepended to the bundle.
46
- * @param params.metadata - Optional analytics metadata attached to the bundle.
47
- * @returns A deep-frozen `Transaction<BlueSupplyCollateralBorrowAction>` with `to`, `value`,
48
- * `data`, and the typed `action` discriminator the simulation layer consumes.
49
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, `minSharePrice`, a V1 fee, or a V2
50
- * penalty is negative.
51
- * @throws {NonPositiveInputError} when `borrowAmount <= 0n`, both collateral amounts resolve to
52
- * zero, or any reallocation withdrawal amount is non-positive.
53
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
54
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
55
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
56
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
57
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
58
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
59
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
60
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the collateral
61
- * token is not the chain's wNative.
62
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
63
- * is provided and the signed asset differs from `marketParams.collateralToken`.
64
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
65
- * is provided and the signed amount differs from the total ERC-20 funding amount.
66
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
67
- * signature is missing its expiration.
68
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
69
- * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
70
- * the target market.
71
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
72
- * 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.
73
54
  * @example
74
55
  * ```ts
56
+ * import { markets } from "@morpho-org/morpho-test";
75
57
  * import { blueSupplyCollateralBorrow } from "@morpho-org/morpho-sdk";
58
+ * import { maxUint256, zeroAddress } from "viem";
59
+ * import { mainnet } from "viem/chains";
76
60
  *
61
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
77
62
  * const tx = blueSupplyCollateralBorrow({
78
- * market: { chainId: 1, marketParams },
63
+ * market: { chainId: mainnet.id, marketParams },
79
64
  * args: {
80
- * amount: 1_000_000_000_000_000_000n,
81
- * borrowAmount: 500_000_000n,
82
- * onBehalf: borrower,
83
- * receiver: borrower,
84
- * 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,
85
70
  * },
86
71
  * });
87
72
  * // tx satisfies Readonly<Transaction<BlueSupplyCollateralBorrowAction>>
88
73
  * ```
89
74
  */
90
- const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams }, args: { amount = 0n, borrowAmount, onBehalf, receiver, minSharePrice, requirementSignature, nativeAmount, reallocations, authorizationSignature, }, metadata, }) => {
91
- if (amount < 0n) {
92
- 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);
93
84
  }
94
- if (nativeAmount !== undefined && nativeAmount < 0n) {
95
- 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);
96
87
  }
97
- if (borrowAmount <= 0n) {
98
- 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();
99
91
  }
100
- if (minSharePrice < 0n) {
101
- throw new index_js_3.NegativeInputError("minSharePrice", minSharePrice);
92
+ if (collateralAssets === 0n && requirementSignature != null) {
93
+ throw new index_js_1.UnexpectedRequirementSignatureError(requirementSignature.action.type);
102
94
  }
103
- const totalCollateral = amount + (nativeAmount ?? 0n);
104
- if (totalCollateral === 0n) {
105
- throw new index_js_3.NonPositiveInputError("totalCollateral", totalCollateral);
95
+ if (borrowAssets === 0n && authorizationSignature != null) {
96
+ throw new index_js_1.UnexpectedRequirementSignatureError("authorization");
106
97
  }
107
- const usesSharedFundingToken = (0, viem_1.isAddressEqual)(marketParams.collateralToken, marketParams.loanToken);
108
- 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)({
109
108
  chainId,
110
- reallocations,
111
- targetMarketParams: marketParams,
112
- penaltyFundingSource: usesSharedFundingToken
113
- ? "generalAdapter1"
114
- : "initiator",
109
+ token: marketParams.collateralToken,
110
+ fundedAmount: collateralAssets,
111
+ nativeAmount: params.args.nativeAmount,
112
+ requirementSignature,
115
113
  });
116
- const erc20FundingAmount = amount + (usesSharedFundingToken ? reallocationResult.penaltyAssets : 0n);
117
- const actions = [];
118
- if (authorizationSignature) {
119
- actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
120
- }
121
- actions.push(...(0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
114
+ const collateralPermit = (0, common_js_1.getBlueBundlesV1TokenPermit)({
122
115
  chainId,
123
- asset: marketParams.collateralToken,
124
- erc20Amount: erc20FundingAmount,
125
- nativeAmount: nativeAmount ?? 0n,
116
+ userAddress,
117
+ token: marketParams.collateralToken,
118
+ amount: collateralAssets,
126
119
  requirementSignature,
127
- }));
128
- actions.push({
129
- type: "morphoSupplyCollateral",
130
- args: [marketParams, totalCollateral, onBehalf, [], false],
131
120
  });
132
- actions.push(...reallocationResult.actions);
133
- actions.push({
134
- type: "morphoBorrow",
135
- args: [marketParams, borrowAmount, 0n, minSharePrice, receiver, false],
121
+ const signedAuthorization = (0, common_js_1.getBlueBundlesV1SignedAuthorization)({
122
+ chainId,
123
+ userAddress,
124
+ authorizationSignature,
136
125
  });
137
- let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
138
- if (metadata) {
139
- 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
+ });
140
134
  }
141
- return (0, morpho_ts_1.deepFreeze)({
142
- ...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
+ }),
143
154
  action: {
144
155
  type: "blueSupplyCollateralBorrow",
145
156
  args: {
146
157
  market: marketParams.id,
147
- collateralAmount: totalCollateral,
148
- borrowAmount,
149
- minSharePrice,
150
- onBehalf,
151
- receiver,
152
- nativeAmount,
153
- reallocationFee: reallocationResult.fee,
154
- 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,
155
168
  },
156
169
  },
157
170
  });