@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
@@ -2,102 +2,70 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueBorrow = void 0;
4
4
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
5
- const index_js_1 = require("../../bundler/index.js");
6
- const index_js_2 = require("../../helpers/index.js");
7
- const index_js_3 = require("../../types/index.js");
8
- const getBlueAuthorizationAction_js_1 = require("../signatures/getBlueAuthorizationAction.js");
9
- const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
5
+ const supplyCollateralBorrow_js_1 = require("./supplyCollateralBorrow.js");
10
6
  /**
11
- * Prepares a borrow transaction for a Morpho Blue market.
7
+ * Encodes a pure borrow through BlueBundlesV1.
12
8
  *
13
- * Routed through bundler3 via `morphoBorrow`. The bundler uses the transaction initiator as
14
- * `onBehalf`. Uses `minSharePrice` to protect against share price manipulation between
15
- * transaction construction and execution.
9
+ * Delegates to {@link blueSupplyCollateralBorrow} with a zero collateral leg. Vault V2 allocator
10
+ * penalties and referral fees reduce the assets received, and no Bundler3 action is encoded.
16
11
  *
17
- * A `reallocations` plan contains either PublicAllocator V1 entries or Vault V2
18
- * BluePublicAllocator entries, never both. The calls run before the borrow.
19
- * V1 fees accumulate in `tx.value`; V2 penalties are paid in the target loan
20
- * token and donated directly to each vault.
21
- *
22
- * @param params.market.chainId - The chain the market lives on.
23
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
24
- * @param params.args.amount - Loan asset amount to borrow, in the loan token's smallest unit.
25
- * @param params.args.receiver - Address that receives the borrowed assets.
26
- * @param params.args.minSharePrice - Minimum borrow share price (in ray). Slippage protection.
27
- * @param params.args.reallocations - Optional homogeneous Vault V1 or Vault V2 reallocations to
28
- * execute before borrowing. Vault V1 inputs are deprecated; use Vault V2 for new integrations.
29
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
30
- * a `setAuthorizationWithSig` call is prepended to the bundle.
31
- * @param params.metadata - Optional analytics metadata attached to the bundle.
32
- * @returns A deep-frozen `Transaction<BlueBorrowAction>` with `to`, `value`, `data`, and the
33
- * typed `action` discriminator the simulation layer consumes.
34
- * @throws {NonPositiveInputError} when `amount <= 0n` or any reallocation withdrawal amount
35
- * is non-positive.
36
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
37
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
38
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
39
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
40
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
41
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
42
- * @throws {NegativeInputError} when `minSharePrice < 0n`, a V1 fee, or a V2 penalty is negative.
43
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
44
- * @throws {ReallocationWithdrawalOnTargetMarketError} when any reallocation withdrawal references
45
- * the target market.
46
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly
47
- * sorted by market id.
12
+ * @param params - Borrow 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 debt position is increased.
16
+ * @param params.args.borrowAssets - Gross loan assets borrowed.
17
+ * @param params.args.maxLtv - Maximum post-operation LTV.
18
+ * @param params.args.reallocations - Vault V2 reallocations executed before borrowing.
19
+ * @param params.args.deadline - Final call deadline in Unix seconds.
20
+ * @param params.args.referralFeePct - Optional WAD-scaled referral fee.
21
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
22
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
23
+ * @param params.metadata - Optional transaction metadata.
24
+ * @returns A deep-frozen `Readonly<Transaction<BlueBorrowAction>>` whose calldata invokes the
25
+ * combined BlueBundlesV1 entrypoint with a zero collateral leg.
26
+ * @throws {NegativeInputError} when an amount, LTV, fee, or reallocation penalty is negative.
27
+ * @throws {NonPositiveInputError} when the borrow, deadline, or reallocation amount is not positive.
28
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its bound.
29
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
30
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
31
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
32
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
33
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the target market.
34
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
35
+ * @throws {DepositOwnerMismatchError} when the signed authorization owner differs from `userAddress`.
36
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when authorization cannot be bound safely.
37
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
38
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
48
39
  * @example
49
40
  * ```ts
41
+ * import { markets } from "@morpho-org/morpho-test";
50
42
  * import { blueBorrow } from "@morpho-org/morpho-sdk";
43
+ * import { zeroAddress } from "viem";
44
+ * import { mainnet } from "viem/chains";
51
45
  *
52
46
  * const tx = blueBorrow({
53
- * market: { chainId: 1, marketParams },
47
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
54
48
  * args: {
55
- * amount: 1_000_000n,
56
- * receiver: borrower,
57
- * minSharePrice: 0n, // disables slippage protection — production code should compute via `computeMinBorrowSharePrice` from market state + slippage tolerance
49
+ * userAddress: zeroAddress,
50
+ * borrowAssets: 1_000_000n,
51
+ * maxLtv: 850000000000000000n,
52
+ * deadline: 1_900_000_000n,
58
53
  * },
59
54
  * });
60
55
  * // tx satisfies Readonly<Transaction<BlueBorrowAction>>
61
56
  * ```
62
57
  */
