import { AccrualPosition, type Market, type MarketParams } from "@morpho-org/blue-sdk"; import { type Address } from "viem"; import type { FetchParameters } from "../../types/data.js"; import { type AssetsOrSharesArgs, type BlueAuthorizationAction, type BlueBorrowAction, type BlueReallocationPlan, type BlueRefinanceAction, type BlueRepayAction, type BlueRepayWithdrawCollateralAction, type BlueSupplyAction, type BlueSupplyCollateralAction, type BlueSupplyCollateralBorrowAction, type BlueWithdrawAction, type BlueWithdrawCollateralAction, type DepositAmountArgs, type ERC20ApprovalAction, type MorphoClientType, type PermitRequirementSignature, type ReallocationComputeOptions, type RepayAmountArgs, type Requirement, type RequirementSignature, type Transaction, type VaultV1Reallocation, type VaultV2BluePublicAllocatorOptions, type VaultV2BlueReallocation } from "../../types/index.js"; import { VaultV1ReallocationData } from "../vaultV1ReallocationData.js"; import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js"; type VaultV1ReallocationsParams = { readonly reallocationData: VaultV1ReallocationData; readonly options?: ReallocationComputeOptions; } & ({ readonly operation: "borrow" | "withdraw"; readonly amount: bigint; readonly borrowAmount?: never; } | { /** @deprecated Pass `{ operation: "borrow", amount }` instead. */ readonly borrowAmount: bigint; readonly operation?: never; readonly amount?: never; }); type VaultV2BlueReallocationsParams = { readonly reallocationData: VaultV2BlueReallocationData; readonly options?: VaultV2BluePublicAllocatorOptions & { readonly operation?: { readonly type: "borrow" | "withdraw"; readonly amount: bigint; }; }; }; export interface BlueActions { /** * Fetches the latest market data with accrued interest. * * @param parameters - Optional fetch parameters (block number, state overrides). * @returns Market state including total supply/borrow assets and shares. */ getMarketData: (parameters?: FetchParameters) => Promise; /** * Fetches the user's position in this market with accrued interest. * * @param userAddress - The user whose position to fetch. * @param parameters - Optional fetch parameters (block number, state overrides). * @returns Accrual position with health metrics (maxBorrowAssets, ltv, isHealthy). */ getPositionData: (userAddress: Address, parameters?: FetchParameters) => Promise; /** * Prepares a supply-collateral transaction. * * Routed through bundler via GeneralAdapter1. * `getRequirements` returns ERC20 approval or permit for GeneralAdapter1. * When `nativeAmount` is provided, native token is wrapped; collateral must be wNative. * * @param params - Supply collateral parameters. * @returns Object with `buildTx` and `getRequirements`. */ supplyCollateral: (params: { userAddress: Address; } & DepositAmountArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: (params?: { /** * Prefer the ERC-2612 simple-permit path when the SDK detects support. * Leave unset or set to `false` to force the Permit2/classic approval fallback when * a token is known to be incompatible despite passing the SDK's shallow nonce probe. */ useSimplePermit?: boolean; }) => Promise<(Readonly> | Requirement)[]>; }; /** * Prepares a loan-asset supply transaction. * * Routed through bundler via GeneralAdapter1. Computes `maxSharePrice` from the supply state of * `marketData` forward-accrued to execution and `slippageTolerance` to protect against * share-price inflation. * `getRequirements` returns ERC20 approval or permit for `GeneralAdapter1` on the loan token. * When `nativeAmount` is provided, native token is wrapped; the loan token must be wNative. * * No Morpho authorization required (supplier is crediting, not withdrawing). * * @param params - Supply parameters. * @returns Object with `buildTx` and `getRequirements`. * @throws {UnsupportedBlueMarketIrmError} when positive debt requires an unsupported IRM projection. */ supply: (params: { userAddress: Address; marketData: Market; slippageTolerance?: bigint; } & DepositAmountArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: (params?: { /** * Prefer the ERC-2612 simple-permit path when the SDK detects support. * Leave unset or set to `false` to force the Permit2/classic approval fallback when * a token is known to be incompatible despite passing the SDK's shallow nonce probe. */ useSimplePermit?: boolean; }) => Promise<(Readonly> | Requirement)[]>; }; /** * Prepares a loan-asset withdraw transaction. * * Routed through bundler3 via `morphoWithdraw`. Supports two modes via {@link AssetsOrSharesArgs}: * - **By assets** (`{ assets }`): withdraws an exact asset amount. * - **By shares** (`{ shares }`): burns an exact share count (full close, immune to interest accrual). * * Computes `minSharePrice` from market supply state and `slippageTolerance`. * * When `reallocations` is provided, its homogeneous V1 or V2 actions are * prepended to move liquidity before withdrawing. V1 fees add * to the transaction value; V2 penalties are paid in the loan token. * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 * reallocations for new integrations. * * `getRequirements` returns the loan-token approval needed for V2 penalties * and `morpho.setAuthorization(generalAdapter1, true)` when GA1 is not yet * authorized on Morpho. * * **Stale `positionData` may cause unexpected supply share calculations.** * * @param params - Withdraw parameters including pre-fetched `positionData`. * @returns Object with `buildTx` and `getRequirements`. * @throws {BundlerErrors.UnexpectedAction} when a V2 plan is unsupported on the chain. * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD. * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties. * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed. * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator. * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape. * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries. */ withdraw: (params: { userAddress: Address; receiver?: Address; positionData: AccrualPosition; slippageTolerance?: bigint; /** Vault V1 inputs are deprecated for high-level Blue writes; prefer Vault V2. */ reallocations?: BlueReallocationPlan; } & AssetsOrSharesArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: () => Promise<(Readonly> | Readonly> | Requirement)[]>; }; /** * Prepares a borrow transaction. * * Routed through bundler3 via `morphoBorrow`. * Validates position health with LLTV buffer (0.5%) using the pre-fetched `positionData`. * Computes `minSharePrice` from market borrow state and `slippageTolerance`. * * When `reallocations` is provided, its homogeneous V1 or V2 actions are * prepended before borrowing. V1 fees add to the transaction * value; V2 penalties are paid in the loan token. * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 * reallocations for new integrations. * * `getRequirements` returns the loan-token approval needed for V2 penalties * and Morpho authorization for GeneralAdapter1 when needed. * * **Stale `positionData` may cause unexpected health.** * * @param params - Borrow parameters including pre-fetched `positionData` for health validation. * @returns Object with `buildTx` and `getRequirements`. * @throws {BundlerErrors.UnexpectedAction} when a V2 plan is unsupported on the chain. * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD. * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties. * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed. * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator. * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape. * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries. */ borrow: (params: { userAddress: Address; amount: bigint; positionData: AccrualPosition; slippageTolerance?: bigint; /** Vault V1 inputs are deprecated for high-level Blue writes; prefer Vault V2. */ reallocations?: BlueReallocationPlan; }) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: () => Promise<(Readonly> | Readonly> | Requirement)[]>; }; /** * Prepares a repay transaction. * * Routed through bundler3 via GeneralAdapter1. * Supports two modes via {@link RepayAmountArgs}: * - **By assets** (`{ amount }`): repays an exact asset amount (partial repay). * - **By shares** (`{ shares }`): repays exact shares (full repay, immune to interest accrual). * * Computes `maxSharePrice` from market borrow state and `slippageTolerance`. * * `getRequirements` returns ERC20 approval for loan token to GeneralAdapter1. * Does NOT require Morpho authorization (anyone can repay on behalf of anyone). * * **Shares mode:** `slippageTolerance` also caps `transferAmount`. * * @param params - Repay parameters including pre-fetched `positionData`. * @returns Object with `buildTx` and `getRequirements`. * @throws {UnsupportedBlueMarketIrmError} when positive debt requires an unsupported IRM projection. */ repay: (params: { userAddress: Address; positionData: AccrualPosition; slippageTolerance?: bigint; } & RepayAmountArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: (params?: { /** * Prefer the ERC-2612 simple-permit path when the SDK detects support. * Leave unset or set to `false` to force the Permit2/classic approval fallback when * a token is known to be incompatible despite passing the SDK's shallow nonce probe. */ useSimplePermit?: boolean; }) => Promise<(Readonly> | Requirement)[]>; }; /** * Prepares a withdraw-collateral transaction. * * Direct call to `morpho.withdrawCollateral()` — no bundler, no GeneralAdapter1. * The caller (`msg.sender`) must be `onBehalf`. * Validates position health after withdrawal using the LLTV buffer. * * No `getRequirements` — no ERC20 approval or GeneralAdapter1 authorization needed * (collateral flows out of Morpho, not in). * * **No on-chain slippage guard — stale `positionData` risks liquidation.** * * @param params - Withdraw collateral parameters including pre-fetched `positionData` for health validation. * @returns Object with `buildTx`. */ withdrawCollateral: (params: { userAddress: Address; amount: bigint; positionData: AccrualPosition; }) => { buildTx: () => Readonly>; }; /** * Prepares an atomic repay-and-withdraw-collateral transaction. * * Routed through bundler3. Bundle order: repay FIRST, then withdraw. * Validates combined position health: simulates the repay, then checks * that the resulting position can sustain the collateral withdrawal. * * `getRequirements` returns in parallel: * - ERC20 approval for loan token to GeneralAdapter1 (for the repay). * - `morpho.setAuthorization(generalAdapter1, true)` if not yet authorized (for the withdraw). * * **Stale `positionData` risks underestimated debt and unsafe withdrawal.** * * @param params - Combined parameters including pre-fetched `positionData`. * @returns Object with `buildTx` and `getRequirements`. * @throws {UnsupportedBlueMarketIrmError} when positive debt requires an unsupported IRM projection. */ repayWithdrawCollateral: (params: { userAddress: Address; withdrawAmount: bigint; positionData: AccrualPosition; slippageTolerance?: bigint; } & RepayAmountArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: (params?: { /** * Prefer the ERC-2612 simple-permit path when the SDK detects support. * Leave unset or set to `false` to force the Permit2/classic approval fallback when * a token is known to be incompatible despite passing the SDK's shallow nonce probe. */ useSimplePermit?: boolean; }) => Promise<(Readonly> | Readonly> | Requirement)[]>; }; /** * Prepares an atomic supply-collateral-and-borrow transaction. * * Routed through the bundler. Validates position health with LLTV buffer * to prevent instant liquidation on new positions near the LLTV threshold. * * When `reallocations` is provided, its homogeneous V1 or V2 actions run * between the collateral supply and `morphoBorrow`. V1 fees add * to the transaction value; V2 penalties are paid in the loan token. * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 * reallocations for new integrations. * * `getRequirements` returns in parallel: * - ERC20 approval or permit for collateral token (to GeneralAdapter1). * - Classic ERC20 approval for any V2 loan-token penalties. * - `morpho.setAuthorization(generalAdapter1, true)` if adapter is not yet authorized. * * **Stale `positionData` may cause unexpected health.** * * @param params - Combined parameters including pre-fetched `positionData` for health validation. * @returns Object with `buildTx` and `getRequirements`. * @throws {BundlerErrors.UnexpectedAction} when a V2 plan is unsupported on the chain. * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD. * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties. * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed. * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator. * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape. * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries. */ supplyCollateralBorrow: (params: { userAddress: Address; positionData: AccrualPosition; borrowAmount: bigint; slippageTolerance?: bigint; /** Vault V1 inputs are deprecated for high-level Blue writes; prefer Vault V2. */ reallocations?: BlueReallocationPlan; } & DepositAmountArgs) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: (params?: { /** * Prefer the ERC-2612 simple-permit path when the SDK detects support. * Leave unset or set to `false` to force the Permit2/classic approval fallback when * a token is known to be incompatible despite passing the SDK's shallow nonce probe. */ useSimplePermit?: boolean; }) => Promise<(Readonly> | Readonly> | Requirement)[]>; }; /** * Prepares an atomic refinance migrating this market's position to another Morpho Blue market * that shares the same loan and collateral tokens. See {@link blueRefinance} for the bundle. * * Validates ownership, token/id match, that amounts do not exceed the source position, and that * both the residual source and the aggregate target position stay within LLTV − buffer. Both * markets are forward-accrued to `now`; in shares mode the target borrow is overshot by * `slippageTolerance` and the callback sweeps the residual. * A homogeneous V1 or V2 target reallocation plan runs first; V1 fees add * to the transaction value and V2 penalties are paid * in the loan token. * Vault V1 inputs are deprecated for high-level Blue writes; use Vault V2 * reallocations for new integrations. * * `getRequirements` returns the loan-token approval needed for V2 penalties * and Morpho authorization for GeneralAdapter1 when needed. * * @param params.userAddress - Position owner on both markets. * @param params.positionData - Pre-fetched source-market accrual position. * @param params.target.marketParams - Target market params. * @param params.target.positionData - Pre-fetched target-market accrual position (zero-position if none). * @param params.collateralAmount - Amount of collateral to migrate from source to target. * @param params.borrowAssets - Loan assets to repay on source; exclusive with `borrowShares`. * @param params.borrowShares - Borrow shares to repay on source; exclusive with `borrowAssets`. * @param params.slippageTolerance - WAD slippage tolerance. Defaults to `DEFAULT_SLIPPAGE_TOLERANCE`. * @param params.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the * target market. Vault V1 inputs are deprecated; prefer Vault V2. * @returns Object with `buildTx` and `getRequirements`. * @throws {UnsupportedBlueMarketIrmError} when positive source or target debt requires an unsupported IRM projection. * @throws {BundlerErrors.UnexpectedAction} when a V2 plan is unsupported on the chain. * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD. * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties. * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed. * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator. * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape. * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries. */ refinance: (params: { userAddress: Address; positionData: AccrualPosition; target: { marketParams: MarketParams; positionData: AccrualPosition; }; collateralAmount: bigint; borrowAssets?: bigint; borrowShares?: bigint; slippageTolerance?: bigint; /** Vault V1 inputs are deprecated for high-level Blue writes; prefer Vault V2. */ targetReallocations?: BlueReallocationPlan; }) => { buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; getRequirements: () => Promise<(Readonly> | Readonly> | Requirement)[]>; }; /** * Fetches all on-chain data needed to construct a {@link VaultV1ReallocationData} * for computing vault reallocations via the public allocator. * * The target market is refetched internally at `block.number` so the * reallocation planner always sees a snapshot from the same block as the * source vaults. A caller-owned market would let stale or adversarial data * inject unnecessary `reallocateTo` actions (and their PublicAllocator * fees) into the resulting bundle. * * The returned reallocation data can be passed to {@link getVaultV1Reallocations} * to compute the `VaultV1Reallocation[]` array for `borrow()` or * `supplyCollateralBorrow()`. * * **Stale data reverts on-chain (fail-safe).** * * @param params.vaultAddresses - Addresses of MetaMorpho vaults that allocate to this market. * @param params.block - The block to fetch data at (number and timestamp). * @returns A VaultV1ReallocationData instance populated with all required data. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocationData}. */ getVaultV1ReallocationData: (params: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }) => Promise; /** * Fetches Vault V1 PublicAllocator state using the deprecated unversioned name. * * @param params.vaultAddresses - Addresses of MetaMorpho vaults that allocate to this market. * @param params.block.number - Block number used for every RPC read. * @param params.block.timestamp - Timestamp corresponding to the fetched block. * @returns A `VaultV1ReallocationData` snapshot populated from one block. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocationData}. */ getReallocationData: (params: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }) => Promise; /** * Fetches Vault V2 BluePublicAllocator state for this target market. * * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each * vault's BluePublicAllocator permissions and allocation caps at one block. * * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity. * @param params.block.number - Block number used for every RPC read. * @param params.block.timestamp - Timestamp corresponding to the fetched block. * @returns A `VaultV2BlueReallocationData` snapshot ready for {@link getVaultV2BlueReallocations}. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @throws {UnsupportedChainIdError} when the chain is absent from the address registry. * @throws {UnknownAddressError} when the chain has no BluePublicAllocator deployment. * @throws {UnknownBlueFactory} when the chain has no Vault V2 factory. * @throws {UnknownBlueOfFactory} when a requested address is not a Vault V2 from that factory. * @throws {UnsupportedBlueVaultV2AdapterError} when a vault contains an unsupported adapter. * @throws {viem.BaseError} when an RPC or contract read fails with no fallback left. */ getVaultV2BlueReallocationData: (params: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }) => Promise; /** * Computes Vault V1 PublicAllocator reallocations for this market. * * Uses the shared-liquidity algorithm to determine which vaults should reallocate liquidity to * this market via the PublicAllocator, based on the post-operation utilization target. * * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow", * amount }`) or `{ operation: "withdraw", amount }` for a loan-asset withdraw. * * @param params.reallocationData - The current on-chain state (from {@link getVaultV1ReallocationData}). * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`). * Defaults to `"borrow"` when `borrowAmount` is provided. * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization. * @param params.borrowAmount - {@deprecated} Equivalent to `{ operation: "borrow", amount }`. Use the * `operation` + `amount` form on new code. * @param params.options - Optional reallocation computation options * (timestamp, utilization targets, reallocatable vaults filter, etc.). * Pass the fetched block timestamp to compute reallocations at the same block. * @returns Array of vault reallocations ready to pass to `borrow()`, `supplyCollateralBorrow()`, * or `withdraw()`. Empty array if no reallocation is needed. * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market — preventing fee-bearing reallocations from being attached to a call that would still revert onchain. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds the target market supply. * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config. * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocations}. * @example * ```ts * const reallocations = market.getVaultV1Reallocations({ * reallocationData, * operation: "borrow", * amount: 1_000_000n, * }); * ``` */ getVaultV1Reallocations: (params: VaultV1ReallocationsParams) => readonly VaultV1Reallocation[]; /** * Computes Vault V1 PublicAllocator reallocations using the deprecated unversioned name. * * @param params.reallocationData - State returned by {@link getVaultV1ReallocationData}. * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`). * @param params.amount - The borrow or withdraw amount used to compute post-state utilization. * @param params.borrowAmount - Deprecated borrow amount alias. * @param params.options - Optional allocator and utilization options. * @returns Vault V1 reallocations ready for a Blue action. * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply. * @throws {MissingPublicAllocatorConfigError} when a selected vault lacks allocator state. * @throws {UnknownReallocationMarketError} when the target market is absent. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocations}. * @example * ```ts * const reallocations = market.getReallocations({ * reallocationData, * operation: "borrow", * amount: 1_000_000n, * }); * ``` */ getReallocations: (params: VaultV1ReallocationsParams) => readonly VaultV1Reallocation[]; /** * Computes Vault V2 BluePublicAllocator reallocations for this market. * * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}. * @param params.options - Optional allocator discovery controls and operation to support. * @returns Action-ready reallocations and their post-simulation state. * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {NegativeInputError} when a utilization or penalty limit is negative. * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD. * @throws {NonPositiveInputError} when an enabled operation amount is not positive. * @throws {UnknownReallocationMarketError} when a required market is absent. * @throws {UnknownReallocationVaultError} when configured vault state is absent. * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent. * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent. * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent. * @throws {UnknownReallocationAllocationError} when required allocation state is absent. * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition. * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition. * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply. * @example * ```ts * const result = market.getVaultV2BlueReallocations({ * reallocationData, * options: { operation: { type: "borrow", amount: 1_000_000n } }, * }); * ``` */ getVaultV2BlueReallocations: (params: VaultV2BlueReallocationsParams) => { readonly reallocations: readonly VaultV2BlueReallocation[]; readonly data: VaultV2BlueReallocationData; }; } export declare class MorphoBlue implements BlueActions { private readonly client; readonly marketParams: MarketParams; private readonly chainId; constructor(client: MorphoClientType, marketParams: MarketParams, chainId: number); private getReallocationPenaltyRequirements; getMarketData(parameters?: FetchParameters): Promise; getPositionData(userAddress: Address, parameters?: FetchParameters): Promise; supply({ amount, userAddress, nativeAmount, marketData, slippageTolerance, }: { userAddress: Address; marketData: Market; slippageTolerance?: bigint; } & DepositAmountArgs): { getRequirements: (params?: { useSimplePermit?: boolean; }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly>)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; withdraw(params: { userAddress: Address; receiver?: Address; positionData: AccrualPosition; slippageTolerance?: bigint; reallocations?: BlueReallocationPlan; } & AssetsOrSharesArgs): { getRequirements: () => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly> | Readonly> | Requirement)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; supplyCollateral({ amount, userAddress, nativeAmount, }: { userAddress: Address; } & DepositAmountArgs): { getRequirements: (params?: { useSimplePermit?: boolean; }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly>)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; borrow({ amount, userAddress, positionData, slippageTolerance, reallocations, }: { amount: bigint; userAddress: Address; positionData: AccrualPosition; slippageTolerance?: bigint; reallocations?: BlueReallocationPlan; }): { getRequirements: () => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly> | Readonly> | Requirement)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; repay(params: { userAddress: Address; positionData: AccrualPosition; slippageTolerance?: bigint; } & RepayAmountArgs): { getRequirements: (reqParams?: { useSimplePermit?: boolean; }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly>)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; withdrawCollateral({ userAddress, amount, positionData, }: { userAddress: Address; amount: bigint; positionData: AccrualPosition; }): { buildTx: () => Readonly>; }; repayWithdrawCollateral(params: { userAddress: Address; withdrawAmount: bigint; positionData: AccrualPosition; slippageTolerance?: bigint; } & RepayAmountArgs): { getRequirements: (reqParams?: { useSimplePermit?: boolean; }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly> | Readonly> | Requirement)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; supplyCollateralBorrow({ amount, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance, reallocations, }: { userAddress: Address; positionData: AccrualPosition; borrowAmount: bigint; slippageTolerance?: bigint; reallocations?: BlueReallocationPlan; } & DepositAmountArgs): { getRequirements: (params?: { useSimplePermit?: boolean; }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly> | Readonly> | Requirement)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance, targetReallocations, }: { userAddress: Address; positionData: AccrualPosition; target: { marketParams: MarketParams; positionData: AccrualPosition; }; collateralAmount: bigint; borrowAssets?: bigint; borrowShares?: bigint; slippageTolerance?: bigint; targetReallocations?: BlueReallocationPlan; }): { getRequirements: () => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly> | Readonly> | Requirement)[]>; buildTx: (signatures?: readonly RequirementSignature[]) => Readonly>; }; /** * Fetches all on-chain inputs needed to compute public allocator reallocations. * * @param params.vaultAddresses - Vaults to inspect for source-market liquidity. * @param params.block.number - Block number used for every RPC read. * @param params.block.timestamp - Timestamp corresponding to the fetched block. * @returns Reallocation data ready for {@link getVaultV1Reallocations}. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocationData}. * @example * ```ts * import { markets, vaults } from "@morpho-org/morpho-test"; * import { createPublicClient, http } from "viem"; * import { mainnet } from "viem/chains"; * import { morphoViemExtension } from "@morpho-org/morpho-sdk"; * import type { VaultV1ReallocationData } from "@morpho-org/morpho-sdk/entities"; * * const client = createPublicClient({ chain: mainnet, transport: http() }) * .extend(morphoViemExtension()); * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id); * const block = await client.getBlock(); * const data: VaultV1ReallocationData = await market.getVaultV1ReallocationData({ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address], * block, * }); * ``` */ getVaultV1ReallocationData({ vaultAddresses, block, }: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }): Promise; /** * Fetches Vault V1 PublicAllocator state using the deprecated unversioned name. * * @param params.vaultAddresses - Addresses of MetaMorpho vaults that allocate to this market. * @param params.block.number - Block number used for every RPC read. * @param params.block.timestamp - Timestamp corresponding to the fetched block. * @returns A `VaultV1ReallocationData` snapshot populated from one block. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocationData}. * @example * ```ts * const data = await market.getReallocationData({ vaultAddresses, block }); * // Equivalent to market.getVaultV1ReallocationData({ vaultAddresses, block }). * ``` */ getReallocationData(params: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }): Promise; /** * Fetches Vault V2 BluePublicAllocator state for this target market. * * Reads the target Morpho Blue market, each Vault V2 accrual tree, and each * vault's BluePublicAllocator permissions and allocation caps at one block. * * @param params.vaultAddresses - Vault V2 addresses to inspect for market or idle liquidity. * @param params.block.number - Block number used for every RPC read. * @param params.block.timestamp - Timestamp corresponding to the fetched block. * @returns A `VaultV2BlueReallocationData` snapshot ready for {@link getVaultV2BlueReallocations}. * @throws {ChainIdMismatchError} when the client chain does not match this market. * @throws {UnsupportedChainIdError} when the chain is absent from the address registry. * @throws {UnknownAddressError} when the chain has no BluePublicAllocator deployment. * @throws {UnknownBlueFactory} when the chain has no Vault V2 factory. * @throws {UnknownBlueOfFactory} when a requested address is not a Vault V2 from that factory. * @throws {UnsupportedBlueVaultV2AdapterError} when a vault contains an unsupported adapter. * @throws {viem.BaseError} when an RPC or contract read fails with no fallback left. * @example * ```ts * import { markets } from "@morpho-org/morpho-test"; * import { createPublicClient, http } from "viem"; * import { mainnet } from "viem/chains"; * import { morphoViemExtension } from "@morpho-org/morpho-sdk"; * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities"; * * const client = createPublicClient({ chain: mainnet, transport: http() }) * .extend(morphoViemExtension()); * const market = client.morpho.blue(markets[mainnet.id].usdc_wbtc, mainnet.id); * const block = await client.getBlock(); * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145"; * const data: VaultV2BlueReallocationData = * await market.getVaultV2BlueReallocationData({ * vaultAddresses: [keyrockUsdcVaultV2], * block, * }); * ``` */ getVaultV2BlueReallocationData({ vaultAddresses, block, }: { vaultAddresses: readonly Address[]; block: { readonly number: bigint; readonly timestamp: bigint; }; }): Promise; /** * Computes Vault V1 PublicAllocator reallocations for this market. * * Pass `{ borrowAmount }` for a borrow (legacy alias, equivalent to `{ operation: "borrow", amount }`) * or `{ operation, amount }` for a borrow or loan-asset withdraw. * * @param params - Reallocation computation parameters. * @param params.reallocationData - State returned by {@link getVaultV1ReallocationData}. * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`). * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization. * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.} * @param params.options - Optional allocator and utilization options. * @returns Vault reallocations ready to pass to `borrow`, `supplyCollateralBorrow`, or `withdraw`. * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`. * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config. * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocations}. * @example * ```ts * const reallocations = market.getVaultV1Reallocations({ * reallocationData, * operation: "borrow", * amount: 1_000_000n, * }); * ``` */ getVaultV1Reallocations(params: VaultV1ReallocationsParams): readonly VaultV1Reallocation[]; /** * Computes Vault V1 PublicAllocator reallocations using the deprecated unversioned name. * * @param params.reallocationData - State returned by {@link getVaultV1ReallocationData}. * @param params.operation - The operation driving the reallocation (`"borrow"` or `"withdraw"`). * @param params.amount - The borrow or withdraw amount used to compute post-state utilization. * @param params.borrowAmount - Deprecated borrow amount alias. * @param params.options - Optional allocator and utilization options. * @returns Vault V1 reallocations ready for a Blue action. * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply. * @throws {MissingPublicAllocatorConfigError} when a selected vault lacks allocator state. * @throws {UnknownReallocationMarketError} when the target market is absent. * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use * {@link getVaultV2BlueReallocations}. * @example * ```ts * const reallocations = market.getReallocations({ * reallocationData, * operation: "borrow", * amount: 1_000_000n, * }); * ``` */ getReallocations(params: VaultV1ReallocationsParams): readonly VaultV1Reallocation[]; /** * Computes Vault V2 BluePublicAllocator reallocations for this market. * * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}. * @param params.options - Optional allocator discovery controls and operation to support. * @returns Action-ready reallocations and their post-simulation state. * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain. * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM. * @throws {NegativeInputError} when a utilization or penalty limit is negative. * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD. * @throws {NonPositiveInputError} when an enabled operation amount is not positive. * @throws {UnknownReallocationMarketError} when a required market is absent. * @throws {UnknownReallocationVaultError} when configured vault state is absent. * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent. * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent. * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent. * @throws {UnknownReallocationAllocationError} when required allocation state is absent. * @throws {ReallocationAdapterSupplySharesUnderflowError} when an inconsistent adapter snapshot underflows during the final transition. * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition. * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the shortfall. * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply. * @example * ```ts * const result = market.getVaultV2BlueReallocations({ * reallocationData, * options: { operation: { type: "borrow", amount: 1_000_000n } }, * }); * ``` */ getVaultV2BlueReallocations({ reallocationData, options, }: VaultV2BlueReallocationsParams): { readonly reallocations: readonly VaultV2BlueReallocation[]; readonly data: VaultV2BlueReallocationData; }; } export {};