@morpho-org/morpho-sdk 9.3.0 → 9.4.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 (40) hide show
  1. package/README.md +3 -1
  2. package/lib/cjs/abis.d.ts +2 -2
  3. package/lib/cjs/abis.js +4 -1
  4. package/lib/cjs/actions/blue/index.d.ts +1 -0
  5. package/lib/cjs/actions/blue/index.js +1 -0
  6. package/lib/cjs/actions/blue/withdrawBuyCallback.d.ts +60 -0
  7. package/lib/cjs/actions/blue/withdrawBuyCallback.js +79 -0
  8. package/lib/cjs/blue/abis.d.ts +1 -1
  9. package/lib/cjs/blue/abis.js +3 -1
  10. package/lib/cjs/entities/blue/blue.d.ts +81 -2
  11. package/lib/cjs/entities/blue/blue.js +85 -0
  12. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +5 -4
  13. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +15 -12
  14. package/lib/cjs/errors.d.ts +1 -1
  15. package/lib/cjs/errors.js +3 -1
  16. package/lib/cjs/midnight/abis.d.ts +1 -1
  17. package/lib/cjs/midnight/abis.js +2 -1
  18. package/lib/cjs/types/action.d.ts +15 -1
  19. package/lib/cjs/types/error.d.ts +34 -0
  20. package/lib/cjs/types/error.js +41 -1
  21. package/lib/esm/abis.d.ts +2 -2
  22. package/lib/esm/abis.js +2 -2
  23. package/lib/esm/actions/blue/index.d.ts +1 -0
  24. package/lib/esm/actions/blue/index.js +1 -0
  25. package/lib/esm/actions/blue/withdrawBuyCallback.d.ts +60 -0
  26. package/lib/esm/actions/blue/withdrawBuyCallback.js +75 -0
  27. package/lib/esm/blue/abis.d.ts +1 -1
  28. package/lib/esm/blue/abis.js +1 -1
  29. package/lib/esm/entities/blue/blue.d.ts +81 -2
  30. package/lib/esm/entities/blue/blue.js +87 -2
  31. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +5 -4
  32. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +15 -12
  33. package/lib/esm/errors.d.ts +1 -1
  34. package/lib/esm/errors.js +1 -1
  35. package/lib/esm/midnight/abis.d.ts +1 -1
  36. package/lib/esm/midnight/abis.js +1 -1
  37. package/lib/esm/types/action.d.ts +15 -1
  38. package/lib/esm/types/error.d.ts +34 -0
  39. package/lib/esm/types/error.js +35 -0
  40. package/package.json +5 -5
@@ -1475,6 +1475,40 @@ export declare class WithdrawSharesExceedSupplyError extends Error {
1475
1475
  market: string;
1476
1476
  });
1477
1477
  }
