@ferra-xyz/aggregator
Version:
808 lines (786 loc) • 26.5 kB
text/typescript
import { SuiClient, SuiEventFilter, TransactionFilter, SuiTransactionBlockResponse, SuiObjectResponseQuery, SuiObjectDataOptions, SuiObjectResponse, DevInspectResults, CoinBalance } from '@mysten/sui/client';
import { Transaction, TransactionArgument, TransactionResult } from '@mysten/sui/transactions';
import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1';
import { Transaction as Transaction$1, TransactionResult as TransactionResult$1 } from '@mysten/sui/dist/cjs/transactions';
import Decimal from 'decimal.js';
declare enum DexOrigins {
Ferra = "Ferra",
Cetus = "Cetus",
Turbos = "Turbos",
Navi = "Navi",
SuiSwap = "SuiSwap"
}
declare enum DexTypes {
AMM = "AMM",
DAMM = "DAMM",
DAMM2 = "DAMM2",
CLMM = "CLMM",
DLMM = "DLMM"
}
type InputFindBestQuotesParams = {
from: string;
to: string;
amount: string;
slippageTolerance?: number;
};
type SwapStep = {
direction: boolean;
type: DexTypes;
origin: DexOrigins;
poolAddress: string;
coinIn: string;
coinOut: string;
feeRate: number;
amountIn: string;
amountOut: string;
currentSqrtPrice: string;
decimalsIn: number;
decimalsOut: number;
currentPrice: string;
};
type TradingRoute = {
percent: string;
inputAmount: string;
outputAmount: string;
outputAmountMin?: string;
pathIndex: number;
lastQuoteOutput: string;
swapStep: SwapStep[];
};
interface IModule {
readonly sdk: FerraAggregatorSDK;
}
declare class QuoterModule implements IModule {
protected _sdk: FerraAggregatorSDK;
/**
* Cache storage for pair data
*/
private readonly _cache;
/**
* Initialize the pair module with SDK instance
* @param sdk - FerraAggregatorSDK instance
*/
constructor(sdk: FerraAggregatorSDK);
/**
* Get the SDK instance
* @returns FerraAggregatorSDK instance
*/
get sdk(): FerraAggregatorSDK;
getBestQuotes(params: InputFindBestQuotesParams): Promise<TradingRoute[]>;
}
declare class AggSwapModule implements IModule {
protected _sdk: FerraAggregatorSDK;
/**
* Cache storage for pair data
*/
private readonly _cache;
/**
* Initialize the pair module with SDK instance
* @param sdk - FerraAggregatorSDK instance
*/
constructor(sdk: FerraAggregatorSDK);
/**
* Get the SDK instance
* @returns FerraAggregatorSDK instance
*/
get sdk(): FerraAggregatorSDK;
swapWithTradingRoutes(params: TradingRoute[]): Promise<Transaction>;
/**
* Execute a swap with automatic routing
* @param params - Swap parameters
* @returns Transaction object
*/
private swap;
private switchFerraDex;
}
/**
* 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 Dex Agg.
*/
declare const AggQuoterModule = "lb_quoter";
/**
* 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 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;
};
/**
* Configuration settings for the Cryptocurrency Liquidity Mining Module (CLMM).
*/
type AggregatorConfig = {
Ferra?: {
clmm_global_config?: string;
dlmm_global_config?: string;
};
Cetus?: {};
Navi?: {};
Turbos?: {};
};
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;
};
/**
* 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;
};
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>;
}
/**
* 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 Aggregator Package configurations.
*/
agg_pkg: Package<AggregatorConfig>;
/**
* The URL for the quoter
*/
quoterUrl?: string;
};
/**
* The entry class of FerraAggregatorSDK, which is almost responsible for all interactions with CLMM.
*/
declare class FerraAggregatorSDK {
private readonly _cache;
/**
* RPC provider on the SUI chain
*/
protected _rpcModule: RpcModule;
/**
* Provide interact with dlmm pairs with a pool router interface.
*/
protected _quoter: QuoterModule;
protected _aggSwap: AggSwapModule;
/**
* Provide sdk options
*/
protected _sdkOptions: SdkOptions;
/**
* After connecting the wallet, set the current wallet address to senderAddress.
*/
protected _senderAddress: string;
config: any;
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);
/**
* 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;
get Quoter(): QuoterModule;
get AggSwap(): AggSwapModule;
/**
* 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;
}
type SwapClmmFerraTransParams = {
packageId: string;
globalConfig: string;
poolId: string;
coinTypeA: string;
coinTypeB: string;
amountIn: TransactionResult[number];
atob: boolean;
};
type SwapDlmmFerraTransParams = {
packageId: string;
globalConfig: string;
pairId: string;
coinTypeA: string;
coinTypeB: string;
amountIn: TransactionResult[number];
atob: boolean;
minAmountOut?: bigint;
};
/**
* Utility class for building DLMM protocol transactions
* Provides static methods for factory, pair, liquidity, and swap operations
*/
declare class TransactionUtil {
private static readonly FERRA_CLMM_MODULE_NAME;
private static readonly FERRA_DLMM_MODULE_NAME;
/**
* Build transaction for swapping from CoinA to CoinB
*/
static buildSwapClmmFerraTransaction(tx: Transaction$1, params: SwapClmmFerraTransParams): [Transaction$1, TransactionResult$1[number]];
static buildSwapDlmmFerraTransaction(tx: Transaction$1, params: SwapDlmmFerraTransParams): [Transaction$1, TransactionResult$1[number]];
/**
* Build a coin object with specific amount from user's coin assets
* @param tx - Transaction object
* @param coinAssets - Array of user's coin assets
* @param coinType - Type of coin to build
* @param amount - Amount needed
* @returns Transaction result with coin object
*/
static buildCoinAmount(tx: Transaction$1, coinAssets: CoinAsset[], coinType: string, amount: bigint): TransactionResult$1[number];
/**
* Create a zero-value coin object
* @param txb - Transaction builder
* @param coinType - Type of coin to create
* @returns Zero-value coin object
*/
static callMintZeroValueCoin: (txb: Transaction$1, coinType: string) => {
$kind: "NestedResult";
NestedResult: [number, number];
};
/**
* Build a coin object by selecting and merging user's coins
* @param tx - Transaction object
* @param amount - Amount needed
* @param coinAssets - Available coin assets
* @param fixAmount - Whether to split exact amount
* @returns Object with target coin and metadata
*/
private static buildSpitTargeCoin;
}
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;
/**
* Check if the address is a valid sui address.
* @param {string}address
* @returns
*/
declare function checkInvalidSuiAddress(address: string): boolean;
declare class TxBlock {
txBlock: Transaction;
constructor();
/**
* Transfer sui to many recipoents.
* @param {string[]}recipients The recipient addresses.
* @param {number[]}amounts The amounts of sui coins to be transferred.
* @returns this
*/
transferSuiToMany(recipients: string[], amounts: number[]): this;
/**
* Transfer sui to one recipient.
* @param {string}recipient recipient cannot be empty or invalid sui address.
* @param {number}amount
* @returns this
*/
transferSui(recipient: string, amount: number): this;
/**
* Transfer coin to many recipients.
* @param {string}recipient recipient cannot be empty or invalid sui address.
* @param {number}amount amount cannot be empty or invalid sui address.
* @param {string[]}coinObjectIds object ids of coins to be transferred.
* @returns this
* @deprecated use transferAndDestoryZeroCoin instead
*/
transferCoin(recipient: string, amount: number, coinObjectIds: string[]): this;
}
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 const aggMainnet: SdkOptions;
/**
* Initialize the mainnet SDK
* @param fullNodeUrl. If provided, it will be used as the full node URL.
* @param simulationAccount. If provided, it will be used as the simulation account address.
* when you use the `preswap` method or other methods that require payment assistance,
* you must configure a simulation account with sufficient balance of input tokens.
* If you connect the wallet, you can set the current wallet address to simulationAccount.
* @returns
*/
declare function initMainnetSDK(fullNodeUrl?: string, wallet?: string): FerraAggregatorSDK;
declare const aggTestnet: SdkOptions;
/**
* Initialize the testnet SDK
* @param fullNodeUrl. If provided, it will be used as the full node URL.
* @param simulationAccount. If provided, it will be used as the simulation account address.
* when you use the `preswap` method or other methods that require payment assistance,
* you must configure a simulation account with sufficient balance of input tokens.
* If you connect the wallet, you can set the current wallet address to simulationAccount.
* @returns
*/
declare function initTestnetSDK(fullNodeUrl?: string, wallet?: string): FerraAggregatorSDK;
declare const aggBeta: SdkOptions;
/**
* Initialize the beta SDK
* @param fullNodeUrl. If provided, it will be used as the full node URL.
* @param simulationAccount. If provided, it will be used as the simulation account address.
* when you use the `preswap` method or other methods that require payment assistance,
* you must configure a simulation account with sufficient balance of input tokens.
* If you connect the wallet, you can set the current wallet address to simulationAccount.
* @returns
*/
declare function initBetaSDK(fullNodeUrl?: string, wallet?: string): FerraAggregatorSDK;
interface InitFerraSDKOptions {
network: 'mainnet' | 'testnet' | 'beta';
fullNodeUrl?: string;
wallet?: string;
}
/**
* Helper function to initialize the Ferra SDK
* @param env - The environment to initialize the SDK in. One of 'mainnet' or 'testnet' or 'beta'.
* @param fullNodeUrl - The full node URL to use.
* @param wallet - The wallet address to use. If not provided,
* If you use the `preswap` method or other methods that require payment assistance,
* you must configure a wallet with sufficient balance of input tokens.
* If you do not set a wallet, the SDK will throw an error.
* @returns The initialized Ferra SDK.
*/
declare function initFerraSDK(options: InitFerraSDKOptions): FerraAggregatorSDK;
declare function initFerraAggregatorSDK(options: InitFerraSDKOptions): FerraAggregatorSDK;
export { AggQuoterModule, AggSwapModule, type AggregatorConfig, type BigNumber, CLOCK_ADDRESS, CachedContent, type CoinAsset, CoinInfoAddress, CoinStoreAddress, type DataPage, DexOrigins, DexTypes, FerraAggregatorSDK, type InputFindBestQuotesParams, type NFT, type Package, type PageQuery, type PaginationArgs, type PoolInfo, QuoterModule, RpcModule, type SdkOptions, type SuiAddressType, type SuiBasicTypes, type SuiInputTypes, type SuiObjectIdType, type SuiResource, type SuiStructTag, type SuiTxArg, type SwapStep, type TokenConfig, type TokenConfigEvent, type TokenInfo, type TradingRoute, TransactionUtil, TxBlock, addHexPrefix, aggBeta, aggMainnet, aggTestnet, bufferToHex, cacheTime24h, cacheTime5min, checkAddress, checkInvalidSuiAddress, composeType, FerraAggregatorSDK as default, extractAddressFromType, extractStructTagFromType, fixCoinType, fixSuiObjectId, getDefaultSuiInputType, getFutureTime, hexToNumber, hexToString, initBetaSDK, initFerraAggregatorSDK, initFerraSDK, initMainnetSDK, initTestnetSDK, isSortedSymbols, normalizeCoinType, patchFixSuiObjectId, removeHexPrefix, shortAddress, shortString, toBuffer, utf8to16 };