@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,72 +1,67 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueWithdrawCollateral = void 0;
4
- const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
- const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
4
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
- const viem_1 = require("viem");
8
- const index_js_1 = require("../../helpers/index.js");
9
- const index_js_2 = require("../../types/index.js");
5
+ const repayWithdrawCollateral_js_1 = require("./repayWithdrawCollateral.js");
10
6
  /**
11
- * Prepares a withdraw-collateral transaction for a Morpho Blue market.
7
+ * Encodes a pure collateral withdrawal through BlueBundlesV1.
12
8
  *
13
- * Direct call to `Morpho.withdrawCollateral` — no bundler needed. Collateral flows out of Morpho,
14
- * so there is no inflation-attack surface requiring the bundler.
9
+ * Delegates to {@link blueRepayWithdrawCollateral} with a zero repay leg. BlueBundlesV1 enforces
10
+ * the supplied post-operation LTV, and no standalone Morpho or Bundler3 call is encoded.
15
11
  *
16
- * The caller (`msg.sender`) must be `onBehalf` or be authorized by them on Morpho.
17
- *
18
- * @param params.market.chainId - The chain the market lives on.
19
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
20
- * @param params.args.amount - Amount of collateral to withdraw.
21
- * @param params.args.onBehalf - Address whose Morpho position the collateral is withdrawn from.
22
- * @param params.args.receiver - Address that receives the withdrawn collateral.
23
- * @param params.metadata - Optional analytics metadata attached to the transaction.
24
- * @returns A deep-frozen `Transaction<BlueWithdrawCollateralAction>` with `to`, `value`,
25
- * `data`, and the typed `action` discriminator the simulation layer consumes.
26
- * @throws {NonPositiveInputError} when `amount <= 0n`.
12
+ * @param params - Collateral-withdrawal 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 collateral position is reduced.
16
+ * @param params.args.collateralAssets - Collateral assets withdrawn.
17
+ * @param params.args.maxLtv - Maximum post-operation LTV.
18
+ * @param params.args.deadline - Final call deadline in Unix seconds.
19
+ * @param params.args.referralFeePct - Optional WAD-scaled referral fee.
20
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
21
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
22
+ * @param params.metadata - Optional transaction metadata.
23
+ * @returns A deep-frozen `Readonly<Transaction<BlueWithdrawCollateralAction>>` whose calldata
24
+ * invokes the combined BlueBundlesV1 entrypoint with a zero repay leg.
25
+ * @throws {NegativeInputError} when collateral, LTV, or fee is negative.
26
+ * @throws {NonPositiveInputError} when collateral or deadline is not positive.
27
+ * @throws {InputExceedsMaxError} when the referral fee is at least WAD.
28
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
29
+ * @throws {DepositOwnerMismatchError} when the signed authorization owner differs from `userAddress`.
30
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when authorization cannot be bound safely.
31
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
32
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
27
33
  * @example
28
34
  * ```ts
35
+ * import { markets } from "@morpho-org/morpho-test";
29
36
  * import { blueWithdrawCollateral } from "@morpho-org/morpho-sdk";
37
+ * import { zeroAddress } from "viem";
38
+ * import { mainnet } from "viem/chains";
30
39
  *
31
40
  * const tx = blueWithdrawCollateral({
32
- * market: { chainId: 1, marketParams },
41
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
33
42
  * args: {
34
- * amount: 1_000_000_000_000_000_000n,
35
- * onBehalf: borrower,
36
- * receiver: borrower,
43
+ * userAddress: zeroAddress,
44
+ * collateralAssets: 1_000_000_000_000_000_000n,
45
+ * maxLtv: 850000000000000000n,
46
+ * deadline: 1_900_000_000n,
37
47
  * },
38
48
  * });
39
49
  * // tx satisfies Readonly<Transaction<BlueWithdrawCollateralAction>>
40
50
  * ```
41
51
  */
