UNPKG

@ferra-xyz/dlmm

Version:
1,567 lines (1,543 loc) 74.6 kB
import { SuiClient, SuiEventFilter, TransactionFilter, SuiTransactionBlockResponse, SuiObjectResponseQuery, SuiObjectDataOptions, SuiObjectResponse, DevInspectResults, CoinBalance, SuiObjectData, SuiObjectRef, OwnedObjectRef, SuiMoveObject, ObjectOwner, DisplayFieldsResponse, SuiParsedData } from '@mysten/sui/client'; import { TransactionResult, Transaction, TransactionArgument } from '@mysten/sui/transactions'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1'; import Decimal, { Decimal as Decimal$1 } from 'decimal.js'; import BN from 'bn.js'; interface IModule { readonly sdk: FerraDlmmSDK; } type Address = string; type U8 = string; type U16 = string; type U32 = string; type U64 = string; type U128 = string; type U256 = string; type ObjectId = string; type SuiAddress = string; type TypeName = string; interface Amounts { id: number; liquidity: bigint; amountX: bigint; amountY: bigint; } interface SwapEvent { sender: Address; to: Address; id: U32; amounts_in: Amounts; amounts_out: Amounts; volatility_accumulator: U32; total_fees: Amounts; protocol_fees: Amounts; } interface LBPair { id: ObjectId; tokenXType: string; tokenYType: string; binStep: U16; reserveX: U128; reserveY: U128; binManager: string; parameters: PairParameters; positionManager: string; version: string; rewarders: { coinType: string; emissions_per_second: string; }[]; } interface LbPairBinData { bin_id: bigint; reserve_x: bigint; reserve_y: bigint; price: bigint; total_supply: bigint; fee_x: bigint; fee_y: bigint; fee_growth_x: bigint; fee_growth_y: bigint; } interface LbPairOnChain { id: { id: string; }; is_pause: boolean; bin_step: number; parameters: { fields: { base_factor: number; filter_period: number; decay_period: number; reduction_factor: number; variable_fee_control: number; protocol_share: number; max_volatility_accumulator: number; volatility_accumulator: number; volatility_reference: number; id_reference: number; time_of_last_update: string; oracle_id: number; active_id: number; }; }; protocol_fee_x: string; protocol_fee_y: string; bin_manager: { fields: { bins: { fields: { id: { id: string; }; head: { fields: { is_none: boolean; v: string; }; }[]; tail: { fields: { is_none: boolean; v: string; }; }; level: string; max_level: string; list_p: string; size: string; random: { fields: { seed: string; }; }; }; }; }; }; oracle: { fields: { samples: { fields: { cumulative_id: string; cumulative_volatility: string; cumulative_bin_crossed: string; sample_lifetime: number; created_at: string; }; }[]; oracle_length: number; initialized: boolean; }; }; position_manager: { fields: { positions: { fields: { id: { id: string; }; size: string; }; }; }; }; balance_x: string; balance_y: string; reward_manager: { fields: { rewarders: { fields: { reward_coin: { fields: { name: string; }; }; emissions_per_second: string; }; }[]; }; }; reward_state: { fields: { reward_per_fee_cumulative: string[]; total_fees_ever: string; last_update_time: string; }; }; } interface Pairs { id: { id: string; }; index: string; list: { fields: { head: string; id: { id: string; }; size: string; tail: string; }; type: string; }; } interface PairInfo { id: { id: string; }; name: string; value: { fields: { next: string; prev: string; value: { fields: { bin_step: number; coin_type_a: { fields: { name: string; }; type: string; }; coin_type_b: { fields: { name: string; }; type: string; }; ignored_for_routing: boolean; pair_id: string; pair_key: string; }; type: string; }; }; type: string; }; } interface PairBin { reserve_x: string; reserve_y: string; } interface LBPosition { id: string; tokenXType: string; tokenYType: string; description: string; index: string; name: string; pair_id: string; url: string; version: string; } interface BinData { id: number; liquidity: bigint; } type PairParameters = { base_factor: U16; filter_period: U16; decay_period: U16; reduction_factor: U16; variable_fee_control: U32; protocol_share: U16; max_volatility_accumulator: U32; volatility_accumulator: U32; volatility_reference: U32; id_reference: U32; time_of_last_update: U64; oracle_id: U16; active_id: number; }; type AddLiquidityParams = { deltaIds: number[]; distributionX: bigint[]; distributionY: bigint[]; amountX: bigint; amountY: bigint; minAmountX?: bigint; minAmountY?: bigint; } & ({ positionId: string; } | { position: TransactionResult[number]; }); interface RemoveLiquidityParams { positionId: string; binIds: number[]; } interface ClosePositionParams { positionId: string; } interface AddLiquidityTxParams { amountX: TransactionResult[number] | ((tx: Transaction) => TransactionResult); amountY: TransactionResult[number] | ((tx: Transaction) => TransactionResult); deltaIds: number[]; distributionX: bigint[]; distributionY: bigint[]; minAmountX?: bigint; minAmountY?: bigint; position: TransactionResult[number] | { $kind: 'Input'; Input: number; type?: 'object'; }; } interface CollectPositionRewardsParams { pairId: string; positionId: string; typeX: string; typeY: string; rewardCoin: string; } interface CollectPositionFeesParams { pairId: string; positionId: string; typeX: string; typeY: string; binIds: number[]; } type CoinPairType = { coinTypeX: string; coinTypeY: string; }; type PrepareSwapParams = { amount: bigint; xtoy?: boolean; recipient?: string; minAmountOut?: bigint; }; type CalculateSwapParams = { amount: bigint; xtoy?: boolean; swapBins: LbPairBinData[]; }; type CalculateRatesResult = { /** * The estimated amount in token A. */ estimatedAmountIn: bigint; /** * The estimated amount in token B. */ estimatedAmountOut: bigint; /** * The estimated ending square root price. */ estimatedEndBinId: number; /** * The estimated fee amount. */ estimatedFeeAmount: bigint; /** * Indicates if the estimated amount exceeds the limit. */ isExceed: boolean; /** * The extra compute limit. */ extraComputeLimit: number; /** * Specifies if the swap is from token A to token B. */ xToY: boolean; /** * The amount to swap. */ amount: bigint; /** * The price impact percentage. */ priceImpactPct: number; }; type SwapParams = { pairId: string; xtoy: boolean; recipient: string; coinX: TransactionResult[number] | ((tx: Transaction) => TransactionResult); coinY: TransactionResult[number] | ((tx: Transaction) => TransactionResult); minAmountOut?: bigint; } & CoinPairType; interface BinReserves { reserve_x: bigint; reserve_y: bigint; fee_x: bigint; fee_y: bigint; total_supply: bigint; } interface Amount { amount_x: bigint; amount_y: bigint; } declare function createBinReserves(reserve_x: bigint, reserve_y: bigint, fee_x: bigint | undefined, fee_y: bigint | undefined, total_supply: bigint): BinReserves; /** * Get total amounts (reserves + fees) */ declare function getTotalAmounts(binReserves: BinReserves): [bigint, bigint]; declare function createAmounts(amount_x: bigint, amount_y: bigint): Amount; /** * Get amount out of bin when burning liquidity * Considers both reserves and fees proportionally * * @param binReserves - The bin reserves including fees * @param amountToBurn - The amount of liquidity to burn * @param totalSupply - The total supply of liquidity * @returns The amounts of tokens to receive */ declare function getAmountOutOfBin(binReserves: BinReserves | null, amountToBurn: bigint, totalSupply: bigint): Amount; declare function getBurnPercentage(amountToBurn: bigint, totalSupply: bigint): number; declare function getAmountsOutOfBins(binsReserves: BinReserves[], amountsToBurn: bigint[], totalSupplies: bigint[]): Amount[]; declare function aggregateAmounts(amountsArray: Amount[]): Amount; /** * Calculate amount X from liquidity, amount Y, and price * * Given: L = x * price + y * Solve for x: x = (L - y) / price * * @param liquidity - Total liquidity value * @param amountY - Amount of token Y * @param price - Price in u40.u88 fixed-point format * @returns Amount of token X */ declare function getAmountXFromLiquidity(liquidity: bigint, amountY: bigint, price: bigint): bigint; /** * Calculate amount Y from liquidity, amount X, and price * * Given: L = x * price + y * Solve for y: y = L - (x * price) * * @param liquidity - Total liquidity value * @param amountX - Amount of token X * @param price - Price in u40.u88 fixed-point format * @returns Amount of token Y */ declare function getAmountYFromLiquidity(liquidity: bigint, amountX: bigint, price: bigint): bigint; /** * Module for managing DLMM pairs * Handles fetching pair data, bins information, and preparing swap transactions */ declare class PairModule implements IModule { protected _sdk: FerraDlmmSDK; /** * Cache storage for pair data */ private readonly _cache; /** * Initialize the pair module with SDK instance * @param sdk - FerraDlmmSDK instance */ constructor(sdk: FerraDlmmSDK); /** * Get the SDK instance * @returns FerraDlmmSDK instance */ get sdk(): FerraDlmmSDK; /** * Fetch a liquidity pair by its address * @param pairAddress - The on-chain address of the pair * @returns Promise resolving to LBPair data or null if not found */ getPair(pairAddress: string): Promise<LBPair | null>; /** * Get bins data for a specific range in a pair * @param pair - The LBPair object * @param binRange - Tuple of [from, to] bin indices to fetch * @returns Promise resolving to array of PairBin data */ getPairBins(pair: LBPair, binRange: [from: number, to: number]): Promise<PairBin[]>; getPairs(): Promise<(LBPair | null)[]>; getPairReserves(pair: LBPair): Promise<(BinReserves & { id: number; })[]>; /** * Extract struct content fields from a Sui object response * @param object - SuiObjectResponse to parse * @returns Parsed fields or null if invalid */ private getStructContentFields; /** * Parse raw pair content from chain into LBPair format * @param typeTag - The type tag string of the pair object * @param contents - The parsed data content from chain * @param version - Version string of the pair * @returns Parsed LBPair or null if invalid */ private parsePairContent; /** * Prepare a swap transaction for a pair * @deprecated * @param pair - The LBPair to swap on * @param params - Swap parameters including amount, direction, recipient * @param tx - Optional existing transaction to add swap to * @returns Transaction object ready to be executed * @throws DlmmPairsError if sender address is invalid */ prepareSwap(pair: LBPair, params: PrepareSwapParams, tx?: Transaction): Promise<Transaction>; /** * Add liquidity to a pair and create a new position (open bucket) * * @param pair - The LBPair to add liquidity to * @param params - Liquidity parameters * @param params.amountX - Amount of token X to add * @param params.amountY - Amount of token Y to add * @param params.deltaIds - Array of relative bin IDs from active bin * @param params.distributionX - Distribution percentages for token X across bins * @param params.distributionY - Distribution percentages for token Y across bins * @param tx - Optional existing transaction to add operations to * @returns Transaction object with liquidity addition and position creation * * @example * ```typescript * const tx = await router.addOpenBucketLiquidity(pair, { * amountX: 1000000000n, // 1 token X * amountY: 2000000000n, // 2 token Y * deltaIds: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], * distributionX: [0, 0, 0, 0, 0, 50, 50, 0, 0, 0, 0], * distributionY: [0, 0, 0, 0, 0, 50, 50, 0, 0, 0, 0] * }); * ``` */ openPositionAndAddLiquidity(pair: LBPair, params: Omit<AddLiquidityParams, 'positionId'>, tx?: Transaction): Promise<Transaction>; openPosition(pair: LBPair, tx?: Transaction): Promise<Transaction>; /** * Add liquidity to an existing position * @param pair - The LBPair to add liquidity to * @param params - Liquidity parameters * @param params.positionId - ID of existing position to add liquidity to * @param params.amountX - Amount of token X to add * @param params.amountY - Amount of token Y to add * @param params.deltaIds - Array of relative bin IDs from active bin * @param params.distributionX - Distribution percentages for token X across bins * @param params.distributionY - Distribution percentages for token Y across bins * @param tx - Optional existing transaction to add operations to * @returns Transaction object with liquidity addition * * @example * ```typescript * const tx = await router.addLiquidity(pair, { * positionId: "0x123...", * amountX: 1000000000n, * amountY: 2000000000n, * deltaIds: [-2, -1, 0, 1, 2], * distributionX: [10, 20, 40, 20, 10], * distributionY: [10, 20, 40, 20, 10] * }); * ``` */ addLiquidity(pair: LBPair, params: AddLiquidityParams, tx?: Transaction): Promise<Transaction>; /** * Remove liquidity from a position * @param pair - The LBPair to remove liquidity from * @param params - Remove liquidity parameters * @param params.positionId - ID of position to remove liquidity from * @param params.binIds - Array of bin IDs to remove liquidity from * @param params.binAmounts - Array of amounts to remove from each bin * @param params.minAmountXOut - Minimum amount of token X to receive (slippage protection) * @param params.minAmountYOut - Minimum amount of token Y to receive (slippage protection) * @param tx - Optional existing transaction to add operations to * @returns Transaction object with liquidity removal * @throws DlmmPairsError if sender address is invalid * @throws Error if bin arrays are empty or mismatched * * @example * ```typescript * const tx = await router.removeLiquidity(pair, { * positionId: "0x123...", * binIds: [8388606, 8388607, 8388608], * binAmounts: [100000n, 200000n, 150000n], * minAmountXOut: 900000n, * minAmountYOut: 1800000n * }); * ``` */ removeLiquidity(pair: LBPair, params: RemoveLiquidityParams, tx?: Transaction): Promise<Transaction>; removeAndClosePosition(pair: LBPair, positionId: string, tx?: Transaction): Promise<Transaction>; getPairBinsData(pairId: string): Promise<LbPairBinData[]>; } declare class QuoterModule implements IModule { protected _sdk: FerraDlmmSDK; private readonly _cache; constructor(sdk: FerraDlmmSDK); get sdk(): FerraDlmmSDK; } declare const LB_FACTORY_CONSTANTS: { readonly MIN_BIN_STEP: "1"; readonly MAX_FLASH_LOAN_FEE: "100000000000000000"; }; interface CreateFactoryParams { owner: Address; flashLoanFee: U256; feeRecipient: Address; } interface CreateLBPairParams { tokenXType: string; tokenYType: string; activeId: number; binStep: number; initialBins?: number; } /** * Module for managing DLMM factory operations * Handles creation of new liquidity pairs */ declare class FactoryModule implements IModule { protected _sdk: FerraDlmmSDK; /** * Cache storage for factory data */ private readonly _cache; /** * Initialize the factory module with SDK instance * @param sdk - FerraDlmmSDK instance */ constructor(sdk: FerraDlmmSDK); /** * Get the SDK instance * @returns FerraDlmmSDK instance */ get sdk(): FerraDlmmSDK; /** * Creates a new LB pair and executes the transaction * @param params - Parameters for creating the LB pair * @param params.tokenXType - Type of token X * @param params.tokenYType - Type of token Y * @param params.binStep - Bin step for the pair * @param params.activeId - Initial active bin ID * @param tx - Optional existing transaction to add the creation to * @returns Transaction object ready to be executed * * @example * ```typescript * const tx = await factory.createLBPair({ * tokenXType: "0x2::sui::SUI", * tokenYType: "0x...::usdc::USDC", * binStep: 10, * activeId: 8388608 * }); * ``` */ createLBPair: (params: Omit<CreateLBPairParams, "packageId" | "factoryId">, tx?: Transaction) => Promise<Transaction>; } /** * Represents a SUI address, which is a string. */ type SuiAddressType = string; /** * Represents a SUI object identifier, which is a string. */ type SuiObjectIdType = string; /** * The address representing the clock in the system. */ declare const CLOCK_ADDRESS = "0x0000000000000000000000000000000000000000000000000000000000000006"; /** * Constants for different modules in the DLMM. */ declare const DlmmFactoryModule = "lb_factory"; declare const DlmmPairModule = "lb_pair"; declare const DlmmQuoterModule = "lb_quoter"; declare const DlmmRouterModule = "lb_router"; declare const DlmmTokenModule = "lb_token"; /** * The address for CoinInfo module. */ declare const CoinInfoAddress = "0x1::coin::CoinInfo"; /** * The address for CoinStore module. */ declare const CoinStoreAddress = "0x1::coin::CoinStore"; /** * Represents a SUI resource, which can be of any type. */ type SuiResource = any; /** * Represents a paginated data page with optional cursor and limit. */ type DataPage<T> = { data: T[]; nextCursor?: any; hasNextPage: boolean; }; /** * Represents query parameters for pagination. */ type PageQuery = { cursor?: any; limit?: number | null; }; /** * Represents arguments for pagination, with options for fetching all data or using PageQuery. */ type PaginationArgs = 'all' | PageQuery; /** * Represents a Non-Fungible Token (NFT) with associated metadata. */ type NFT = { /** * The address or identifier of the creator of the NFT. */ creator: string; /** * A description providing additional information about the NFT. */ description: string; /** * The URL to the image representing the NFT visually. */ image_url: string; /** * A link associated with the NFT, providing more details or interactions. */ link: string; /** * The name or title of the NFT. */ name: string; /** * The URL to the project or collection associated with the NFT. */ project_url: string; }; /** * Represents a SUI struct tag. */ type SuiStructTag = { /** * The full address of the struct. */ full_address: string; /** * The source address of the struct. */ source_address: string; /** * The address of the struct. */ address: SuiAddressType; /** * The module to which the struct belongs. */ module: string; /** * The name of the struct. */ name: string; /** * An array of type arguments (SUI addresses) for the struct. */ type_arguments: SuiAddressType[]; }; /** * Represents basic SUI data types. */ type SuiBasicTypes = 'address' | 'bool' | 'u8' | 'u16' | 'u32' | 'u64' | 'u128' | 'u256'; /** * Represents a SUI transaction argument, which can be of various types. */ type SuiTxArg = TransactionArgument | string | number | bigint | boolean; /** * Represents input types for SUI data. */ type SuiInputTypes = 'object' | SuiBasicTypes; /** * Gets the default SUI input type based on the provided value. * @param value - The value to determine the default input type for. * @returns The default SUI input type. * @throws Error if the type of the value is unknown. */ declare const getDefaultSuiInputType: (value: any) => SuiInputTypes; /** * Represents configuration for tokens. */ type TokenConfig = { /** * The object identifier of the coin registry. */ coin_registry_id: SuiObjectIdType; /** * The object identifier of the coin list owner. */ coin_list_owner: SuiObjectIdType; /** * The object identifier of the pool registry. */ pool_registry_id: SuiObjectIdType; /** * The object identifier of the pool list owner. */ pool_list_owner: SuiObjectIdType; }; /** * Represents information about a token. */ type TokenInfo = { /** * The name of the token. */ name: string; /** * The symbol of the token. */ symbol: string; /** * The official symbol of the token. */ official_symbol: string; /** * The Coingecko ID of the token. */ coingecko_id: string; /** * The number of decimal places for the token. */ decimals: number; /** * The project URL for the token. */ project_url: string; /** * The URL to the logo image of the token. */ logo_url: string; /** * The address of the token. */ address: string; } & Record<string, any>; /** * Represents information about a liquidity pool. */ type PoolInfo = { /** * The symbol of the pool. */ symbol: string; /** * The name of the pool. */ name: string; /** * The number of decimal places for the pool. */ decimals: number; /** * The fee for the pool. */ fee: string; /** * The tick spacing for the pool. */ tick_spacing: number; /** * The type of the pool. */ type: string; /** * The address of the pool. */ address: string; /** * The address of coin A for the pool. */ coin_a_address: string; /** * The address of coin B for the pool. */ coin_b_address: string; /** * The project URL for the pool. */ project_url: string; /** * The sort order for the pool. */ sort: number; /** * Indicates if the rewarder is displayed for the pool. */ is_display_rewarder: boolean; /** * Indicates if rewarder 1 is displayed for the pool. */ rewarder_display1: boolean; /** * Indicates if rewarder 2 is displayed for the pool. */ rewarder_display2: boolean; /** * Indicates if rewarder 3 is displayed for the pool. */ rewarder_display3: boolean; /** * Indicates if the pool is stable. */ is_stable: boolean; } & Record<string, any>; /** * Represents an event related to token configuration. */ type TokenConfigEvent = { /** * The object identifier of the coin registry. */ coin_registry_id: SuiObjectIdType; /** * The object identifier of the coin list owner. */ coin_list_owner: SuiObjectIdType; /** * The object identifier of the pool registry. */ pool_registry_id: SuiObjectIdType; /** * The object identifier of the pool list owner. */ pool_list_owner: SuiObjectIdType; }; /** * Represents a coin asset with address, object ID, and balance information. */ type CoinAsset = { /** * The address type of the coin asset. */ coinAddress: SuiAddressType; /** * The object identifier of the coin asset. */ coinObjectId: SuiObjectIdType; /** * The balance amount of the coin asset. */ balance: bigint; }; /** * Represents a faucet coin configuration. */ type FaucetCoin = { /** * The name or identifier of the transaction module. */ transactionModule: string; /** * The supply ID or object identifier of the faucet coin. */ suplyID: SuiObjectIdType; /** * The number of decimal places used for the faucet coin. */ decimals: number; }; /** * Configuration settings for the Cryptocurrency Liquidity Mining Module (CLMM). */ type DlmmConfig = { global_config: string; pairs_id: string; reward_vault: string; }; type Package<T = undefined> = { /** * The unique identifier of the package. */ package_id: string; /** * the package was published. */ published_at: string; /** * The version number of the package (optional). */ version?: number; /** * The configuration or data contained in the package (optional). */ config?: T; }; type BigNumber = Decimal.Value | number | string; /** * Represents a module for making RPC (Remote Procedure Call) requests. */ declare class RpcModule extends SuiClient { /** * Get events for a given query criteria * @param query * @param paginationArgs * @returns */ queryEventsByPage(query: SuiEventFilter, paginationArgs?: PaginationArgs): Promise<DataPage<any>>; queryTransactionBlocksByPage(filter?: TransactionFilter, paginationArgs?: PaginationArgs, order?: 'ascending' | 'descending' | null | undefined): Promise<DataPage<SuiTransactionBlockResponse>>; /** * Get all objects owned by an address * @param owner * @param query * @param paginationArgs * @returns */ getOwnedObjectsByPage(owner: string, query: SuiObjectResponseQuery, paginationArgs?: PaginationArgs): Promise<DataPage<any>>; /** * Return the list of dynamic field objects owned by an object * @param parentId * @param paginationArgs * @returns */ getDynamicFieldsByPage(parentId: SuiObjectIdType, paginationArgs?: PaginationArgs): Promise<DataPage<any>>; /** * Batch get details about a list of objects. If any of the object ids are duplicates the call will fail * @param ids * @param options * @param limit * @returns */ batchGetObjects(ids: SuiObjectIdType[], options?: SuiObjectDataOptions, limit?: number): Promise<SuiObjectResponse[]>; /** * Calculates the gas cost of a transaction block. * @param {Transaction} tx - The transaction block to calculate gas for. * @returns {Promise<number>} - The estimated gas cost of the transaction block. * @throws {Error} - Throws an error if the sender is empty. */ calculationTxGas(tx: Transaction): Promise<number>; /** * Sends a transaction block after signing it with the provided keypair. * * @param {Ed25519Keypair | Secp256k1Keypair} keypair - The keypair used for signing the transaction. * @param {Transaction} tx - The transaction block to send. * @returns {Promise<SuiTransactionBlockResponse | undefined>} - The response of the sent transaction block. */ sendTransaction(keypair: Ed25519Keypair | Secp256k1Keypair, tx: Transaction): Promise<SuiTransactionBlockResponse | undefined>; /** * Send a simulation transaction. * @param tx - The transaction block. * @param simulationAccount - The simulation account. * @param useDevInspect - A flag indicating whether to use DevInspect. Defaults to true. * @returns A promise that resolves to DevInspectResults or undefined. */ sendSimulationTransaction(tx: Transaction, simulationAccount: string, useDevInspect?: boolean): Promise<DevInspectResults | undefined>; } type LbPositionOnChain = { coin_type_a: { fields: { name: string; }; type: string; }; coin_type_b: { fields: { name: string; }; type: string; }; description: string; id: { id: string; }; index: string; name: string; pair_id: string; url: string; }; interface BinDataOnchain { name: number; value: string; } interface PositionBinOnchain { name: number; value: { fields: { amount: string; fee_growth_inside_last_x: string; fee_growth_inside_last_y: string; fees_pending_x: string; fees_pending_y: string; }; }; } type BinReserveOnchain = { id: { id: string; }; name: string; value: { fields: { score: string; nexts: { fields: { is_none: boolean; v: string; }; }[]; prev: { fields: { is_none: boolean; v: string; }; }; value: { fields: { reserve_x: string | number | bigint; reserve_y: string | number | bigint; fee_x: string | number | bigint; fee_y: string | number | bigint; price: string | number | bigint; fee_growth_x: string | number | bigint; fee_growth_y: string | number | bigint; rewards_growth: Iterable<string | number | bigint> & { length: number; }; liquidity: string | number | bigint; total_supply: string | number | bigint; }; }; }; }; }; interface PositionInfoOnChain { id: { id: string; }; name: string; value: { fields: { position_id: string; bins: { fields: { id: { id: string; }; size: string; }; }; total_fees_gen: string; reward_per_fee_snapshot: string[]; reward_dump: boolean; reward_dump_version: string; reward_claimed_bitmap: number; reward_version_checksum: string; }; }; } type PositionReward = { coinType: string; amount: string; }; interface LockPositionParams { positionId: string; untilTimestamp: number; pairId: string; typeX: string; typeY: string; } /** * Module for managing DLMM positions * Handles fetching and parsing of liquidity positions and their associated bins */ declare class PositionModule implements IModule { protected _sdk: FerraDlmmSDK; /** * Cache storage for position data */ private readonly _cache; /** * Initialize the position module with SDK instance * @param sdk - FerraDlmmSDK instance */ constructor(sdk: FerraDlmmSDK); /** * Get the SDK instance * @returns FerraDlmmSDK instance */ get sdk(): FerraDlmmSDK; /** * Fetch a single liquidity position by ID * @param positionId - The object ID of the position to fetch * @returns Promise resolving to LBPosition data * @throws Error if position ID is invalid or position not found */ getLbPosition(positionId: string): Promise<LBPosition>; /** * Fetch all liquidity positions owned by the current sender * @returns Promise resolving to array of LBPosition data * @throws DlmmPairsError if sender address is invalid */ getLbPositions(pairIds: string[]): Promise<LBPosition[]>; /** * Get all bins associated with a position in a specific pair * @param pair - The LBPair object containing position manager * @param positionId - The ID of the position to fetch bins for * @returns Promise resolving to array of BinData * @throws Error if position manager not found or position doesn't match pair */ getPositionBins(pair: LBPair, positionId: string): Promise<BinData[]>; /** * Get all bins associated with a position in a specific pair * @param pair - The LBPair object containing position manager * @param positionId - The ID of the position to fetch bins for * @returns Promise resolving to array of BinData * @throws Error if position manager not found or position doesn't match pair */ getPositionBinsWithRange(pair: LBPair, positionId: string, binRange: [from: number, to: number]): Promise<BinData[]>; getPositionBinsAmount(pair: LBPair, positionId: string): Promise<Amounts[]>; getPositionRewards(pair: LBPair, positionId: string): Promise<PositionReward[]>; claimPositionRewards(pair: LBPair, positionId: string, tx?: Transaction): Promise<Transaction>; getPositionFees(pair: LBPair, positionId: string, binIds: number[]): Promise<[PositionReward, PositionReward] | null>; claimPositionFee(pair: LBPair, positionId: string, binIds: number[], tx?: Transaction): Promise<Transaction>; lockPosition(pair: LBPair, positionId: string, untilTimestamp: number, tx?: Transaction): Promise<Transaction>; getLockPositionStatus(positionId: string): Promise<[current_lock: number, current_timestamp: number, is_locked: boolean]>; /** * Fetch all bins from a bin manager * @param binManagerId - The ID of the bin manager object * @param positionVersion - Version string of the position * @returns Promise resolving to sorted array of BinData */ private getBinsByManager; /** * Get bin manager for a specific position * @param positionManager - The ID of the position manager object * @param positionId - The ID of the position * @returns Promise resolving to bin manager data * @throws Error if position manager ID is invalid or bin manager not found */ private getBinManager; /** * Extract struct content fields from a Sui object response * @param object - SuiObjectResponse to parse * @returns Parsed fields or null if invalid */ private getStructContentFields; /** * Extract bin manager from position info object * @param positionInfo - SuiObjectResponse containing position info * @returns Bin manager fields or null if not found */ private getBinManagerByPositionInfo; /** * Parse raw position content into LBPosition format * @param typeTag - The type tag string of the position object * @param contents - The parsed data content from chain * @param version - Version string of the position * @returns Parsed LBPosition or null if invalid */ private parsePositionContent; } /** * Module for managing DLMM swap * Handles */ declare class SwapModule implements IModule { protected _sdk: FerraDlmmSDK; /** * Cache storage for pair data */ private readonly _cache; /** * Initialize the pair module with SDK instance * @param sdk - FerraDlmmSDK instance */ constructor(sdk: FerraDlmmSDK); /** * Get the SDK instance * @returns FerraDlmmSDK instance */ get sdk(): FerraDlmmSDK; calculateRates(pair: LBPair, params: CalculateSwapParams): CalculateRatesResult; /** * Prepare a swap transaction for a pair * @param pair - The LBPair to swap on * @param params - Swap parameters including amount, direction, recipient * @param tx - Optional existing transaction to add swap to * @returns Transaction object ready to be executed * @throws DlmmPairsError if sender address is invalid */ prepareSwap(pair: LBPair, params: PrepareSwapParams, tx?: Transaction): Promise<Transaction>; } /** * Represents options and configurations for an SDK. */ type SdkOptions = { /** * The full URL for interacting with the RPC (Remote Procedure Call) service. */ fullRpcUrl: string; /** * Optional URL for the faucet service. */ faucetURL?: string; /** * Configuration for the simulation account. */ simulationAccount: { /** * The address of the simulation account. */ address: string; }; /** * Package containing token-related configurations. */ token?: Package<TokenConfig>; /** * Package containing Cryptocurrency Liquidity Mining Module (DLMM) pool configurations. */ dlmm_pool: Package<DlmmConfig>; /** * Package containing integration-related configurations. */ integrate: Package; /** * The URL for the swap count */ dlmmApiUrl?: string; }; /** * The entry class of FerraDlmmSDK, which is almost responsible for all interactions with DLMM. */ declare class FerraDlmmSDK { private readonly _cache; /** * RPC provider on the SUI chain */ protected _rpcModule: RpcModule; /** * Provide interact with dlmm pairs with a pool router interface. */ protected _pair: PairModule; protected _position: PositionModule; protected _factory: FactoryModule; protected _quoter: QuoterModule; protected _swap: SwapModule; /** * Provide sdk options */ protected _sdkOptions: SdkOptions; /** * After connecting the wallet, set the current wallet address to senderAddress. */ protected _senderAddress: string; constructor(options: SdkOptions); /** * Getter for the sender address property. * @returns {SuiAddressType} The sender address. */ get senderAddress(): SuiAddressType; /** * Setter for the sender address property. * @param {string} value - The new sender address value. */ set senderAddress(value: string); get Factory(): FactoryModule; /** * Getter for the fullClient property. * @returns {RpcModule} The fullClient property value. */ get fullClient(): RpcModule; /** * Getter for the sdkOptions property. * @returns {SdkOptions} The sdkOptions property value. */ get sdkOptions(): SdkOptions; /** * Getter for the Pool property. * @returns {PoolModule} The Pool property value. */ get Pair(): PairModule; /** * Getter for the Pool property. * @returns {PoolModule} The Pool property value. */ get Position(): PositionModule; get Quoter(): QuoterModule; get Swap(): SwapModule; /** * Gets all coin assets for the given owner and coin type. * * @param suiAddress The address of the owner. * @param coinType The type of the coin. * @returns an array of coin assets. */ getOwnerCoinAssets(suiAddress: string, coinType?: string | null, forceRefresh?: boolean): Promise<CoinAsset[]>; /** * Gets all coin balances for the given owner and coin type. * * @param suiAddress The address of the owner. * @param coinType The type of the coin. * @returns an array of coin balances. */ getOwnerCoinBalances(suiAddress: string, coinType?: string | null): Promise<CoinBalance[]>; /** * Updates the cache for the given key. * * @param key The key of the cache entry to update. * @param data The data to store in the cache. * @param time The time in minutes after which the cache entry should expire. */ updateCache(key: string, data: SuiResource, time?: number): void; /** * Gets the cache entry for the given key. * * @param key The key of the cache entry to get. * @param forceRefresh Whether to force a refresh of the cache entry. * @returns The cache entry for the given key, or undefined if the cache entry does not exist or is expired. */ getCache<T>(key: string, forceRefresh?: boolean): T | undefined; } declare const cacheTime5min: number; declare const cacheTime24h: number; declare function getFutureTime(interval: number): number; /** * Defines the structure of a CachedContent object, used for caching resources in memory. */ declare class CachedContent { overdueTime: number; value: SuiResource | null; constructor(value: SuiResource | null, overdueTime?: number); isValid(): boolean; } /** * Converts an amount to a decimal value, based on the number of decimals specified. * @param {number | string} amount - The amount to convert to decimal. * @param {number | string} decimals - The number of decimals to use in the conversion. * @returns {number} - Returns the converted amount as a number. */ declare function toDecimalsAmount(amount: number | string, decimals: number | string): number; /** * Converts a bigint to an unsigned integer of the specified number of bits. * @param {bigint} int - The bigint to convert. * @param {number} bits - The number of bits to use in the conversion. Defaults to 32 bits. * @returns {string} - Returns the converted unsigned integer as a string. */ declare function asUintN(int: bigint, bits?: number): string; /** * Converts a bigint to a signed integer of the specified number of bits. * @param {bigint} int - The bigint to convert. * @param {number} bits - The number of bits to use in the conversion. Defaults to 32 bits. * @returns {number} - Returns the converted signed integer as a number. */ declare function asIntN(int: bigint, bits?: number): number; /** * Converts an amount in decimals to its corresponding numerical value. * @param {number|string} amount - The amount to convert. * @param {number|string} decimals - The number of decimal places used in the amount. * @returns {number} - Returns the converted numerical value. */ declare function fromDecimalsAmount(amount: number | string, decimals: number | string): number; /** * Converts a secret key in string or Uint8Array format to an Ed25519 key pair. * @param {string|Uint8Array} secretKey - The secret key to convert. * @param {string} ecode - The encoding of the secret key ('hex' or 'base64'). Defaults to 'hex'. * @returns {Ed25519Keypair} - Returns the Ed25519 key pair. */ declare function secretKeyToEd25519Keypair(secretKey: string | Uint8Array, ecode?: 'hex' | 'base64'): Ed25519Keypair; /** * Converts a secret key in string or Uint8Array format to a Secp256k1 key pair. * @param {string|Uint8Array} secretKey - The secret key to convert. * @param {string} ecode - The encoding of the secret key ('hex' or 'base64'). Defaults to 'hex'. * @returns {Ed25519Keypair} - Returns the Secp256k1 key pair. */ declare function secretKeyToSecp256k1Keypair(secretKey: string | Uint8Array, ecode?: 'hex' | 'base64'): Secp256k1Keypair; /** * Builds an NFT object based on a response containing information about the NFT. * @param {any} objects - The response containing information about the NFT. * @returns {NFT} - The built NFT object. */ declare function buildNFT(objects: any): NFT; declare function isSortedSymbols(symbolX: string, symbolY: string): boolean; declare function composeType(address: string, generics: SuiAddressType[]): SuiAddressType; declare function composeType(address: string, struct: string, generics?: SuiAddressType[]): SuiAddressType; declare function composeType(address: string, module: string, struct: string, generics?: SuiAddressType[]): SuiAddressType; declare function extractAddressFromType(type: string): string; declare function extractStructTagFromType(type: string): SuiStructTag; declare function normalizeCoinType(coinType: string): string; declare function fixSuiObjectId(value: string): string; /** * Fixes and normalizes a coin type by removing or keeping the prefix. * * @param {string} coinType - The coin type to be fixed. * @param {boolean} removePrefix - Whether to remove the prefix or not (default: true). * @returns {string} - The fixed and normalized coin type. */ declare const fixCoinType: (coinType: string, removePrefix?: boolean) => string; /** * Recursively traverses the given data object and patches any string values that represent Sui object IDs. * * @param {any} data - The data object to be patched. */ declare function patchFixSuiObjectId(data: any): void; declare function addHexPrefix(hex: string): string; declare function removeHexPrefix(hex: string): string; declare function shortString(str: string, start?: number, end?: number): string; declare function shortAddress(address: string, start?: number, end?: number): string; declare function checkAddress(address: any, options?: { leadingZero: boolean; }): boolean; /** * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. * @param v the value */ declare function toBuffer(v: any): Buffer; declare function bufferToHex(buffer: Buffer): string; /** * '\x02\x00\x00\x00' to 2 * @param binaryData */ declare function hexToNumber(binaryData: string): number; declare function utf8to16(str: string): string; declare function hexToString(str: string): string; declare function d(value?: Decimal.Value): Decimal.Instance; declare function decimalsMultiplier(decimals?: Decimal.Value): Decimal.Instance; /** * Utility class for building DLMM protocol transactions * Provides static methods for factory, pair, liquidity, and swap operations */ declare class TransactionUtil { /** Factory Operations */ /** * Create a new DLMM factory * @param params - Factory creation parameters * @param params.owner - Address of the factory owner * @param params.feeRecipient - Address to receive protocol fees * @param params.flashLoanFee - Fee percentage for flash loans * @param sdkOptions - SDK configuration options * @returns Transaction object for factory creation * @throws Error if addresses are invalid or fee is not provided */ static createFatory: (params: CreateFactoryParams, sdkOptions: SdkOptions) => Transaction; /** * Creates a new LB pair on the DLMM factory * @param params - Parameters for creating the LB pair * @param params.tokenXType - Type of token X (must be < tokenYType) * @param params.tokenYType - Type of token Y (must be > tokenXType) * @param params.activeId - Initial active bin ID * @param params.binStep - Bin step in basis points * @param sdkOptions - SDK configuration options * @param tx - Optional existing transaction to add to * @returns Transaction object with pair creation * @throws Error if parameters are invalid */ static createLBPair: (params: CreateLBPairParams, sdkOptions: SdkOptions, tx?: Transaction) => Transaction; /** * Create a new liquidity position NFT * @param pair - The LBPair to create position for * @param sdkOptions - SDK configuration options * @param tx - Optional existing transaction to add to * @returns Tuple of [Transaction, position object] */ static createLbPosition(pair: LBPair, sdkOptions: SdkOptions, tx?: Transaction): [Transaction, TransactionResult[number]]; /** * Add liquidity to a position * @param pair - The LBPair to add liquidity to * @param params - Liquidity addition parameters * @param params.deltaIds - Array of bin IDs to add liquidity to * @param params.distributionX - Distribution of token X across bins * @param params.distributionY - Distribution of token Y across bins * @param params.amountX - Token X amount to add * @param params.amountY - Token Y amount to add * @param params.position - Position object to add liquidity to * @param sdkOptions - SDK configuration options * @param tx - Optional existing transaction to add to * @returns Transaction object with liquidity addition */ static addLiquidity(pair: LBPair, { deltaIds, distributionX, distributionY, amountX, amountY, position, minAmountX, mi