63
- const blueBorrow = ({ market: { chainId, marketParams }, args: { amount, receiver, minSharePrice, reallocations, authorizationSignature, }, metadata, }) => {
64
- if (amount <= 0n) {
65
- throw new index_js_3.NonPositiveInputError("amount", amount);
66
- }
67
- if (minSharePrice < 0n) {
68
- throw new index_js_3.NegativeInputError("minSharePrice", minSharePrice);
69
- }
70
- const actions = [];
71
- if (authorizationSignature) {
72
- actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
73
- }
74
- const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
75
- chainId,
76
- reallocations,
77
- targetMarketParams: marketParams,
78
- });
79
- actions.push(...reallocationActions);
80
- actions.push({
81
- type: "morphoBorrow",
82
- args: [marketParams, amount, 0n, minSharePrice, receiver, false],
58
+ const blueBorrow = (params) => {
59
+ const transaction = (0, supplyCollateralBorrow_js_1.blueSupplyCollateralBorrow)({
60
+ ...params,
61
+ args: {
62
+ ...params.args,
63
+ collateralAssets: 0n,
64
+ },
83
65
  });
84
- let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
85
- if (metadata) {
86
- tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
87
- }
88
66
  return (0, morpho_ts_1.deepFreeze)({
89
- ...tx,
90
- action: {
91
- type: "blueBorrow",
92
- args: {
93
- market: marketParams.id,
94
- amount,
95
- receiver,
96
- minSharePrice,
97
- reallocationFee,
98
- reallocationPenaltyAssets,
99
- },
100
- },
67
+ ...transaction,
68
+ action: { ...transaction.action, type: "blueBorrow" },
101
69
  });
102
70
  };
103
71
  exports.blueBorrow = blueBorrow;
@@ -0,0 +1,99 @@
1
+ import { MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Hex } from "viem";
3
+ import { type AuthorizationRequirementSignature, type BaseAction, type BlueBundlesV1TokenRequirementSignature, type Metadata, type RequirementSignature, type TokenRequirementSignature, type Transaction, type VaultV2BlueReallocation } from "../../types/index.js";
4
+ /** @internal */
5
+ export interface BlueBundlesV1CommonParams {
6
+ chainId: number;
7
+ userAddress: Address;
8
+ deadline: bigint;
9
+ referralFeePct?: bigint;
10
+ referralFeeRecipient?: Address;
11
+ metadata?: Metadata;
12
+ }
13
+ /** @internal */
14
+ export interface NormalizedBlueBundlesV1CommonParams {
15
+ referralFeePct: bigint;
16
+ referralFeeRecipient: Address;
17
+ }
18
+ /**
19
+ * BlueBundlesV1 token-permit discriminator carried in the encoded permit struct: `none` (0) skips
20
+ * the pull, `erc2612` (1) is an ERC-2612 permit, `permit2TransferFrom` (2) is a Permit2
21
+ * SignatureTransfer. Named so a transposed literal can't silently route a permit to the wrong branch.
22
+ * @internal
23
+ */
24
+ declare const BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND: {
25
+ readonly none: 0;
26
+ readonly erc2612: 1;
27
+ readonly permit2TransferFrom: 2;
28
+ };
29
+ interface BlueBundlesV1TokenPermit {
30
+ kind: (typeof BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND)[keyof typeof BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND];
31
+ data: Hex;
32
+ }
33
+ interface BlueBundlesV1SignedAuthorization {
34
+ signature: {
35
+ v: number;
36
+ r: Hex;
37
+ s: Hex;
38
+ };
39
+ nonce: bigint;
40
+ deadline: bigint;
41
+ }
42
+ /** @internal */
43
+ export declare const normalizeBlueBundlesV1CommonParams: (params: BlueBundlesV1CommonParams) => NormalizedBlueBundlesV1CommonParams;
44
+ /** @internal */
45
+ export declare const validateBlueBundlesV1NativeFunding: (params: {
46
+ chainId: number;
47
+ token: Address;
48
+ fundedAmount: bigint;
49
+ nativeAmount?: bigint;
50
+ requirementSignature?: BlueBundlesV1TokenRequirementSignature;
51
+ }) => bigint;
52
+ /** @internal */
53
+ export declare const getBlueBundlesV1TokenPermit: (params: {
54
+ chainId: number;
55
+ userAddress: Address;
56
+ token: Address;
57
+ amount: bigint;
58
+ requirementSignature?: TokenRequirementSignature;
59
+ }) => BlueBundlesV1TokenPermit;
60
+ /** @internal */
61
+ export declare const getBlueBundlesV1SignedAuthorization: (params: {
62
+ chainId: number;
63
+ userAddress: Address;
64
+ authorizationSignature?: AuthorizationRequirementSignature;
65
+ }) => BlueBundlesV1SignedAuthorization;
66
+ /** @internal */
67
+ export declare const getBlueBundlesV1PublicAllocations: (reallocations: readonly VaultV2BlueReallocation[], targetMarketParams: MarketParams) => {
68
+ vault: `0x${string}`;
69
+ adapter: `0x${string}`;
70
+ marketParams: MarketParams;
71
+ fromIdle: boolean;
72
+ sourceAdapter: `0x${string}`;
73
+ sourceMarketParams: MarketParams;
74
+ assets: bigint;
75
+ penalty: bigint;
76
+ }[];
77
+ /** @internal */
78
+ export declare const getBlueBundlesV1PenaltyAssets: (reallocations: readonly {
79
+ assets: bigint;
80
+ penalty: bigint;
81
+ }[]) => bigint;
82
+ /** @internal */
83
+ export declare const getBlueBundlesV1ReferralFeeAssets: (assets: bigint, referralFeePct: bigint) => bigint;
84
+ /** @internal */
85
+ export declare const selectBlueBundlesV1RequirementSignatures: (signatures: readonly RequirementSignature[] | undefined, accepts: {
86
+ token?: boolean;
87
+ authorization?: boolean;
88
+ }) => {
89
+ token?: BlueBundlesV1TokenRequirementSignature;
90
+ authorization?: AuthorizationRequirementSignature;
91
+ };
92
+ /** @internal */
93
+ export declare const finalizeBlueBundlesV1Transaction: <TAction extends BaseAction>(params: {
94
+ common: BlueBundlesV1CommonParams;
95
+ value: bigint;
96
+ data: Hex;
97
+ action: TAction;
98
+ }) => Readonly<Transaction<TAction>>;
99
+ export {};
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.finalizeBlueBundlesV1Transaction = exports.selectBlueBundlesV1RequirementSignatures = exports.getBlueBundlesV1ReferralFeeAssets = exports.getBlueBundlesV1PenaltyAssets = exports.getBlueBundlesV1PublicAllocations = exports.getBlueBundlesV1SignedAuthorization = exports.getBlueBundlesV1TokenPermit = exports.validateBlueBundlesV1NativeFunding = exports.normalizeBlueBundlesV1CommonParams = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const viem_1 = require("viem");
7
+ const index_js_1 = require("../../helpers/index.js");
8
+ const validate_js_1 = require("../../helpers/validate.js");
9
+ const index_js_2 = require("../../types/index.js");
10
+ /**
11
+ * BlueBundlesV1 token-permit discriminator carried in the encoded permit struct: `none` (0) skips
12
+ * the pull, `erc2612` (1) is an ERC-2612 permit, `permit2TransferFrom` (2) is a Permit2
13
+ * SignatureTransfer. Named so a transposed literal can't silently route a permit to the wrong branch.
14
+ * @internal
15
+ */
16
+ const BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND = {
17
+ none: 0,
18
+ erc2612: 1,
19
+ permit2TransferFrom: 2,
20
+ };
21
+ const EMPTY_TOKEN_PERMIT = {
22
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.none,
23
+ data: "0x",
24
+ };
25
+ const EMPTY_SIGNED_AUTHORIZATION = {
26
+ signature: { v: 0, r: viem_1.zeroHash, s: viem_1.zeroHash },
27
+ nonce: 0n,
28
+ deadline: 0n,
29
+ };
30
+ /** @internal */
31
+ const normalizeBlueBundlesV1CommonParams = (params) => {
32
+ if (params.deadline <= 0n) {
33
+ throw new index_js_2.NonPositiveInputError("deadline", params.deadline);
34
+ }
35
+ if (params.deadline > viem_1.maxUint256) {
36
+ throw new index_js_2.InputExceedsMaxError({
37
+ field: "deadline",
38
+ value: params.deadline,
39
+ max: viem_1.maxUint256,
40
+ });
41
+ }
42
+ const referralFeePct = params.referralFeePct ?? 0n;
43
+ if (referralFeePct < 0n) {
44
+ throw new index_js_2.NegativeInputError("referralFeePct", referralFeePct);
45
+ }
46
+ if (referralFeePct >= blue_sdk_1.MathLib.WAD) {
47
+ throw new index_js_2.InputExceedsMaxError({
48
+ field: "referralFeePct",
49
+ value: referralFeePct,
50
+ max: blue_sdk_1.MathLib.WAD - 1n,
51
+ });
52
+ }
53
+ if (referralFeePct > 0n &&
54
+ (params.referralFeeRecipient == null ||
55
+ (0, viem_1.isAddressEqual)(params.referralFeeRecipient, viem_1.zeroAddress))) {
56
+ throw new index_js_2.MissingReferralFeeRecipientError();
57
+ }
58
+ return {
59
+ referralFeePct,
60
+ referralFeeRecipient: params.referralFeeRecipient ?? viem_1.zeroAddress,
61
+ };
62
+ };
63
+ exports.normalizeBlueBundlesV1CommonParams = normalizeBlueBundlesV1CommonParams;
64
+ /** @internal */
65
+ const validateBlueBundlesV1NativeFunding = (params) => {
66
+ const nativeAmount = params.nativeAmount ?? 0n;
67
+ if (nativeAmount < 0n) {
68
+ throw new index_js_2.NegativeInputError("nativeAmount", nativeAmount);
69
+ }
70
+ if (nativeAmount === 0n)
71
+ return 0n;
72
+ (0, index_js_1.validateNativeAsset)(params.chainId, params.token);
73
+ if (nativeAmount !== params.fundedAmount) {
74
+ throw new index_js_2.NativeFundingAmountMismatchError(nativeAmount, params.fundedAmount);
75
+ }
76
+ if (params.requirementSignature != null) {
77
+ throw new index_js_2.UnexpectedRequirementSignatureError(params.requirementSignature.action.type);
78
+ }
79
+ return nativeAmount;
80
+ };
81
+ exports.validateBlueBundlesV1NativeFunding = validateBlueBundlesV1NativeFunding;
82
+ /** @internal */
83
+ const getBlueBundlesV1TokenPermit = (params) => {
84
+ const { requirementSignature } = params;
85
+ if (requirementSignature == null)
86
+ return EMPTY_TOKEN_PERMIT;
87
+ const spender = (0, morpho_ts_1.getChainAddress)(params.chainId, "bundles.blueBundlesV1");
88
+ if (!(0, viem_1.isAddressEqual)(requirementSignature.args.owner, params.userAddress)) {
89
+ throw new index_js_2.DepositOwnerMismatchError(params.userAddress, requirementSignature.args.owner);
90
+ }
91
+ if (!(0, viem_1.isAddressEqual)(requirementSignature.args.asset, params.token)) {
92
+ throw new index_js_2.DepositAssetMismatchError(params.token, requirementSignature.args.asset);
93
+ }
94
+ if (requirementSignature.args.amount !== params.amount) {
95
+ throw new index_js_2.DepositAmountMismatchError(params.amount, requirementSignature.args.amount);
96
+ }
97
+ if (!(0, viem_1.isAddressEqual)(requirementSignature.action.args.spender, spender)) {
98
+ throw new index_js_2.DepositSpenderMismatchError(spender, requirementSignature.action.args.spender);
99
+ }
100
+ if (requirementSignature.action.args.amount !== params.amount) {
101
+ throw new index_js_2.DepositAmountMismatchError(params.amount, requirementSignature.action.args.amount);
102
+ }
103
+ if (requirementSignature.action.args.deadline !==
104
+ requirementSignature.args.deadline) {
105
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
106
+ field: "deadline",
107
+ expected: String(requirementSignature.args.deadline),
108
+ actual: String(requirementSignature.action.args.deadline),
109
+ });
110
+ }
111
+ if (requirementSignature.action.type === "permit2TransferFrom") {
112
+ return {
113
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.permit2TransferFrom,
114
+ data: (0, viem_1.encodeAbiParameters)([
115
+ { type: "uint256", name: "nonce" },
116
+ { type: "uint256", name: "deadline" },
117
+ { type: "bytes", name: "signature" },
118
+ ], [
119
+ requirementSignature.args.nonce,
120
+ requirementSignature.args.deadline,
121
+ requirementSignature.args.signature,
122
+ ]),
123
+ };
124
+ }
125
+ if (requirementSignature.action.type !== "permit") {
126
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
127
+ field: "type",
128
+ expected: "permit or permit2TransferFrom",
129
+ actual: requirementSignature.action.type,
130
+ });
131
+ }
132
+ const serializedSignature = requirementSignature.args.signature;
133
+ let parsed;
134
+ try {
135
+ parsed =
136
+ (0, viem_1.size)(serializedSignature) === 64
137
+ ? (0, viem_1.compactSignatureToSignature)((0, viem_1.parseCompactSignature)(serializedSignature))
138
+ : (0, viem_1.parseSignature)(serializedSignature);
139
+ }
140
+ catch (cause) {
141
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
142
+ field: "signature",
143
+ expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
144
+ actual: serializedSignature,
145
+ cause,
146
+ });
147
+ }
148
+ const v = parsed.v ??
149
+ (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
150
+ if (v == null) {
151
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
152
+ field: "signature",
153
+ expected: "a signature containing v or yParity",
154
+ actual: serializedSignature,
155
+ });
156
+ }
157
+ return {
158
+ kind: BLUE_BUNDLES_V1_TOKEN_PERMIT_KIND.erc2612,
159
+ data: (0, viem_1.encodeAbiParameters)([
160
+ { type: "uint256", name: "deadline" },
161
+ { type: "uint8", name: "v" },
162
+ { type: "bytes32", name: "r" },
163
+ { type: "bytes32", name: "s" },
164
+ ], [requirementSignature.args.deadline, Number(v), parsed.r, parsed.s]),
165
+ };
166
+ };
167
+ exports.getBlueBundlesV1TokenPermit = getBlueBundlesV1TokenPermit;
168
+ /** @internal */
169
+ const getBlueBundlesV1SignedAuthorization = (params) => {
170
+ const { authorizationSignature } = params;
171
+ if (authorizationSignature == null)
172
+ return EMPTY_SIGNED_AUTHORIZATION;
173
+ const authorized = (0, morpho_ts_1.getChainAddress)(params.chainId, "bundles.blueBundlesV1");
174
+ if (!(0, viem_1.isAddressEqual)(authorizationSignature.args.owner, params.userAddress)) {
175
+ throw new index_js_2.DepositOwnerMismatchError(params.userAddress, authorizationSignature.args.owner);
176
+ }
177
+ if (!(0, viem_1.isAddressEqual)(authorizationSignature.args.authorized, authorized)) {
178
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
179
+ field: "authorized",
180
+ expected: authorized,
181
+ actual: authorizationSignature.args.authorized,
182
+ });
183
+ }
184
+ if (!(0, viem_1.isAddressEqual)(authorizationSignature.action.args.authorized, authorized)) {
185
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
186
+ field: "authorized",
187
+ expected: authorized,
188
+ actual: authorizationSignature.action.args.authorized,
189
+ });
190
+ }
191
+ if (!authorizationSignature.args.isAuthorized) {
192
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
193
+ field: "isAuthorized",
194
+ expected: "true",
195
+ actual: String(authorizationSignature.args.isAuthorized),
196
+ });
197
+ }
198
+ if (!authorizationSignature.action.args.isAuthorized) {
199
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
200
+ field: "isAuthorized",
201
+ expected: "true",
202
+ actual: String(authorizationSignature.action.args.isAuthorized),
203
+ });
204
+ }
205
+ if (authorizationSignature.action.args.deadline !==
206
+ authorizationSignature.args.deadline) {
207
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
208
+ field: "deadline",
209
+ expected: String(authorizationSignature.args.deadline),
210
+ actual: String(authorizationSignature.action.args.deadline),
211
+ });
212
+ }
213
+ const serializedSignature = authorizationSignature.args.signature;
214
+ let parsed;
215
+ try {
216
+ parsed =
217
+ (0, viem_1.size)(serializedSignature) === 64
218
+ ? (0, viem_1.compactSignatureToSignature)((0, viem_1.parseCompactSignature)(serializedSignature))
219
+ : (0, viem_1.parseSignature)(serializedSignature);
220
+ }
221
+ catch (cause) {
222
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
223
+ field: "signature",
224
+ expected: "a 64-byte compact or 65-byte serialized ECDSA signature",
225
+ actual: serializedSignature,
226
+ cause,
227
+ });
228
+ }
229
+ const v = parsed.v ??
230
+ (parsed.yParity == null ? undefined : BigInt(parsed.yParity + 27));
231
+ if (v == null) {
232
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
233
+ field: "signature",
234
+ expected: "a signature containing v or yParity",
235
+ actual: serializedSignature,
236
+ });
237
+ }
238
+ return {
239
+ signature: { v: Number(v), r: parsed.r, s: parsed.s },
240
+ nonce: authorizationSignature.args.nonce,
241
+ deadline: authorizationSignature.args.deadline,
242
+ };
243
+ };
244
+ exports.getBlueBundlesV1SignedAuthorization = getBlueBundlesV1SignedAuthorization;
245
+ /** @internal */
246
+ const getBlueBundlesV1PublicAllocations = (reallocations, targetMarketParams) => {
247
+ (0, validate_js_1.validateVaultV2BlueReallocations)(reallocations, targetMarketParams.id);
248
+ // Hoisted out of the map: idle sources all reference the same synthetic idle market, whose
249
+ // construction eagerly hashes the market id — computing it once per call instead of per entry.
250
+ const idleMarketParams = blue_sdk_1.MarketParams.idle(targetMarketParams.loanToken);
251
+ return reallocations.map((reallocation) => {
252
+ if (reallocation.from.type === "market" &&
253
+ !(0, viem_1.isAddressEqual)(reallocation.from.marketParams.loanToken, targetMarketParams.loanToken)) {
254
+ throw new index_js_2.ReallocationLoanTokenMismatchError(targetMarketParams.loanToken, reallocation.from.marketParams.loanToken);
255
+ }
256
+ return {
257
+ vault: reallocation.vault,
258
+ adapter: reallocation.to.adapter,
259
+ marketParams: targetMarketParams,
260
+ fromIdle: reallocation.from.type === "idle",
261
+ sourceAdapter: reallocation.from.type === "market"
262
+ ? reallocation.from.adapter
263
+ : viem_1.zeroAddress,
264
+ sourceMarketParams: reallocation.from.type === "market"
265
+ ? reallocation.from.marketParams
266
+ : idleMarketParams,
267
+ assets: reallocation.assets,
268
+ penalty: reallocation.penalty,
269
+ };
270
+ });
271
+ };
272
+ exports.getBlueBundlesV1PublicAllocations = getBlueBundlesV1PublicAllocations;
273
+ /** @internal */
274
+ const getBlueBundlesV1PenaltyAssets = (reallocations) => reallocations.reduce((total, reallocation) => total +
275
+ blue_sdk_1.VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
276
+ exports.getBlueBundlesV1PenaltyAssets = getBlueBundlesV1PenaltyAssets;
277
+ /** @internal */
278
+ const getBlueBundlesV1ReferralFeeAssets = (assets, referralFeePct) => referralFeePct === 0n
279
+ ? 0n
280
+ : blue_sdk_1.MathLib.mulDivDown(assets, referralFeePct, blue_sdk_1.MathLib.WAD - referralFeePct);
281
+ exports.getBlueBundlesV1ReferralFeeAssets = getBlueBundlesV1ReferralFeeAssets;
282
+ /** @internal */
283
+ const selectBlueBundlesV1RequirementSignatures = (signatures, accepts) => {
284
+ const { permit, permit2TransferFrom, authorization } = (0, index_js_2.selectRequirementSignatures)(signatures, {
285
+ permit: accepts.token,
286
+ permit2TransferFrom: accepts.token,
287
+ authorization: accepts.authorization,
288
+ });
289
+ if (permit?.action.type === "permit2") {
290
+ throw new index_js_2.BlueBundlesV1RequirementSignatureMismatchError({
291
+ field: "type",
292
+ expected: "permit or permit2TransferFrom",
293
+ actual: permit.action.type,
294
+ });
295
+ }
296
+ if (permit != null && permit2TransferFrom != null) {
297
+ throw new index_js_2.AmbiguousRequirementSignaturesError("permit", 2);
298
+ }
299
+ return {
300
+ token: permit ??
301
+ permit2TransferFrom,
302
+ authorization,
303
+ };
304
+ };
305
+ exports.selectBlueBundlesV1RequirementSignatures = selectBlueBundlesV1RequirementSignatures;
306
+ /** @internal */
307
+ const finalizeBlueBundlesV1Transaction = (params) => {
308
+ let transaction = {
309
+ to: (0, morpho_ts_1.getChainAddress)(params.common.chainId, "bundles.blueBundlesV1"),
310
+ value: params.value,
311
+ data: params.data,
312
+ };
313
+ if (params.common.metadata != null) {
314
+ transaction = (0, index_js_1.addTransactionMetadata)(transaction, params.common.metadata);
315
+ }
316
+ return (0, morpho_ts_1.deepFreeze)({ ...transaction, action: params.action });
317
+ };
318
+ exports.finalizeBlueBundlesV1Transaction = finalizeBlueBundlesV1Transaction;