import { SuiPriceServiceConnection, SuiPythClient } from "@pythnetwork/pyth-sui-js"; import { Network } from "../constants/index.js"; import { Transaction, TransactionObjectArgument, TransactionResult } from "@mysten/sui/transactions"; import { SupplyParams, WithdrawParams, BorrowParams, RepayParams, ClaimRewardsParams, ClaimAndSupplyOrRepayParams, LiquidateParams, MarketData, UserPortfolio, ProtocolStats, CoinMetadata, ZapInSupplyParams, ZapOutWithdrawParams, quoteObject, AlphalendClientOptions, SwapAndRepayParams, ClaimSwapAndSupplyOrRepayOrTransferParams, FlashRepayParams } from "./types.js"; import { Constants } from "../constants/types.js"; import { LendingProtocol } from "../models/lendingProtocol.js"; import { Blockchain } from "../models/blockchain.js"; import { Market } from "../models/market.js"; import { SevenKGateway } from "./sevenKSwap.js"; import { QuoteResponse } from "@7kprotocol/sdk-ts"; import { CetusSwap } from "./cetusSwap.js"; /** * AlphaLend Client * * The main entry point for interacting with the AlphaLend protocol: * - Provides methods for all protocol actions (supply, borrow, withdraw, repay, claimRewards, liquidate) * - Handles connection to the Sui blockchain and Pyth oracle * - Manages transaction building for protocol interactions * - Exposes query methods for protocol state, markets, and user positions * - Initializes and coordinates price feed updates * - Automatically fetches market data on first use (lazy loading) */ export declare class AlphalendClient { pythClient: SuiPythClient; pythConnection: SuiPriceServiceConnection; network: Network; constants: Constants; lendingProtocol: LendingProtocol; blockchain: Blockchain; sevenKGateway: SevenKGateway; cetusSwap: CetusSwap; private coinMetadataMap; private isInitialized; private initializationPromise; /** Resolved at runtime from DEEPBOOK_UPGRADE_CAP_ID; used for dbUSDC deposit move calls. */ private deepbookPackageId; /** Tracks whether resolveLatestDeepbookPackageId has been called, independent of isInitialized. */ private deepbookPackageIdResolved; /** In-flight promise for resolveLatestDeepbookPackageId — prevents duplicate concurrent RPC calls. */ private deepbookPackageIdPromise; /** * Creates a new AlphaLend client instance. * * The SDK connects to Sui via GraphQL. The only remaining JSON-RPC usage * is an internal, minimal `SuiClient` passed to `@pythnetwork/pyth-sui-js`'s * `SuiPythClient` constructor (that SDK has not yet migrated to GraphQL). * It is never exposed on the public surface. * * @param network One of the supported Sui networks. * @param graphqlUrl Optional GraphQL endpoint override. If omitted, a default * public endpoint for the given `network` is used. * @param options Optional prebuilt coin metadata map for offline testing. */ constructor(network: Network, graphqlUrl?: string, options?: AlphalendClientOptions); /** * Fetches the coin metadata map * * @returns Promise resolving to a Map object */ fetchCoinMetadataMap(): Promise>; /** * Updates price information for assets from Pyth oracle * * This method: * 1. Gathers price feed IDs for the specified coins * 2. Fetches the latest price data from Pyth oracle * 3. Adds price update instructions to the transaction * 4. Updates the protocol with new price information * * @param tx - Transaction object to add price update calls to * @param coinTypes - Array of fully qualified coin types (e.g., "0x2::sui::SUI") * @returns Transaction object with price update calls */ updatePrices(tx: Transaction, coinTypes: string[]): Promise; updateAllPrices(tx: Transaction, coinTypes: string[]): Promise; /** * Supplies token collateral to the AlphaLend protocol * * @param params Supply parameters * @param params.marketId Market ID where collateral is being added * @param params.amount Amount to supply as collateral in base units (bigint, in mists) * @param params.coinType Fully qualified coin type to supply (e.g., "0x2::sui::SUI") * @param params.positionCapId Optional: Object ID of the position capability object * @param params.address Address of the user supplying collateral * @returns Transaction object ready for signing and execution */ supply(params: SupplyParams): Promise; /** * True when the target market is dbUSDC (DEEPBOOK_STAKED). * Used to choose Deepbook deposit path instead of Cetus swap. */ private isDbUsdcMarket; /** * True when the user is paying with USDC. */ private isUsdcInput; /** * True when Deepbook config is set (mainnet). When false, we use Cetus path only. */ private hasDeepbookConfig; /** * True when we have static Deepbook IDs (for quote only). Does not require deepbookPackageId. * Use in getSwapQuote so SUI→dbUSDC quote works even before UpgradeCap is resolved. */ private hasDeepbookQuoteConfig; /** * True when the user is already paying with dbUSDC (same as market). * Then we only need to supply, no swap and no Deepbook deposit. */ private isDbUsdcInput; /** * Zap-in supply when the target market is dbUSDC. * - If user pays dbUSDC: direct supply (no swap, no Deepbook deposit). * - If user pays USDC: deposit USDC to Deepbook pool → get dbUSDC → supply. * - If user pays another token: Cetus swap to USDC → Deepbook deposit → supply. */ private zapInSupplyViaDeepbook; /** * Supplies collateral to the AlphaLend protocol with automatic token swapping * * This method performs a "zap in" operation by first swapping the input token * to the market's required collateral token via 7k Protocol, then supplying * the swapped tokens as collateral to the specified market. * * @param params Zap in supply parameters * @param params.marketId Market ID where collateral is being added * @param params.inputAmount Amount of input tokens to swap and supply (in base units) * @param params.inputCoinType Fully qualified type of the input token to swap from (e.g., "0x2::sui::SUI") * @param params.marketCoinType Fully qualified type of the market's collateral token to swap to * @param params.slippage Maximum allowed slippage percentage for the swap * @param params.positionCapId Optional: Object ID of the position capability object * @param params.address Address of the user performing the zap in supply * @returns Transaction object ready for signing and execution, or undefined if swap fails */ zapInSupply(params: ZapInSupplyParams): Promise; /** * Withdraws token collateral from the AlphaLend protocol * * @param params Withdraw parameters * @param params.marketId Market ID from which to withdraw * @param params.amount Amount to withdraw in base units (bigint, in mists, use MAX_U64 to withdraw all) * @param params.coinType Fully qualified coin type to withdraw (e.g., "0x2::sui::SUI") * @param params.positionCapId Object ID of the position capability object * @param params.address Address of the user withdrawing collateral * @param params.priceUpdateCoinTypes Array of coin types to update prices for * @returns Transaction object ready for signing and execution */ withdraw(params: WithdrawParams): Promise; /** * Gets a user's portfolio from a position capability ID * * @param positionCapId Position capability ID * @returns User portfolio, or undefined if position not found */ getUserPortfolioFromPositionCapId(positionCapId: string): Promise; /** * Withdraws collateral from the AlphaLend protocol with automatic token swapping * * This method performs a "zap out" operation by first withdrawing collateral * from the specified market, then swapping the withdrawn tokens to the desired * output token via 7k Protocol. * * @param params Zap out withdraw parameters * @param params.marketId Market ID from which collateral is being withdrawn * @param params.amount Amount to withdraw (in base units) * @param params.marketCoinType Fully qualified type of the market's collateral token to withdraw from * @param params.outputCoinType Fully qualified type of the desired output token to swap to (e.g., "0x2::sui::SUI") * @param params.slippage Maximum allowed slippage percentage for the swap * @param params.positionCapId Object ID of the position capability object * @param params.address Address of the user performing the zap out withdraw * @param params.priceUpdateCoinTypes Coin types of the coins whose price needs to be updated * @returns Transaction object ready for signing and execution, or undefined if swap fails */ zapOutWithdraw(params: ZapOutWithdrawParams): Promise; swapAndRepay(params: SwapAndRepayParams): Promise; /** * Borrows tokens from the AlphaLend protocol * * @param params Borrow parameters * @param params.marketId Market ID to borrow from * @param params.amount Amount to borrow in base units (bigint, in mists) * @param params.coinType Fully qualified coin type to borrow (e.g., "0x2::sui::SUI") * @param params.positionCapId Object ID of the position capability object * @param params.address Address of the user borrowing tokens * @param params.priceUpdateCoinTypes Array of coin types to update prices for * @returns Transaction object ready for signing and execution */ borrow(params: BorrowParams): Promise; /** * Repays borrowed tokens to the AlphaLend protocol * * @param params Repay parameters * @param params.marketId Market ID where debt exists * @param params.amount Amount to repay in base units (bigint, in mists) * @param params.coinType Fully qualified coin type to repay (e.g., "0x2::sui::SUI") * @param params.positionCapId Object ID of the position capability object * @param params.address Address of the user repaying the debt * @returns Transaction object ready for signing and execution */ repay(params: RepayParams): Promise; /** * Claims rewards from the AlphaLend protocol * * @param params ClaimRewards parameters * @param params.positionCapId Object ID of the position capability object * @param params.address Address of the user claiming rewards * @deprecated Use claimAndDepositAlpha instead * @param params.claimAlpha Whether to claim and deposit Alpha token rewards * @deprecated Use claimAndDepositAll instead * @param params.claimAll Whether to claim and deposit all other reward tokens * @param params.claimAndDepositAlpha Whether to claim and deposit Alpha token rewards * @param params.claimAndDepositAll Whether to claim and deposit all other reward tokens * @returns Transaction object ready for signing and execution */ claimRewards(params: ClaimRewardsParams): Promise; /** * Merges multiple coins of the same type into a single coin * * @param tx Transaction to add merge operation to * @param targetCoin Existing coin to merge into (or undefined) * @param coins Array of coins to merge * @returns Transaction argument representing the merged coin */ private mergeCoins; /** * Claims all available rewards, swaps them into a single `targetCoinType`, then: * - transfers the swapped coin to the wallet if `transferTargetCoin` is true, otherwise * - repays `targetMarketId` if `isTargetBorrowed` is true (and transfers any remainder), otherwise * - supplies the swapped coin as collateral to `targetMarketId`. * * On mainnet, optionally updates prices before repay/supply if `priceUpdateCoinTypes` is provided. * * @param params ClaimSwapAndSupplyOrRepayOrTransferParams - swap/repay/supply configuration * @returns Transaction ready for signing and execution, or undefined if nothing is claimable */ claimSwapAndSupplyOrRepayOrTransfer(params: ClaimSwapAndSupplyOrRepayOrTransferParams): Promise; /** * Claims all available rewards, then repays debts for reward coin types present in `borrowedCoins`. * Any remainder returned by `repay` is transferred to the wallet. * * Note: reward coin types that are not present in `borrowedCoins` are currently not processed. * * On mainnet, optionally updates prices first if `priceUpdateCoinTypes` is provided. * * @param params ClaimAndSupplyOrRepayParams - claim + repay configuration * @returns Transaction object ready for signing and execution */ claimAndSupplyOrRepay(params: ClaimAndSupplyOrRepayParams): Promise; /** * Liquidates an unhealthy position * * @param params Liquidate parameters - liquidatePositionId, borrowMarketId, withdrawMarketId, repayAmount, * borrowCoinType, withdrawCoinType, coinObjectId, priceUpdateCoinTypes * @returns Transaction object ready for signing and execution */ liquidate(params: LiquidateParams): Promise<(TransactionObjectArgument | undefined)[]>; /** * Breaks out of a leveraged looping position using a Navi flash loan. * Use like withdraw/repay: same client method + params pattern; returns Transaction for signing. * * @param params FlashRepayParams - flash repay parameters * @returns Transaction ready for signing and execution */ flashRepay(params: FlashRepayParams): Promise; /** * Creates a new position in the protocol * * @returns Transaction object for creating a new position */ createPosition(tx: Transaction): TransactionResult; /** * Gets statistics of the protocol * * @returns Promise resolving to a ProtocolStats object */ getProtocolStats(): Promise; /** * Gets statistics of the protocol with cached markets data * * @returns Promise resolving to a ProtocolStats object */ getProtocolStatsWithCachedMarkets(markets: Market[]): Promise; /** * Gets all markets data from the protocol * * @param options - Optional configuration for caching * @param options.useCache - Whether to use blockchain cache (default: false) * @param options.cacheTTL - Custom cache TTL in milliseconds (default: 60000) * @returns Promise resolving to an array of Market objects */ getAllMarkets(options?: { useCache?: boolean; cacheTTL?: number; }): Promise; /** * Gets market data of a particular market id from the protocol * * @returns Promise resolving to a MarketData object */ getMarketDataFromId(marketId: number): Promise; /** * Gets all markets data from the protocol with cached markets chain data * * @returns Promise resolving to an array of MarketData objects */ getAllMarketsWithCachedMarkets(markets: Market[]): Promise; /** * Gets all markets chain data to cache * * @returns Promise resolving to an array of Market objects */ getMarketsChain(): Promise; /** * Gets user portfolio data * * @param userAddress The user's address for which to fetch portfolio data * @returns Promise resolving to an array of UserPortfolio objects or undefined if not found */ getUserPortfolio(userAddress: string): Promise; /** * Gets portfolio data from position id with cached markets data * * @param positionId The position id for which to fetch portfolio data * @param markets The cached markets data to use for the portfolio * @returns Promise resolving to a UserPortfolio object or undefined if not found */ getUserPortfolioFromPositionWithCachedMarkets(positionId: string, markets: Market[]): Promise; /** * Gets user portfolio data with cached markets data * * @param userAddress The user's address for which to fetch portfolio data * @param markets The cached markets data to use for the portfolio * @returns Promise resolving to an array of UserPortfolio objects or undefined if not found */ getUserPortfolioWithCachedMarkets(userAddress: string, markets: Market[]): Promise; /** * Gets user portfolio data for a specific position * * @param positionId The position ID to get portfolio data for * @returns Promise resolving to a UserPortfolio object or undefined if not found */ getUserPortfolioFromPosition(positionId: string): Promise; /** * Gets a coin object suitable for a transaction. Upto 200 coins are merged together and returned. * * @param tx Transaction to which the coin will be added * @param type Fully qualified coin type to source * @param address Owner address whose balance/coins are spent (sets tx sender) * @param amount Exact coin amount in base units * @returns Transaction argument representing the exact-amount coin */ getCoinObject(tx: Transaction, type: string, address: string, amount: bigint): TransactionObjectArgument; /** * Credits a coin to `address`'s address balance (the accumulator) instead of * sending it as a standalone coin object. Used to return withdrawn/borrowed * coins and leftovers back to the user. * * @param tx Transaction to which the move call will be added * @param type Fully qualified coin type being returned * @param address Recipient whose address balance is credited * @param coin The coin to credit (consumed by the call) */ sendCoinToAddressBalance(tx: Transaction, type: string, address: string, coin: TransactionObjectArgument | string): void; private handlePromise; private depositAlphaTransaction; getEstimatedGasBudget(tx: Transaction, address: string): Promise; getSwapQuote(tokenIn: string, tokenOut: string, amountIn: string): Promise; getSwapTransactionBlock(tx: Transaction, address: string, slippage: number, quoteResponse: QuoteResponse, coinIn?: TransactionObjectArgument): Promise; /** * Ensures the client is fully initialized before any operation: * 1. Resolves the live deepbook package ID from the UpgradeCap (once, for dbUSDC operations). * 2. Fetches and caches coin metadata from the GraphQL API (once, for all other operations). * Both steps are skipped on subsequent calls — zero extra RPC after first initialization. */ private ensureInitialized; /** * Reads the alphalend_deepbook UpgradeCap from chain and sets deepbookPackageId * to whatever is currently live on-chain. * * Sui's upgrade mechanism updates the UpgradeCap's `package` field to the latest * published-at address on every upgrade. The UpgradeCap object ID never changes. */ private resolveLatestDeepbookPackageId; /** * Fetches coin metadata from the AlphaLend GraphQL API and caches it. */ private fetchAndCacheCoinMetadata; /** * Gets Pyth price feed ID for a coin type * Uses dynamic data fetched from GraphQL API */ private getPythPriceFeedId; /** * Gets price info object ID for a coin type * Uses dynamic data fetched from GraphQL API */ private getPythPriceInfoObjectId; /** * Gets decimal places for a coin type * Uses dynamic data fetched from GraphQL API */ private getDecimals; /** * Gets whether a coin type is pyth sponsored * Uses dynamic data fetched from GraphQL API */ private getPythSponsored; } //# sourceMappingURL=client.d.ts.map