42
- const blueWithdrawCollateral = ({ market: { chainId, marketParams }, args: { amount, onBehalf, receiver }, metadata, }) => {
43
- if (amount <= 0n) {
44
- throw new index_js_2.NonPositiveInputError("amount", amount);
45
- }
46
- const { morpho } = (0, blue_sdk_1.getChainAddresses)(chainId);
47
- let tx = {
48
- to: morpho,
49
- data: (0, viem_1.encodeFunctionData)({
50
- abi: blue_sdk_viem_1.blueAbi,
51
- functionName: "withdrawCollateral",
52
- args: [marketParams, amount, onBehalf, receiver],
53
- }),
54
- value: 0n,
55
- };
56
- if (metadata) {
57
- tx = (0, index_js_1.addTransactionMetadata)(tx, metadata);
58
- }
59
- return (0, morpho_ts_1.deepFreeze)({
60
- ...tx,
61
- action: {
62
- type: "blueWithdrawCollateral",
63
- args: {
64
- market: marketParams.id,
65
- amount,
66
- onBehalf,
67
- receiver,
68
- },
52
+ const blueWithdrawCollateral = (params) => {
53
+ const transaction = (0, repayWithdrawCollateral_js_1.blueRepayWithdrawCollateral)({
54
+ ...params,
55
+ args: {
56
+ ...params.args,
57
+ repayAssets: 0n,
58
+ repayShares: 0n,
59
+ maxRepayAssets: 0n,
69
60
  },
70
61
  });
62
+ return (0, morpho_ts_1.deepFreeze)({
63
+ ...transaction,
64
+ action: { ...transaction.action, type: "blueWithdrawCollateral" },
65
+ });
71
66
  };
72
67
  exports.blueWithdrawCollateral = blueWithdrawCollateral;
@@ -1,4 +1,4 @@
1
- export type { BlueActions } from "../entities/blue/index.js";
1
+ export type { BlueActions, BlueTokenRequirementsParams, } from "../entities/blue/index.js";
2
2
  export type { MidnightActions } from "../entities/midnight/index.js";
3
3
  export type { VaultV1Actions } from "../entities/vaultV1/index.js";
4
4
  export type { VaultV2Actions } from "../entities/vaultV2/index.js";
@@ -2,48 +2,60 @@ import type { Client } from "viem";
2
2
  import { type Address } from "viem";
3
3
  import { type AuthorizationRequirementSignature, type BlueAuthorizationAction, type Requirement, type Transaction } from "../../../types/index.js";
4
4
  /**
5
- * Resolves whether `GeneralAdapter1` needs Blue authorization for the given user, and returns
5
+ * Resolves whether a supported operator needs Blue authorization for the given user, and returns
6
6
  * the requirement to satisfy it when it does.
7
7
  *
8
- * Reads `Morpho.isAuthorized(userAddress, generalAdapter1)` on the target chain. Required before
9
- * any bundled Blue path that operates on behalf of the user (`borrow`, `withdraw`,
10
- * `supplyCollateralBorrow`, `repayWithdrawCollateral`, `refinance`).
8
+ * Reads `Morpho.isAuthorized(userAddress, authorized)` on the target chain.
11
9
  *
12
10
  * - When `supportSignature` is falsy (default), returns the
13
- * `setAuthorization(generalAdapter1, true)` transaction the user submits before the bundle.
11
+ * `setAuthorization(authorized, true)` transaction the user submits before the operation.
14
12
  * - When `supportSignature` is `true`, reads the user's Morpho `nonce` and returns a signable
15
- * `Requirement`; the signed authorization is folded into the bundle via
16
- * `setAuthorizationWithSig`, removing the standalone transaction.
13
+ * `Requirement`. The selected route consumes the result: Bundler3 emits
14
+ * `setAuthorizationWithSig`, while BlueBundlesV1 embeds its signed-authorization struct.
17
15
  *
18
16
  * @param params.viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
19
- * @param params.chainId - Target chain id (used to resolve Morpho and `GeneralAdapter1`).
20
- * @param params.userAddress - The user that must authorize `GeneralAdapter1`.
17
+ * @param params.chainId - Target chain id used to resolve Morpho and the default GeneralAdapter1.
18
+ * @param params.userAddress - The user granting authorization.
19
+ * @param params.authorized - Operator to authorize. Defaults to GeneralAdapter1; direct Blue
20
+ * writes pass the registered BlueBundlesV1 deployment. Must be the chain's registered
21
+ * GeneralAdapter1 or BlueBundlesV1 operator.
22
+ * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
21
23
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
22
- * transaction so authorization can be bundled via `setAuthorizationWithSig`.
24
+ * transaction so the destination route can consume the signed authorization.
23
25
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
24
26
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
25
27
  * place.
26
28
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
29
+ * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
30
+ * GeneralAdapter1 nor its BlueBundlesV1 operator.
31
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
32
+ * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
27
33
  * @example
28
34
  * ```ts
29
- * import { createPublicClient, http } from "viem";
35
+ * import { createPublicClient, http, zeroAddress } from "viem";
30
36
  * import { mainnet } from "viem/chains";
31
37
  * import { getBlueAuthorizationRequirement } from "@morpho-org/morpho-sdk";
38
+ * import { getChainAddress } from "@morpho-org/morpho-ts";
32
39
  *
33
40
  * const client = createPublicClient({ chain: mainnet, transport: http() });
41
+ * const blueBundlesV1 = getChainAddress(mainnet.id, "bundles.blueBundlesV1");
34
42
  * const requirement = await getBlueAuthorizationRequirement({
35
43
  * viemClient: client,
36
- * chainId: 1,
37
- * userAddress: borrower,
44
+ * chainId: mainnet.id,
45
+ * userAddress: zeroAddress,
38
46
  * supportSignature: true,
47
+ * authorized: blueBundlesV1,
48
+ * deadline: 1_900_000_000n,
39
49
  * });
40
50
  * // requirement is null when already authorized, a Requirement when supportSignature is true,
41
51
  * // otherwise Readonly<Transaction<BlueAuthorizationAction>>
42
52
  * ```
43
53
  */
44
54
  export declare const getBlueAuthorizationRequirement: (params: {
45
- viemClient: Client;
46
- chainId: number;
47
- userAddress: Address;
48
- supportSignature?: boolean;
55
+ readonly viemClient: Client;
56
+ readonly chainId: number;
57
+ readonly userAddress: Address;
58
+ readonly supportSignature?: boolean;
59
+ readonly authorized?: Address;
60
+ readonly deadline?: bigint;
49
61
  }) => Promise<Readonly<Transaction<BlueAuthorizationAction>> | Requirement<AuthorizationRequirementSignature> | null>;
@@ -8,40 +8,50 @@ const viem_1 = require("viem");
8
8
  const index_js_1 = require("../../../types/index.js");
9
9
  const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSignatureAuthorization.js");
10
10
  /**
11
- * Resolves whether `GeneralAdapter1` needs Blue authorization for the given user, and returns
11
+ * Resolves whether a supported operator needs Blue authorization for the given user, and returns
12
12
  * the requirement to satisfy it when it does.
13
13
  *
14
- * Reads `Morpho.isAuthorized(userAddress, generalAdapter1)` on the target chain. Required before
15
- * any bundled Blue path that operates on behalf of the user (`borrow`, `withdraw`,
16
- * `supplyCollateralBorrow`, `repayWithdrawCollateral`, `refinance`).
14
+ * Reads `Morpho.isAuthorized(userAddress, authorized)` on the target chain.
17
15
  *
18
16
  * - When `supportSignature` is falsy (default), returns the
19
- * `setAuthorization(generalAdapter1, true)` transaction the user submits before the bundle.
17
+ * `setAuthorization(authorized, true)` transaction the user submits before the operation.
20
18
  * - When `supportSignature` is `true`, reads the user's Morpho `nonce` and returns a signable
21
- * `Requirement`; the signed authorization is folded into the bundle via
22
- * `setAuthorizationWithSig`, removing the standalone transaction.
19
+ * `Requirement`. The selected route consumes the result: Bundler3 emits
20
+ * `setAuthorizationWithSig`, while BlueBundlesV1 embeds its signed-authorization struct.
23
21
  *
24
22
  * @param params.viemClient - Connected viem `Client` whose `chain.id` matches `params.chainId`.
25
- * @param params.chainId - Target chain id (used to resolve Morpho and `GeneralAdapter1`).
26
- * @param params.userAddress - The user that must authorize `GeneralAdapter1`.
23
+ * @param params.chainId - Target chain id used to resolve Morpho and the default GeneralAdapter1.
24
+ * @param params.userAddress - The user granting authorization.
25
+ * @param params.authorized - Operator to authorize. Defaults to GeneralAdapter1; direct Blue
26
+ * writes pass the registered BlueBundlesV1 deployment. Must be the chain's registered
27
+ * GeneralAdapter1 or BlueBundlesV1 operator.
28
+ * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
27
29
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
28
- * transaction so authorization can be bundled via `setAuthorizationWithSig`.
30
+ * transaction so the destination route can consume the signed authorization.
29
31
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
30
32
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
31
33
  * place.
32
34
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
35
+ * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is neither the chain's
36
+ * GeneralAdapter1 nor its BlueBundlesV1 operator.
37
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
38
+ * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
33
39
  * @example
34
40
  * ```ts
35
- * import { createPublicClient, http } from "viem";
41
+ * import { createPublicClient, http, zeroAddress } from "viem";
36
42
  * import { mainnet } from "viem/chains";
37
43
  * import { getBlueAuthorizationRequirement } from "@morpho-org/morpho-sdk";
44
+ * import { getChainAddress } from "@morpho-org/morpho-ts";
38
45
  *
39
46
  * const client = createPublicClient({ chain: mainnet, transport: http() });
47
+ * const blueBundlesV1 = getChainAddress(mainnet.id, "bundles.blueBundlesV1");
40
48
  * const requirement = await getBlueAuthorizationRequirement({
41
49
  * viemClient: client,
42
- * chainId: 1,
43
- * userAddress: borrower,
50
+ * chainId: mainnet.id,
51
+ * userAddress: zeroAddress,
44
52
  * supportSignature: true,
53
+ * authorized: blueBundlesV1,
54
+ * deadline: 1_900_000_000n,
45
55
  * });
46
56
  * // requirement is null when already authorized, a Requirement when supportSignature is true,
47
57
  * // otherwise Readonly<Transaction<BlueAuthorizationAction>>
@@ -52,9 +62,39 @@ const getBlueAuthorizationRequirement = async (params) => {
52
62
  if (viemClient.chain?.id !== chainId) {
53
63
  throw new index_js_1.ChainIdMismatchError(viemClient.chain?.id, chainId);
54
64
  }
55
- const { morpho, bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
65
+ const { morpho, bundler3: { generalAdapter1 }, bundles, } = (0, blue_sdk_1.getChainAddresses)(chainId);
66
+ const authorized = params.authorized ?? generalAdapter1;
67
+ // The SDK only ever authorizes the chain's registered GeneralAdapter1 or BlueBundlesV1 operator;
68
+ // reject any other override so a misconfigured `authorized` cannot grant an arbitrary address
69
+ // control over the user's Morpho positions.
70
+ const supportedOperators = [generalAdapter1];
71
+ if (bundles?.blueBundlesV1 != null) {
72
+ supportedOperators.push(bundles.blueBundlesV1);
73
+ }
74
+ if (!supportedOperators.some((operator) => (0, viem_1.isAddressEqual)(operator, authorized))) {
75
+ throw new index_js_1.UnsupportedAuthorizationOperatorError(authorized, chainId);
76
+ }
56
77
  const pc = viemClient.extend(viem_1.publicActions);
57
78
  if (supportSignature) {
79
+ // The forwarded deadline is only consumed on the signable path; reject an invalid or expired
80
+ // one before the RPC reads so the caller never signs an authorization that cannot be encoded
81
+ // or would revert on-chain. An omitted deadline defaults downstream to two hours from now.
82
+ if (params.deadline != null) {
83
+ if (params.deadline <= 0n) {
84
+ throw new index_js_1.NonPositiveInputError("deadline", params.deadline);
85
+ }
86
+ if (params.deadline > viem_1.maxUint256) {
87
+ throw new index_js_1.InputExceedsMaxError({
88
+ field: "deadline",
89
+ value: params.deadline,
90
+ max: viem_1.maxUint256,
91
+ });
92
+ }
93
+ const timestamp = morpho_ts_1.Time.timestamp();
94
+ if (params.deadline <= timestamp) {
95
+ throw new index_js_1.ExpiredDeadlineError(params.deadline, timestamp);
96
+ }
97
+ }
58
98
  // The signable path needs the user's Morpho nonce; fetch it alongside the
59
99
  // authorization status so both reads share a round-trip (batched into a
60
100
  // single multicall when the client enables batching) instead of
@@ -64,7 +104,7 @@ const getBlueAuthorizationRequirement = async (params) => {
64
104
  address: morpho,
65
105
  abi: blue_sdk_viem_1.blueAbi,
66
106
  functionName: "isAuthorized",
67
- args: [userAddress, generalAdapter1],
107
+ args: [userAddress, authorized],
68
108
  }),
69
109
  pc.readContract({
70
110
  address: morpho,
@@ -77,16 +117,17 @@ const getBlueAuthorizationRequirement = async (params) => {
77
117
  return null;
78
118
  }
79
119
  return (0, encodeBlueSignatureAuthorization_js_1.encodeBlueSignatureAuthorization)(viemClient, {
80
- authorized: generalAdapter1,
120
+ authorized,
81
121
  chainId,
82
122
  nonce,
123
+ deadline: params.deadline,
83
124
  });
84
125
  }
85
126
  const isAuthorized = await pc.readContract({
86
127
  address: morpho,
87
128
  abi: blue_sdk_viem_1.blueAbi,
88
129
  functionName: "isAuthorized",
89
- args: [userAddress, generalAdapter1],
130
+ args: [userAddress, authorized],
90
131
  });
91
132
  if (isAuthorized) {
92
133
  return null;
@@ -96,13 +137,13 @@ const getBlueAuthorizationRequirement = async (params) => {
96
137
  data: (0, viem_1.encodeFunctionData)({
97
138
  abi: blue_sdk_viem_1.blueAbi,
98
139
  functionName: "setAuthorization",
99
- args: [generalAdapter1, true],
140
+ args: [authorized, true],
100
141
  }),
101
142
  value: 0n,
102
143
  action: {
103
144
  type: "blueAuthorization",
104
145
  args: {
105
- authorized: generalAdapter1,
146
+ authorized,
106
147
  isAuthorized: true,
107
148
  },
108
149
  },
@@ -0,0 +1,80 @@
1
+ import { type Address, type Client } from "viem";
2
+ import { type BlueBundlesV1TokenSignatureRequirement, type ERC20ApprovalAction, type Transaction } from "../../../types/index.js";
3
+ /** Parameters for {@link getBlueBundlesV1TokenRequirements}. */
4
+ export interface GetBlueBundlesV1TokenRequirementsParams {
5
+ /** ERC-20 token funded by the operation. */
6
+ readonly token: Address;
7
+ /** Exact amount BlueBundlesV1 will pull. */
8
+ readonly amount: bigint;
9
+ /** Classic approval amount; defaults to the exact pull amount. */
10
+ readonly approvalAmount?: bigint;
11
+ /** Account funding the operation. */
12
+ readonly owner: Address;
13
+ /** Target chain id. */
14
+ readonly chainId: number;
15
+ /** Final-call and signature deadline. */
16
+ readonly deadline: bigint;
17
+ /** Whether the caller can collect offchain token signatures. */
18
+ readonly supportSignature: boolean;
19
+ /** Whether token metadata reads may use deployless aggregation. */
20
+ readonly supportDeployless?: boolean;
21
+ /** Prefer ERC-2612 when the token exposes a compatible nonce. */
22
+ readonly useSimplePermit?: boolean;
23
+ /** Explicit unused Permit2 SignatureTransfer unordered nonce. */
24
+ readonly permit2Nonce?: bigint;
25
+ }
26
+ /**
27
+ * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
28
+ * BlueBundlesV1.
29
+ *
30
+ * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
31
+ * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names BlueBundlesV1
32
+ * as spender. Permit2 SignatureTransfer requires an explicit unused unordered nonce so concurrent
33
+ * requirements never silently sign the same owner-global nonce.
34
+ *
35
+ * @param viemClient - Connected viem client used for allowance and nonce reads.
36
+ * @param params - Token requirement parameters.
37
+ * @param params.token - ERC-20 token funded by the operation.
38
+ * @param params.amount - Exact amount BlueBundlesV1 will pull; zero returns no requirements.
39
+ * @param params.approvalAmount - Classic approval amount; defaults to `amount` and is ignored by signature paths.
40
+ * @param params.owner - Account funding the operation.
41
+ * @param params.chainId - Target chain id; must match the client chain.
42
+ * @param params.deadline - Final-call and signature deadline.
43
+ * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
44
+ * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
45
+ * @param params.useSimplePermit - Prefer ERC-2612 when its nonce probe succeeds.
46
+ * @param params.permit2Nonce - Explicit unused uint256 nonce required when Permit2 is selected.
47
+ * @returns Ordered deep-frozen approval transactions and/or signable token requirements.
48
+ * @throws {ChainIdMismatchError} when the connected client targets another chain.
49
+ * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
50
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
51
+ * @throws {ExpiredDeadlineError} when `deadline` is positive but not in the future.
52
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
53
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered for the chain.
54
+ * @throws {MissingPermit2TransferFromNonceError} when Permit2 is selected without a nonce.
55
+ * @throws {Permit2TransferFromNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
56
+ * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
57
+ * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount` is below `amount`.
58
+ * @throws {viem.BaseError} when a required allowance, Permit2 nonce-bitmap, or ERC-2612 metadata
59
+ * read fails. A failed ERC-2612 nonce probe alone falls back to Permit2 or classic approval.
60
+ * @example
61
+ * ```ts
62
+ * import { addressesRegistry } from "@morpho-org/blue-sdk";
63
+ * import { createPublicClient, http, zeroAddress } from "viem";
64
+ * import { mainnet } from "viem/chains";
65
+ * import { getBlueBundlesV1TokenRequirements } from "@morpho-org/morpho-sdk";
66
+ *
67
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
68
+ * const requirements = await getBlueBundlesV1TokenRequirements(client, {
69
+ * token: addressesRegistry[mainnet.id].usdc,
70
+ * amount: 1_000_000n,
71
+ * owner: zeroAddress,
72
+ * chainId: mainnet.id,
73
+ * deadline: 1_900_000_000n,
74
+ * supportSignature: true,
75
+ * permit2Nonce: 42n,
76
+ * });
77
+ * // requirements contains approvals and/or signable BlueBundlesV1 token requirements.
78
+ * ```
79
+ */
80
+ export declare const getBlueBundlesV1TokenRequirements: (viemClient: Client, params: GetBlueBundlesV1TokenRequirementsParams) => Promise<readonly (Readonly<Transaction<ERC20ApprovalAction>> | BlueBundlesV1TokenSignatureRequirement)[]>;
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getBlueBundlesV1TokenRequirements = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const viem_1 = require("viem");
8
+ const actions_1 = require("viem/actions");
9
+ const index_js_1 = require("../../../helpers/index.js");
10
+ const index_js_2 = require("../../../types/index.js");
11
+ const encodeErc20Permit_js_1 = require("../encode/encodeErc20Permit.js");
12
+ const encodeErc20Permit2TransferFrom_js_1 = require("../encode/encodeErc20Permit2TransferFrom.js");
13
+ const getRequirementsApproval_js_1 = require("../getRequirementsApproval.js");
14
+ /**
15
+ * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
16
+ * BlueBundlesV1.
17
+ *
18
+ * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
19
+ * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names BlueBundlesV1
20
+ * as spender. Permit2 SignatureTransfer requires an explicit unused unordered nonce so concurrent
21
+ * requirements never silently sign the same owner-global nonce.
22
+ *
23
+ * @param viemClient - Connected viem client used for allowance and nonce reads.
24
+ * @param params - Token requirement parameters.
25
+ * @param params.token - ERC-20 token funded by the operation.
26
+ * @param params.amount - Exact amount BlueBundlesV1 will pull; zero returns no requirements.
27
+ * @param params.approvalAmount - Classic approval amount; defaults to `amount` and is ignored by signature paths.
28
+ * @param params.owner - Account funding the operation.
29
+ * @param params.chainId - Target chain id; must match the client chain.
30
+ * @param params.deadline - Final-call and signature deadline.
31
+ * @param params.supportSignature - Whether ERC-2612 or Permit2 signatures may be requested.
32
+ * @param params.supportDeployless - Whether ERC-2612 metadata reads may use deployless calls.
33
+ * @param params.useSimplePermit - Prefer ERC-2612 when its nonce probe succeeds.
34
+ * @param params.permit2Nonce - Explicit unused uint256 nonce required when Permit2 is selected.
35
+ * @returns Ordered deep-frozen approval transactions and/or signable token requirements.
36
+ * @throws {ChainIdMismatchError} when the connected client targets another chain.
37
+ * @throws {NegativeInputError} when `amount` or `permit2Nonce` is negative.
38
+ * @throws {NonPositiveInputError} when `deadline` is not positive.
39
+ * @throws {ExpiredDeadlineError} when `deadline` is positive but not in the future.
40
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
41
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered for the chain.
42
+ * @throws {MissingPermit2TransferFromNonceError} when Permit2 is selected without a nonce.
43
+ * @throws {Permit2TransferFromNonceAlreadyUsedError} when `permit2Nonce` is already consumed.
44
+ * @throws {InputExceedsMaxError} when `amount`, `deadline`, or `permit2Nonce` exceeds uint256.
45
+ * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount` is below `amount`.
46
+ * @throws {viem.BaseError} when a required allowance, Permit2 nonce-bitmap, or ERC-2612 metadata
47
+ * read fails. A failed ERC-2612 nonce probe alone falls back to Permit2 or classic approval.
48
+ * @example
49
+ * ```ts
50
+ * import { addressesRegistry } from "@morpho-org/blue-sdk";
51
+ * import { createPublicClient, http, zeroAddress } from "viem";
52
+ * import { mainnet } from "viem/chains";
53
+ * import { getBlueBundlesV1TokenRequirements } from "@morpho-org/morpho-sdk";
54
+ *
55
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
56
+ * const requirements = await getBlueBundlesV1TokenRequirements(client, {
57
+ * token: addressesRegistry[mainnet.id].usdc,
58
+ * amount: 1_000_000n,
59
+ * owner: zeroAddress,
60
+ * chainId: mainnet.id,
61
+ * deadline: 1_900_000_000n,
62
+ * supportSignature: true,
63
+ * permit2Nonce: 42n,
64
+ * });
65
+ * // requirements contains approvals and/or signable BlueBundlesV1 token requirements.
66
+ * ```
67
+ */
68
+ const getBlueBundlesV1TokenRequirements = async (viemClient, params) => {
69
+ (0, index_js_1.validateChainId)(viemClient.chain?.id, params.chainId);
70
+ if (params.amount < 0n) {
71
+ throw new index_js_2.NegativeInputError("amount", params.amount);
72
+ }
73
+ // Reject oversized inputs before any RPC read so this resolver never asks the user to sign or
74
+ // submit an approval/permit that the eventual BlueBundlesV1 call (uint256 ABI) would reject.
75
+ if (params.amount > viem_1.maxUint256) {
76
+ throw new index_js_2.InputExceedsMaxError({
77
+ field: "amount",
78
+ value: params.amount,
79
+ max: viem_1.maxUint256,
80
+ });
81
+ }
82
+ if (params.deadline <= 0n) {
83
+ throw new index_js_2.NonPositiveInputError("deadline", params.deadline);
84
+ }
85
+ if (params.deadline > viem_1.maxUint256) {
86
+ throw new index_js_2.InputExceedsMaxError({
87
+ field: "deadline",
88
+ value: params.deadline,
89
+ max: viem_1.maxUint256,
90
+ });
91
+ }
92
+ // Reject an already-expired deadline before the RPC reads so a direct caller of this resolver
93
+ // never signs a permit for a supply the BlueBundlesV1 call would revert. The entity validates
94
+ // this too, but the exported resolver must guard its own callers.
95
+ const timestamp = morpho_ts_1.Time.timestamp();
96
+ if (params.deadline <= timestamp) {
97
+ throw new index_js_2.ExpiredDeadlineError(params.deadline, timestamp);
98
+ }
99
+ if (params.amount === 0n)
100
+ return [];
101
+ const blueBundlesV1 = (0, morpho_ts_1.getChainAddress)(params.chainId, "bundles.blueBundlesV1");
102
+ const { permit2, dai } = (0, blue_sdk_1.getChainAddresses)(params.chainId);
103
+ if (params.supportSignature) {
104
+ const isDai = (0, morpho_ts_1.isDefined)(dai) && (0, viem_1.isAddressEqual)(params.token, dai);
105
+ if (params.useSimplePermit && !isDai) {
106
+ const nonce = await (0, actions_1.readContract)(viemClient, {
107
+ abi: blue_sdk_viem_1.erc2612Abi,
108
+ address: params.token,
109
+ functionName: "nonces",
110
+ args: [params.owner],
111
+ }).catch(() => undefined);
112
+ if ((0, morpho_ts_1.isDefined)(nonce)) {
113
+ return [
114
+ await (0, encodeErc20Permit_js_1.encodeErc20Permit)(viemClient, {
115
+ token: params.token,
116
+ spender: blueBundlesV1,
117
+ amount: params.amount,
118
+ chainId: params.chainId,
119
+ nonce,
120
+ deadline: params.deadline,
121
+ supportDeployless: params.supportDeployless,
122
+ }),
123
+ ];
124
+ }
125
+ }
126
+ if (permit2 != null) {
127
+ if (params.permit2Nonce == null) {
128
+ throw new index_js_2.MissingPermit2TransferFromNonceError();
129
+ }
130
+ if (params.permit2Nonce < 0n) {
131
+ throw new index_js_2.NegativeInputError("permit2Nonce", params.permit2Nonce);
132
+ }
133
+ if (params.permit2Nonce > viem_1.maxUint256) {
134
+ throw new index_js_2.InputExceedsMaxError({
135
+ field: "permit2Nonce",
136
+ value: params.permit2Nonce,
137
+ max: viem_1.maxUint256,
138
+ });
139
+ }
140
+ const wordPosition = params.permit2Nonce >> 8n;
141
+ const bitPosition = params.permit2Nonce & 255n;
142
+ const [allowance, nonceBitmap] = await Promise.all([
143
+ (0, actions_1.readContract)(viemClient, {
144
+ abi: viem_1.erc20Abi,
145
+ address: params.token,
146
+ functionName: "allowance",
147
+ args: [params.owner, permit2],
148
+ }),
149
+ (0, actions_1.readContract)(viemClient, {
150
+ abi: blue_sdk_viem_1.permit2Abi,
151
+ address: permit2,
152
+ functionName: "nonceBitmap",
153
+ args: [params.owner, wordPosition],
154
+ }),
155
+ ]);
156
+ if ((nonceBitmap & (1n << bitPosition)) !== 0n) {
157
+ throw new index_js_2.Permit2TransferFromNonceAlreadyUsedError(params.owner, params.permit2Nonce);
158
+ }
159
+ return [
160
+ ...(0, getRequirementsApproval_js_1.getRequirementsApproval)({
161
+ address: params.token,
162
+ chainId: params.chainId,
163
+ args: {
164
+ spender: permit2,
165
+ spendAmount: params.amount,
166
+ approvalAmount: viem_1.maxUint256,
167
+ },
168
+ allowances: allowance,
169
+ }),
170
+ (0, encodeErc20Permit2TransferFrom_js_1.encodeErc20Permit2TransferFrom)({
171
+ token: params.token,
172
+ spender: blueBundlesV1,
173
+ amount: params.amount,
174
+ chainId: params.chainId,
175
+ nonce: params.permit2Nonce,
176
+ deadline: params.deadline,
177
+ }),
178
+ ];
179
+ }
180
+ }
181
+ const approvalAmount = params.approvalAmount ?? params.amount;
182
+ if (approvalAmount < params.amount) {
183
+ throw new index_js_2.ApprovalAmountLessThanSpendAmountError();
184
+ }
185
+ const allowance = await (0, actions_1.readContract)(viemClient, {
186
+ abi: viem_1.erc20Abi,
187
+ address: params.token,
188
+ functionName: "allowance",
189
+ args: [params.owner, blueBundlesV1],
190
+ });
191
+ return (0, getRequirementsApproval_js_1.getRequirementsApproval)({
192
+ address: params.token,
193
+ chainId: params.chainId,
194
+ args: {
195
+ spender: blueBundlesV1,
196
+ // The pull the operation actually performs is `amount`; `approvalAmount`
197
+ // is only the allowance to set when one is needed. Comparing the existing
198
+ // allowance against `amount` (not `approvalAmount`) avoids emitting a
199
+ // redundant approval — and a zero-reset on approve-only-once tokens like
200
+ // USDT — when the current allowance already covers the pull.
201
+ spendAmount: params.amount,
202
+ approvalAmount,
203
+ },
204
+ allowances: allowance,
205
+ });
206
+ };
207
+ exports.getBlueBundlesV1TokenRequirements = getBlueBundlesV1TokenRequirements;