1478
+ /** Thrown when a Blue withdrawal finds no supply shares to withdraw for the position owner. */
1479
+ export declare class EmptyBlueSupplyPositionError extends Error {
1480
+ constructor(params: {
1481
+ market: string;
1482
+ user: string;
1483
+ });
1484
+ }
1485
+ /** Thrown when a Blue withdrawal needs more assets than the market's available liquidity. */
1486
+ export declare class InsufficientBlueLiquidityError extends Error {
1487
+ constructor(params: {
1488
+ market: string;
1489
+ assets: bigint;
1490
+ liquidity: bigint;
1491
+ });
1492
+ }
1493
+ /** Thrown when an address is not a BlueBuyCallback created by the chain's registered factory. */
1494
+ export declare class NotBlueBuyCallbackError extends Error {
1495
+ constructor(callback: string);
1496
+ }
1497
+ /** Thrown when a BlueBuyCallback's `OWNER()` is not the account withdrawing its Blue position. */
1498
+ export declare class BlueBuyCallbackOwnerMismatchError extends Error {
1499
+ constructor(params: {
1500
+ callback: string;
1501
+ owner: string;
1502
+ userAddress: string;
1503
+ });
1504
+ }
1505
+ /** Thrown when Morpho Blue does not authorize an account to withdraw a BlueBuyCallback's position. */
1506
+ export declare class BlueBuyCallbackUnauthorizedError extends Error {
1507
+ constructor(params: {
1508
+ callback: string;
1509
+ userAddress: string;
1510
+ });
1511
+ }
1478
1512
  /**
1479
1513
  * Thrown when a Vault V2 reallocation planner receives a withdraw `amount` greater
1480
1514
  * than the target market's current `totalSupplyAssets` — the post-withdraw
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DepositOwnerMismatchError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.UnsupportedMidnightAuthorizationTargetError = exports.UnsupportedErc20ApprovalSpenderError = exports.MissingClientPropertyError = exports.CryptoUnavailableError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.UnsupportedRequirementSignatureError = exports.UnexpectedRequirementSignatureError = exports.AmbiguousRequirementSignaturesError = exports.MaxRepayAssetsBelowRepayAssetsError = exports.ReallocationsRequireBorrowError = exports.UnsupportedAuthorizationOperatorError = exports.ReallocationLoanTokenMismatchError = exports.SameVaultMigrationError = exports.AmountAndSharesExclusiveError = exports.MixedBundlesFundingError = exports.MidnightReferralFeePctExceededError = exports.ReferralFeePctExceededError = exports.ReferralFeeRecipientMissingError = exports.NativeFundingAmountMismatchError = exports.NoUnusedPermit2NonceError = exports.Permit2SignatureTransferNonceAlreadyUsedError = exports.BundlesRequirementSignatureMismatchError = exports.BundlesPermitMismatchError = exports.VaultIsBlueFeeRecipientError = exports.VaultMorphoMismatchError = exports.InsufficientBlueBalanceForInKindRedeemError = exports.InKindRedeemCoverageError = exports.InKindRedeemZeroDeallocationError = exports.VaultV2ForceWithdrawFeeSharesExceedBurnError = exports.VaultV2ForceWithdrawSharePriceBelowFloorError = exports.VaultV2ForceWithdrawZeroSharePriceError = exports.VaultV2ForceWithdrawZeroWithdrawalError = exports.VaultV2ForceWithdrawCoverageError = exports.VaultV2UndecodableLiquidityDataError = exports.VaultV2UnsupportedLiquidityAdapterError = exports.VaultV2UnsupportedExitAdapterError = exports.AdapterNotPartOfVaultError = exports.VaultV2SingleAdapterRequiredError = exports.ExpiredDeadlineError = exports.EmptyMarketParamsListError = exports.InputExceedsMaxError = exports.NonPositiveInputError = exports.NegativeInputError = void 0;
4
4
  exports.MidnightOfferMarketAddressMismatchError = exports.MidnightOfferMarketChainMismatchError = exports.MidnightTakeDeadlineTooFarError = exports.MidnightContractReceiverError = exports.MidnightZeroOnBehalfError = exports.MidnightZeroReceiverError = exports.MidnightRepayExceedsDebtError = exports.MidnightContinuousFeeAboveMaxError = exports.MidnightTakeTargetUnreachableError = exports.MidnightTakeableOffersNotFillableError = exports.UnboundedMidnightTakeInputError = exports.MidnightOfferSellerReceiverMismatchError = exports.MidnightOfferContinuousFeeCapError = exports.MidnightOfferMakerMismatchError = exports.MidnightOfferReduceOnlyError = exports.MidnightOfferSideMismatchError = exports.EmptyMidnightTakeableOffersError = exports.DuplicateMidnightGroupCancellationError = exports.EmptyMidnightCollateralSuppliesError = exports.EmptyMidnightGroupCancellationsError = exports.ReallocationAdapterSupplySharesUnderflowError = exports.ReallocationAllocationUnderflowError = exports.UnknownReallocationAdapterError = exports.UnknownReallocationMarketPublicAllocatorConfigError = exports.UnknownReallocationActiveAdaptersError = exports.UnknownReallocationPublicAllocatorConfigError = exports.UnknownReallocationAllocationError = exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.MutuallyExclusiveRepayAmountsError = exports.InconsistentReallocationPenaltyError = exports.InvalidReallocationSourceTypeError = exports.InvalidReallocationAddressError = exports.InvalidVaultV2BlueReallocationShapeError = exports.ReallocationWithdrawalOnTargetMarketError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeAssetError = exports.VaultAddressMismatchError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.DepositSpenderMismatchError = void 0;
5
- exports.MidnightCalldataEncodingError = exports.MidnightZeroAccountError = exports.MissingContractCodeError = exports.MidnightOfferNotReduceOnlyError = exports.RefinanceTokenMismatchError = exports.RefinanceSameMarketError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.MidnightInvalidAccountAddressError = exports.InvalidMidnightHexInputError = exports.InsufficientMidnightWithdrawableLiquidityError = exports.MidnightRedeemExceedsCreditError = exports.NoMidnightCreditToRedeemError = exports.MidnightReplacementGroupCancelledError = exports.MidnightOfferRatifierMismatchError = exports.MidnightTakeableOfferZeroSellerReceiverError = exports.MidnightTakeableOfferMarketMismatchError = exports.MissingDeadSharesDataError = exports.InsufficientDeadSharesError = exports.ZeroBlueParkingSharesError = exports.EmptyBlueParkingMarketError = exports.MidnightOfferCallbackDataMismatchError = exports.MidnightOfferCallbackMismatchError = exports.MidnightOfferMarketLoanTokenMismatchError = exports.MidnightMarketAddressMismatchError = void 0;
5
+ exports.MidnightCalldataEncodingError = exports.MidnightZeroAccountError = exports.MissingContractCodeError = exports.MidnightOfferNotReduceOnlyError = exports.RefinanceTokenMismatchError = exports.RefinanceSameMarketError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.BlueBuyCallbackUnauthorizedError = exports.BlueBuyCallbackOwnerMismatchError = exports.NotBlueBuyCallbackError = exports.InsufficientBlueLiquidityError = exports.EmptyBlueSupplyPositionError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.MidnightInvalidAccountAddressError = exports.InvalidMidnightHexInputError = exports.InsufficientMidnightWithdrawableLiquidityError = exports.MidnightRedeemExceedsCreditError = exports.NoMidnightCreditToRedeemError = exports.MidnightReplacementGroupCancelledError = exports.MidnightOfferRatifierMismatchError = exports.MidnightTakeableOfferZeroSellerReceiverError = exports.MidnightTakeableOfferMarketMismatchError = exports.MissingDeadSharesDataError = exports.InsufficientDeadSharesError = exports.ZeroBlueParkingSharesError = exports.EmptyBlueParkingMarketError = exports.MidnightOfferCallbackDataMismatchError = exports.MidnightOfferCallbackMismatchError = exports.MidnightOfferMarketLoanTokenMismatchError = exports.MidnightMarketAddressMismatchError = void 0;
6
6
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
7
7
  const midnight_sdk_1 = require("@morpho-org/midnight-sdk");
8
8
  const constant_js_1 = require("../helpers/constant.js");
@@ -1896,6 +1896,46 @@ class WithdrawSharesExceedSupplyError extends Error {
1896
1896
  }
1897
1897
  }
1898
1898
  exports.WithdrawSharesExceedSupplyError = WithdrawSharesExceedSupplyError;
1899
+ /** Thrown when a Blue withdrawal finds no supply shares to withdraw for the position owner. */
1900
+ class EmptyBlueSupplyPositionError extends Error {
1901
+ constructor(params) {
1902
+ super(`Supply position of "${params.user}" is empty on market "${params.market}". Refresh the position data or skip the withdrawal.`);
1903
+ this.name = "EmptyBlueSupplyPositionError";
1904
+ }
1905
+ }
1906
+ exports.EmptyBlueSupplyPositionError = EmptyBlueSupplyPositionError;
1907
+ /** Thrown when a Blue withdrawal needs more assets than the market's available liquidity. */
1908
+ class InsufficientBlueLiquidityError extends Error {
1909
+ constructor(params) {
1910
+ super(`Blue liquidity is insufficient on market "${params.market}": assets "${params.assets}", liquidity "${params.liquidity}". Try again when liquidity returns.`);
1911
+ this.name = "InsufficientBlueLiquidityError";
1912
+ }
1913
+ }
1914
+ exports.InsufficientBlueLiquidityError = InsufficientBlueLiquidityError;
1915
+ /** Thrown when an address is not a BlueBuyCallback created by the chain's registered factory. */
1916
+ class NotBlueBuyCallbackError extends Error {
1917
+ constructor(callback) {
1918
+ super(`Address "${callback}" is not a BlueBuyCallback created by the registered factory. Pass a callback created by midnightBlueBuyCallbackFactory.`);
1919
+ this.name = "NotBlueBuyCallbackError";
1920
+ }
1921
+ }
1922
+ exports.NotBlueBuyCallbackError = NotBlueBuyCallbackError;
1923
+ /** Thrown when a BlueBuyCallback's `OWNER()` is not the account withdrawing its Blue position. */
1924
+ class BlueBuyCallbackOwnerMismatchError extends Error {
1925
+ constructor(params) {
1926
+ super(`BlueBuyCallback "${params.callback}" is owned by "${params.owner}", not "${params.userAddress}". Withdraw from the owner's account.`);
1927
+ this.name = "BlueBuyCallbackOwnerMismatchError";
1928
+ }
1929
+ }
1930
+ exports.BlueBuyCallbackOwnerMismatchError = BlueBuyCallbackOwnerMismatchError;
1931
+ /** Thrown when Morpho Blue does not authorize an account to withdraw a BlueBuyCallback's position. */
1932
+ class BlueBuyCallbackUnauthorizedError extends Error {
1933
+ constructor(params) {
1934
+ super(`"${params.userAddress}" is not authorized on Morpho Blue to withdraw for BlueBuyCallback "${params.callback}". Call setAuthorization on the callback from its owner, then retry.`);
1935
+ this.name = "BlueBuyCallbackUnauthorizedError";
1936
+ }
1937
+ }
1938
+ exports.BlueBuyCallbackUnauthorizedError = BlueBuyCallbackUnauthorizedError;
1899
1939
  /**
1900
1940
  * Thrown when a Vault V2 reallocation planner receives a withdraw `amount` greater
1901
1941
  * than the target market's current `totalSupplyAssets` — the post-withdraw
package/lib/esm/abis.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  export { marketParamsAbi as blueMarketParamsAbi } from "@morpho-org/blue-sdk";
2
- export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
2
+ export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  preLiquidationAbi as bluePreLiquidationAbi,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
6
6
  preLiquidationFactoryAbi as bluePreLiquidationFactoryAbi, vaultV2Abi, vaultV2BluePublicAllocatorAbi, vaultV2FactoryAbi, whitelistControllerAggregatorV2Abi, wrappedBackedTokenAbi, wstEthAbi, } from "@morpho-org/blue-sdk-viem";
7
- export { blueBuyCallbackFactoryAbi as midnightBlueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi as midnightEcrecoverAuthorizerAbi, ecrecoverRatifierAbi as midnightEcrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi as midnightPriceRatifierV1Abi, rateRatifierV1Abi as midnightRateRatifierV1Abi, setterRatifierAbi as midnightSetterRatifierAbi, } from "@morpho-org/midnight-sdk";
7
+ export { blueBuyCallbackAbi as midnightBlueBuyCallbackAbi, blueBuyCallbackFactoryAbi as midnightBlueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi as midnightEcrecoverAuthorizerAbi, ecrecoverRatifierAbi as midnightEcrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi as midnightPriceRatifierV1Abi, rateRatifierV1Abi as midnightRateRatifierV1Abi, setterRatifierAbi as midnightSetterRatifierAbi, } from "@morpho-org/midnight-sdk";
8
8
  /** ABI for the VaultExitBundlesV1 periphery contract. */
9
9
  export declare const vaultExitBundlesV1Abi: readonly [{
10
10
  readonly type: "constructor";
package/lib/esm/abis.js CHANGED
@@ -1,10 +1,10 @@
1
1
  export { marketParamsAbi as blueMarketParamsAbi } from "@morpho-org/blue-sdk";
2
- export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
2
+ export { adaptiveCurveIrmAbi as blueAdaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  preLiquidationAbi as bluePreLiquidationAbi,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
6
6
  preLiquidationFactoryAbi as bluePreLiquidationFactoryAbi, vaultV2Abi, vaultV2BluePublicAllocatorAbi, vaultV2FactoryAbi, whitelistControllerAggregatorV2Abi, wrappedBackedTokenAbi, wstEthAbi, } from "@morpho-org/blue-sdk-viem";
7
- export { blueBuyCallbackFactoryAbi as midnightBlueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi as midnightEcrecoverAuthorizerAbi, ecrecoverRatifierAbi as midnightEcrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi as midnightPriceRatifierV1Abi, rateRatifierV1Abi as midnightRateRatifierV1Abi, setterRatifierAbi as midnightSetterRatifierAbi, } from "@morpho-org/midnight-sdk";
7
+ export { blueBuyCallbackAbi as midnightBlueBuyCallbackAbi, blueBuyCallbackFactoryAbi as midnightBlueBuyCallbackFactoryAbi, ecrecoverAuthorizerAbi as midnightEcrecoverAuthorizerAbi, ecrecoverRatifierAbi as midnightEcrecoverRatifierAbi, midnightAbi, midnightBundlesV2Abi, midnightEventsAbi, priceRatifierV1Abi as midnightPriceRatifierV1Abi, rateRatifierV1Abi as midnightRateRatifierV1Abi, setterRatifierAbi as midnightSetterRatifierAbi, } from "@morpho-org/midnight-sdk";
8
8
  /** ABI for the VaultExitBundlesV1 periphery contract. */
9
9
  export const vaultExitBundlesV1Abi = [
10
10
  {
@@ -6,4 +6,5 @@ export * from "./supply.js";
6
6
  export * from "./supplyCollateral.js";
7
7
  export * from "./supplyCollateralBorrow.js";
8
8
  export * from "./withdraw.js";
9
+ export * from "./withdrawBuyCallback.js";
9
10
  export * from "./withdrawCollateral.js";
@@ -6,4 +6,5 @@ export * from "./supply.js";
6
6
  export * from "./supplyCollateral.js";
7
7
  export * from "./supplyCollateralBorrow.js";
8
8
  export * from "./withdraw.js";
9
+ export * from "./withdrawBuyCallback.js";
9
10
  export * from "./withdrawCollateral.js";
@@ -0,0 +1,60 @@
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
+ import { type BlueWithdrawBuyCallbackAction, type Metadata, type Transaction } from "../../types/index.js";
4
+ /** Parameters for {@link blueWithdrawBuyCallback}. */
5
+ export interface BlueWithdrawBuyCallbackParams {
6
+ /** Chain and scoped Morpho Blue market. */
7
+ readonly market: {
8
+ readonly chainId: number;
9
+ readonly marketParams: MarketParams;
10
+ };
11
+ /** Direct Morpho Blue withdrawal arguments. */
12
+ readonly args: {
13
+ /** BlueBuyCallback whose supply position is withdrawn. */
14
+ readonly callbackAddress: Address;
15
+ /** Callback owner, who sends the transaction and receives the loan assets. */
16
+ readonly userAddress: Address;
17
+ /** Supply shares burned. */
18
+ readonly shares: bigint;
19
+ };
20
+ /** Optional transaction metadata suffix. */
21
+ readonly metadata?: Metadata;
22
+ }
23
+ /**
24
+ * Encodes a direct Morpho Blue `withdraw` of a BlueBuyCallback's supply shares to its owner.
25
+ *
26
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, userAddress)` on Morpho Blue, not
27
+ * BlueBundlesV1: the callback authorizes its owner on Blue, so the owner withdraws on its behalf
28
+ * directly. Use `client.morpho.blue(...).withdrawBuyCallback(...)` to check the callback, its owner,
29
+ * the Blue authorization and the market liquidity first.
30
+ *
31
+ * @param params - Withdrawal encoding parameters.
32
+ * @param params.market.chainId - Chain containing Morpho Blue.
33
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
34
+ * @param params.args.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
35
+ * @param params.args.userAddress - Callback owner, sender and receiver of the loan assets.
36
+ * @param params.args.shares - Supply shares burned.
37
+ * @param params.metadata - Optional transaction metadata.
38
+ * @returns A deep-frozen `Readonly<Transaction<BlueWithdrawBuyCallbackAction>>` whose `to` address
39
+ * is Morpho Blue.
40
+ * @throws {MarketIdMismatchError} when `marketParams.id` does not hash from its tuple fields.
41
+ * @throws {NegativeInputError} when `shares` is negative.
42
+ * @throws {NonPositiveInputError} when `shares` is zero.
43
+ * @throws {InputExceedsMaxError} when `shares` exceeds `uint256`.
44
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
45
+ * @throws {UnknownAddressError} when Morpho Blue is not registered.
46
+ * @example
47
+ * ```ts
48
+ * import { markets } from "@morpho-org/morpho-test";
49
+ * import { blueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
50
+ * import { zeroAddress } from "viem";
51
+ * import { mainnet } from "viem/chains";
52
+ *
53
+ * const tx = blueWithdrawBuyCallback({
54
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
55
+ * args: { callbackAddress: zeroAddress, userAddress: zeroAddress, shares: 1_000_000n },
56
+ * });
57
+ * // tx satisfies Readonly<Transaction<BlueWithdrawBuyCallbackAction>>
58
+ * ```
59
+ */
60
+ export declare const blueWithdrawBuyCallback: (params: BlueWithdrawBuyCallbackParams) => Readonly<Transaction<BlueWithdrawBuyCallbackAction>>;
@@ -0,0 +1,75 @@
1
+ import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
2
+ import { encodeFunctionData } from "viem";
3
+ import { blueAbi } from "../../abis.js";
4
+ import { addTransactionMetadata } from "../../helpers/index.js";
5
+ import { validateMarketParamsId, validateUint256Field, } from "../../helpers/validate.js";
6
+ import { NonPositiveInputError, } from "../../types/index.js";
7
+ /**
8
+ * Encodes a direct Morpho Blue `withdraw` of a BlueBuyCallback's supply shares to its owner.
9
+ *
10
+ * The call is `withdraw(marketParams, 0, shares, callbackAddress, userAddress)` on Morpho Blue, not
11
+ * BlueBundlesV1: the callback authorizes its owner on Blue, so the owner withdraws on its behalf
12
+ * directly. Use `client.morpho.blue(...).withdrawBuyCallback(...)` to check the callback, its owner,
13
+ * the Blue authorization and the market liquidity first.
14
+ *
15
+ * @param params - Withdrawal encoding parameters.
16
+ * @param params.market.chainId - Chain containing Morpho Blue.
17
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
18
+ * @param params.args.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
19
+ * @param params.args.userAddress - Callback owner, sender and receiver of the loan assets.
20
+ * @param params.args.shares - Supply shares burned.
21
+ * @param params.metadata - Optional transaction metadata.
22
+ * @returns A deep-frozen `Readonly<Transaction<BlueWithdrawBuyCallbackAction>>` whose `to` address
23
+ * is Morpho Blue.
24
+ * @throws {MarketIdMismatchError} when `marketParams.id` does not hash from its tuple fields.
25
+ * @throws {NegativeInputError} when `shares` is negative.
26
+ * @throws {NonPositiveInputError} when `shares` is zero.
27
+ * @throws {InputExceedsMaxError} when `shares` exceeds `uint256`.
28
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
29
+ * @throws {UnknownAddressError} when Morpho Blue is not registered.
30
+ * @example
31
+ * ```ts
32
+ * import { markets } from "@morpho-org/morpho-test";
33
+ * import { blueWithdrawBuyCallback } from "@morpho-org/morpho-sdk";
34
+ * import { zeroAddress } from "viem";
35
+ * import { mainnet } from "viem/chains";
36
+ *
37
+ * const tx = blueWithdrawBuyCallback({
38
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
39
+ * args: { callbackAddress: zeroAddress, userAddress: zeroAddress, shares: 1_000_000n },
40
+ * });
41
+ * // tx satisfies Readonly<Transaction<BlueWithdrawBuyCallbackAction>>
42
+ * ```
43
+ */
44
+ export const blueWithdrawBuyCallback = (params) => {
45
+ const { chainId, marketParams } = params.market;
46
+ const { callbackAddress, userAddress, shares } = params.args;
47
+ validateMarketParamsId(marketParams);
48
+ validateUint256Field("shares", shares);
49
+ if (shares === 0n)
50
+ throw new NonPositiveInputError("shares", shares);
51
+ let tx = {
52
+ to: getChainAddress(chainId, "blue"),
53
+ value: 0n,
54
+ data: encodeFunctionData({
55
+ abi: blueAbi,
56
+ functionName: "withdraw",
57
+ args: [marketParams, 0n, shares, callbackAddress, userAddress],
58
+ }),
59
+ };
60
+ if (params.metadata) {
61
+ tx = addTransactionMetadata(tx, params.metadata);
62
+ }
63
+ return deepFreeze({
64
+ ...tx,
65
+ action: {
66
+ type: "blueWithdrawBuyCallback",
67
+ args: {
68
+ market: marketParams.id,
69
+ shares,
70
+ onBehalf: callbackAddress,
71
+ receiver: userAddress,
72
+ },
73
+ },
74
+ });
75
+ };
@@ -1,5 +1,5 @@
1
1
  export { marketParamsAbi } from "@morpho-org/blue-sdk";
2
- export { adaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
2
+ export { adaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  preLiquidationAbi,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
@@ -1,5 +1,5 @@
1
1
  export { marketParamsAbi } from "@morpho-org/blue-sdk";
2
- export { adaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
2
+ export { adaptiveCurveIrmAbi, blueAbi, blueOracleAbi, erc2612Abi, erc3643Abi, erc3643IdentityRegistryAbi, erc5267Abi, metaMorphoAbi, metaMorphoFactoryAbi, morphoMarketV1AdapterAbi, morphoMarketV1AdapterFactoryAbi, morphoMarketV1AdapterV2Abi, morphoMarketV1AdapterV2FactoryAbi, morphoVaultV1AdapterAbi, morphoVaultV1AdapterFactoryAbi, permissionedErc20WrapperAbi, permit2Abi,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  preLiquidationAbi,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
@@ -1,7 +1,7 @@
1
1
  import { type AccrualPosition, type Market, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
3
  import type { FetchParameters } from "../../types/data.js";
4
- import { type ActionOutput, type ActionRequirement, type AssetsOrSharesArgs, type BlueBorrowAction, type BlueRefinanceAction, type BlueRepayAction, type BlueRepayWithdrawCollateralAction, type BlueSupplyAction, type BlueSupplyCollateralAction, type BlueSupplyCollateralBorrowAction, type BlueWithdrawAction, type BlueWithdrawCollateralAction, type MorphoClientType, type RequirementSignature, type VaultV2BluePublicAllocatorOptions, type VaultV2BlueReallocation } from "../../types/index.js";
4
+ import { type ActionOutput, type ActionRequirement, type AssetsOrSharesArgs, type BlueBorrowAction, type BlueRefinanceAction, type BlueRepayAction, type BlueRepayWithdrawCollateralAction, type BlueSupplyAction, type BlueSupplyCollateralAction, type BlueSupplyCollateralBorrowAction, type BlueWithdrawAction, type BlueWithdrawBuyCallbackAction, type BlueWithdrawCollateralAction, type MorphoClientType, type RequirementSignature, type VaultV2BluePublicAllocatorOptions, type VaultV2BlueReallocation } from "../../types/index.js";
5
5
  import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
6
6
  type VaultV2BlueReallocationsParams = {
7
7
  readonly reallocationData: VaultV2BlueReallocationData;
@@ -23,7 +23,10 @@ export interface BlueTokenRequirementsParams {
23
23
  /** Explicit unused Permit2 SignatureTransfer unordered nonce; defaults to the lowest unused nonce. */
24
24
  readonly permit2Nonce?: bigint;
25
25
  }
26
- /** Action surface for Morpho Blue reads and writes; writes route through BlueBundlesV1. */
26
+ /**
27
+ * Action surface for Morpho Blue reads and writes; writes route through BlueBundlesV1, except
28
+ * `withdrawBuyCallback`, which calls Morpho Blue directly.
29
+ */
27
30
  export interface BlueActions {
28
31
  /**
29
32
  * Fetches the latest market data with accrued interest.
@@ -314,6 +317,76 @@ export interface BlueActions {
314
317
  readonly referralFeePct?: bigint;
315
318
  readonly referralFeeRecipient?: Address;
316
319
  } & AssetsOrSharesArgs) => ActionOutput<BlueWithdrawAction, readonly RequirementSignature[], undefined>;
320
+ /**
321
+ * Prepares a direct Morpho Blue withdrawal of a BlueBuyCallback's whole supply position to its
322
+ * owner.
323
+ *
324
+ * A BlueBuyCallback parks a maker's Midnight buy-offer funds as Blue supply owned by the
325
+ * callback. After the offer is cancelled or expires, its owner recovers them with
326
+ * `withdraw(marketParams, 0, supplyShares, callbackAddress, userAddress)` sent straight to Morpho
327
+ * Blue: BlueBundlesV1 cannot act for the callback. The callback's constructor authorizes its
328
+ * owner on Blue, so no requirement is returned.
329
+ *
330
+ * The handle checks the snapshot synchronously: it must be the callback's position on this
331
+ * market, hold supply shares, and the market's liquidity must cover their assets.
332
+ * `getRequirements()` then reads the chain and throws unless the registered
333
+ * `midnightBlueBuyCallbackFactory` created the callback, its `OWNER()` is `userAddress`, and Blue
334
+ * still authorizes `userAddress` for the callback. Await it before submitting the transaction.
335
+ *
336
+ * @param params.userAddress - Callback owner, who sends the transaction and receives the assets.
337
+ * @param params.callbackAddress - BlueBuyCallback whose supply position is withdrawn.
338
+ * @param params.positionData - Fresh snapshot of the callback's position on this market, for
339
+ * example from `getPositionData(callbackAddress)`. Every supply share in it is withdrawn.
340
+ * @returns Lazy owner and authorization checks with no requirements, and a synchronous
341
+ * deep-frozen transaction targeting Morpho Blue.
342
+ * @throws {ChainIdMismatchError} when the client targets another chain, or from
343
+ * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
344
+ * @throws {viem.InvalidAddressError} when `callbackAddress` is malformed.
345
+ * @throws {MissingAccrualPositionError} when no position snapshot is provided.
346
+ * @throws {MarketIdMismatchError} when `positionData` belongs to another market.
347
+ * @throws {AccrualPositionUserMismatchError} when `positionData` belongs to another account than
348
+ * `callbackAddress`.
349
+ * @throws {EmptyBlueSupplyPositionError} when the callback holds no supply shares.
350
+ * @throws {InsufficientBlueLiquidityError} when the position's assets exceed market liquidity.
351
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
352
+ * @throws {UnknownAddressError} when Morpho Blue or `midnightBlueBuyCallbackFactory` is not
353
+ * registered.
354
+ * @throws {MissingContractCodeError} from `getRequirements()` when Morpho Blue or the factory has
355
+ * no code at its registered address.
356
+ * @throws {NotBlueBuyCallbackError} from `getRequirements()` when the factory did not create
357
+ * `callbackAddress`.
358
+ * @throws {BlueBuyCallbackOwnerMismatchError} from `getRequirements()` when the callback's
359
+ * `OWNER()` is not `userAddress`.
360
+ * @throws {BlueBuyCallbackUnauthorizedError} from `getRequirements()` when Blue does not
361
+ * authorize `userAddress` for the callback.
362
+ * @throws {viem.BaseError} from `getRequirements()` when a read fails.
363
+ * @example
364
+ * ```ts
365
+ * import { markets } from "@morpho-org/morpho-test";
366
+ * import { createPublicClient, http, zeroAddress } from "viem";
367
+ * import { mainnet } from "viem/chains";
368
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
369
+ *
370
+ * const userAddress = zeroAddress;
371
+ * const callbackAddress = zeroAddress;
372
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
373
+ * .extend(morphoViemExtension());
374
+ * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id);
375
+ * const action = market.withdrawBuyCallback({
376
+ * userAddress,
377
+ * callbackAddress,
378
+ * positionData: await market.getPositionData(callbackAddress),
379
+ * });
380
+ * await action.getRequirements(); // throws unless userAddress owns the callback
381
+ * const tx = action.buildTx();
382
+ * // tx satisfies Readonly<Transaction<BlueWithdrawBuyCallbackAction>>
383
+ * ```
384
+ */
385
+ withdrawBuyCallback: (params: {
386
+ readonly userAddress: Address;
387
+ readonly callbackAddress: Address;
388
+ readonly positionData: AccrualPosition;
389
+ }) => ActionOutput<BlueWithdrawBuyCallbackAction, undefined, undefined>;
317
390
  /**
318
391
  * Prepares a direct BlueBundlesV1 loan-asset borrow.
319
392
  *
@@ -1022,6 +1095,12 @@ export declare class MorphoBlue implements BlueActions {
1022
1095
  getRequirements: () => Promise<readonly ActionRequirement[]>;
1023
1096
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<import("../../types/action.js").Transaction<BlueWithdrawAction>>;
1024
1097
  };
1098
+ /** {@inheritDoc BlueActions.withdrawBuyCallback} */
1099
+ withdrawBuyCallback(params: {
1100
+ readonly userAddress: Address;
1101
+ readonly callbackAddress: Address;
1102
+ readonly positionData: AccrualPosition;
1103
+ }): ActionOutput<BlueWithdrawBuyCallbackAction, undefined, undefined>;
1025
1104
  /** {@inheritDoc BlueActions.supplyCollateral} */
1026
1105
  supplyCollateral(params: {
1027
1106
  readonly userAddress: Address;
@@ -3,12 +3,13 @@ import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchVaultV2Blu
3
3
  import { getChainAddress, getChainAddresses, Time, } from "@morpho-org/morpho-ts";
4
4
  import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { readContract } from "viem/actions";
6
+ import { blueAbi, midnightBlueBuyCallbackAbi, midnightBlueBuyCallbackFactoryAbi, } from "../../abis.js";
6
7
  import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, selectBlueBundlesV1RequirementSignatures, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
7
- import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
8
+ import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawBuyCallback, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
8
9
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
10
  import { DEFAULT_LLTV_BUFFER, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
10
11
  import { validateMarketParamsId } from "../../helpers/validate.js";
11
- import { ExpiredDeadlineError, InputExceedsMaxError, MarketIdMismatchError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
12
+ import { BlueBuyCallbackOwnerMismatchError, BlueBuyCallbackUnauthorizedError, EmptyBlueSupplyPositionError, ExpiredDeadlineError, InputExceedsMaxError, InsufficientBlueLiquidityError, MarketIdMismatchError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, NotBlueBuyCallbackError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
12
13
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
13
14
  import { getBundlesTokenRequirements } from "../requirements/index.js";
14
15
  import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
@@ -263,6 +264,90 @@ export class MorphoBlue {
263
264
  },
264
265
  };
265
266
  }
267
+ /** {@inheritDoc BlueActions.withdrawBuyCallback} */
268
+ withdrawBuyCallback(params) {
269
+ const { userAddress, callbackAddress, positionData } = params;
270
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
271
+ if (positionData == null) {
272
+ throw new MissingAccrualPositionError(this.marketParams.id);
273
+ }
274
+ validateAccrualPosition({
275
+ positionData,
276
+ expectedMarketId: this.marketParams.id,
277
+ expectedUser: callbackAddress,
278
+ });
279
+ const shares = positionData.supplyShares;
280
+ if (shares === 0n) {
281
+ throw new EmptyBlueSupplyPositionError({
282
+ market: this.marketParams.id,
283
+ user: callbackAddress,
284
+ });
285
+ }
286
+ const assets = positionData.supplyAssets;
287
+ const liquidity = positionData.market.liquidity;
288
+ if (assets > liquidity) {
289
+ throw new InsufficientBlueLiquidityError({
290
+ market: this.marketParams.id,
291
+ assets,
292
+ liquidity,
293
+ });
294
+ }
295
+ const blue = getChainAddress(this.chainId, "blue");
296
+ const factory = getChainAddress(this.chainId, "midnightBlueBuyCallbackFactory");
297
+ const tx = blueWithdrawBuyCallback({
298
+ market: { chainId: this.chainId, marketParams: this.marketParams },
299
+ args: { callbackAddress, userAddress, shares },
300
+ metadata: this.client.options.metadata,
301
+ });
302
+ return {
303
+ getRequirements: async () => {
304
+ const viemClient = this.client.viemClient;
305
+ await validateClientChainId(viemClient, this.chainId);
306
+ await assertRegistryTargetsHaveCode(viemClient, this.chainId, [
307
+ { role: "blue", address: blue },
308
+ { role: "midnightBlueBuyCallbackFactory", address: factory },
309
+ ]);
310
+ // Check the factory first: OWNER() on an arbitrary address can revert or lie.
311
+ const isBlueBuyCallback = await readContract(viemClient, {
312
+ address: factory,
313
+ abi: midnightBlueBuyCallbackFactoryAbi,
314
+ functionName: "isBlueBuyCallback",
315
+ args: [callbackAddress],
316
+ });
317
+ if (!isBlueBuyCallback) {
318
+ throw new NotBlueBuyCallbackError(callbackAddress);
319
+ }
320
+ const [owner, isAuthorized] = await Promise.all([
321
+ readContract(viemClient, {
322
+ address: callbackAddress,
323
+ abi: midnightBlueBuyCallbackAbi,
324
+ functionName: "OWNER",
325
+ }),
326
+ readContract(viemClient, {
327
+ address: blue,
328
+ abi: blueAbi,
329
+ functionName: "isAuthorized",
330
+ args: [callbackAddress, userAddress],
331
+ }),
332
+ ]);
333
+ if (!isAddressEqual(owner, userAddress)) {
334
+ throw new BlueBuyCallbackOwnerMismatchError({
335
+ callback: callbackAddress,
336
+ owner,
337
+ userAddress,
338
+ });
339
+ }
340
+ if (!isAuthorized) {
341
+ throw new BlueBuyCallbackUnauthorizedError({
342
+ callback: callbackAddress,
343
+ userAddress,
344
+ });
345
+ }
346
+ return [];
347
+ },
348
+ buildTx: () => tx,
349
+ };
350
+ }
266
351
  /** {@inheritDoc BlueActions.supplyCollateral} */
267
352
  supplyCollateral(params) {
268
353
  const { userAddress, collateralAssets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
@@ -29,10 +29,11 @@ export interface GetBundlesTokenRequirementsParams {
29
29
  * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
30
30
  * a registered fixed bundles contract.
31
31
  *
32
- * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
33
- * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names the bundles contract
34
- * as spender. The resolver picks the lowest unused unordered nonce by default; concurrent flows for
35
- * the same owner should pass explicit nonces.
32
+ * Returns no requirements when the direct bundles allowance covers the amount, even when
33
+ * signatures are supported. Otherwise reads only the state required by the selected path.
34
+ * Permit2 keeps the ERC-20 allowance on canonical Permit2 while the one-time signed transfer
35
+ * names the bundles contract as spender. The resolver picks the lowest unused unordered nonce
36
+ * by default; concurrent flows for the same owner should pass explicit nonces.
36
37
  *
37
38
  * @param viemClient - Connected viem client used for allowance and nonce reads.
38
39
  * @param params - Token requirement parameters.
@@ -13,10 +13,11 @@ import { getUnusedPermit2Nonce } from "./getUnusedPermit2Nonce.js";
13
13
  * Resolves direct approval, ERC-2612, or Permit2 SignatureTransfer prerequisites for
14
14
  * a registered fixed bundles contract.
15
15
  *
16
- * Reads only the allowance and nonce state required by the selected path. Permit2 keeps the
17
- * ERC-20 allowance on canonical Permit2 while the one-time signed transfer names the bundles contract
18
- * as spender. The resolver picks the lowest unused unordered nonce by default; concurrent flows for
19
- * the same owner should pass explicit nonces.
16
+ * Returns no requirements when the direct bundles allowance covers the amount, even when
17
+ * signatures are supported. Otherwise reads only the state required by the selected path.
18
+ * Permit2 keeps the ERC-20 allowance on canonical Permit2 while the one-time signed transfer
19
+ * names the bundles contract as spender. The resolver picks the lowest unused unordered nonce
20
+ * by default; concurrent flows for the same owner should pass explicit nonces.
20
21
  *
21
22
  * @param viemClient - Connected viem client used for allowance and nonce reads.
22
23
  * @param params - Token requirement parameters.
@@ -119,6 +120,14 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
119
120
  if (params.amount === 0n)
120
121
  return [];
121
122
  await validateClientChainId(viemClient, params.chainId);
123
+ const allowance = await readContract(viemClient, {
124
+ abi: erc20Abi,
125
+ address: params.token,
126
+ functionName: "allowance",
127
+ args: [params.owner, params.spender],
128
+ });
129
+ if (allowance >= params.amount)
130
+ return [];
122
131
  const { permit2, dai } = getChainAddresses(params.chainId);
123
132
  if (params.supportSignature) {
124
133
  const isDai = isDefined(dai) && isAddressEqual(params.token, dai);
@@ -171,7 +180,7 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
171
180
  });
172
181
  }
173
182
  const wordPosition = permit2Nonce >> 8n;
174
- const [allowance, nonceBitmap] = await Promise.all([
183
+ const [permit2Allowance, nonceBitmap] = await Promise.all([
175
184
  readContract(viemClient, {
176
185
  abi: erc20Abi,
177
186
  address: params.token,
@@ -195,19 +204,13 @@ export const getBundlesTokenRequirements = async (viemClient, params) => {
195
204
  now: timestamp,
196
205
  state: {
197
206
  type: "permit2SignatureTransfer",
198
- permit2Allowance: allowance,
207
+ permit2Allowance,
199
208
  permit2Nonce,
200
209
  nonceBitmap,
201
210
  },
202
211
  });
203
212
  }
204
213
  }
205
- const allowance = await readContract(viemClient, {
206
- abi: erc20Abi,
207
- address: params.token,
208
- functionName: "allowance",
209
- args: [params.owner, params.spender],
210
- });
211
214
  return resolveBundlesTokenRequirements({
212
215
  token: params.token,
213
216
  spender: params.spender,
@@ -4,4 +4,4 @@ UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
5
  export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -3,4 +3,4 @@ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as I
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
4
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
5
  export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, RetriesExhaustedError, RetryStoppedError, } from "@morpho-org/morpho-ts";