import { Transaction } from '../api/transaction-api'; import { LogLevel } from '../utils/logger'; import { TransferParams, WithdrawParams, FastBridgeInfo, BridgeSupportedNetwork, DepositHistory, WithdrawHistory, L1DepositParams, L1DepositResult, L1BridgeConfig } from '../types/api'; import { Signer } from 'ethers'; import type { AxiosRequestConfig } from 'axios'; /** * Configuration interface for SignerClient * @interface SignerConfig */ export interface SignerConfig { /** Lighter Protocol API URL */ url: string; /** Private key for signing transactions */ privateKey: string; /** Account index (0 for master account) */ accountIndex: number; /** API key index for authentication */ apiKeyIndex: number; /** Chain ID (defaults to 304) */ chainId?: number; /** Optional WASM signer configuration */ wasmConfig?: { wasmPath: string; wasmExecPath?: string; waitForReady?: boolean; }; /** Optional logging level */ logLevel?: LogLevel; /** Optional: Enable WebSocket order placement */ enableWebSocket?: boolean; /** Optional: Enable request batching */ enableBatching?: boolean; /** Optional: Enable memory pooling */ enableMemoryPooling?: boolean; /** Optional: Enable advanced caching */ enableAdvancedCaching?: boolean; /** Optional: L1 bridge configuration for L1-to-L2 deposits */ l1BridgeConfig?: L1BridgeConfig; additionalHeaders?: Record; requestConfig?: AxiosRequestConfig; } export interface CreateOrderParams { marketIndex: number; clientOrderIndex: number; baseAmount: number; price: number; isAsk: boolean; orderType?: number; timeInForce?: number; reduceOnly?: boolean; triggerPrice?: number; orderExpiry?: number; nonce?: number; } export interface CreateMarketOrderParams { marketIndex: number; clientOrderIndex: number; baseAmount: number; avgExecutionPrice: number; isAsk: boolean; reduceOnly?: boolean; } export interface CancelOrderParams { marketIndex: number; orderIndex: number; } export interface ChangeApiKeyParams { ethSigner: string | Signer; newPubkey: string; newApiKeyIndex?: number; nonce?: number; } /** * Order Type Constants and Enums * Provides easy-to-understand order type references without context */ export declare enum OrderType { LIMIT = 0, MARKET = 1, STOP_LOSS = 2, STOP_LOSS_LIMIT = 3, TAKE_PROFIT = 4, TAKE_PROFIT_LIMIT = 5, TWAP = 6 } export declare enum TimeInForce { IMMEDIATE_OR_CANCEL = 0, GOOD_TILL_TIME = 1, POST_ONLY = 2 } /** * Legacy SDK values retained for existing consumers. * @deprecated These values do not describe raw API statuses. Migrate to * ApiTransactionStatus or getTransactionExecutionStatus explicitly. */ export declare enum TransactionStatus { PENDING = 0, QUEUED = 1, COMMITTED = 2, EXECUTED = 3, FAILED = 4, REJECTED = 5 } export declare enum TransactionType { TRANSFER = 12, WITHDRAW = 13, CREATE_ORDER = 14, CANCEL_ORDER = 15, CANCEL_ALL_ORDERS = 16, MODIFY_ORDER = 17, MINT_SHARES = 18, BURN_SHARES = 19, UPDATE_LEVERAGE = 20 } export interface CreateOrderParams { marketIndex: number; clientOrderIndex: number; baseAmount: number; price: number; isAsk: boolean; orderType?: number; timeInForce?: number; reduceOnly?: boolean; triggerPrice?: number; orderExpiry?: number; nonce?: number; } /** * Main SignerClient class for interacting with Lighter Protocol * Handles order creation, account management, and transaction signing * @class SignerClient */ export declare class SignerClient { private config; private apiClient; private transactionApi; private accountApi; private bridgeApi; private orderApi; private wallet; private signerType; private nonceManager?; private l1BridgeConfig?; private clientCreated; private nonceCache; private wsOrderClient; private orderBatcher; static readonly ORDER_TYPE_LIMIT = 0; static readonly ORDER_TYPE_MARKET = 1; static readonly ORDER_TIME_IN_FORCE_GOOD_TILL_TIME = 1; static readonly ORDER_TIME_IN_FORCE_IMMEDIATE_OR_CANCEL = 0; static readonly ORDER_TIME_IN_FORCE_FILL_OR_KILL = 2; static readonly TX_TYPE_CHANGE_PUB_KEY = 8; static readonly TX_TYPE_CREATE_SUB_ACCOUNT = 9; static readonly TX_TYPE_CREATE_PUBLIC_POOL = 10; static readonly TX_TYPE_UPDATE_PUBLIC_POOL = 11; static readonly TX_TYPE_TRANSFER = 12; static readonly TX_TYPE_WITHDRAW = 13; static readonly TX_TYPE_CREATE_ORDER = 14; static readonly TX_TYPE_CANCEL_ORDER = 15; static readonly TX_TYPE_CANCEL_ALL_ORDERS = 16; static readonly TX_TYPE_MODIFY_ORDER = 17; static readonly TX_TYPE_MINT_SHARES = 18; static readonly TX_TYPE_BURN_SHARES = 19; static readonly TX_TYPE_UPDATE_LEVERAGE = 20; static readonly ORDER_TYPE_STOP_LOSS = 2; static readonly ORDER_TYPE_STOP_LOSS_LIMIT = 3; static readonly ORDER_TYPE_TAKE_PROFIT = 4; static readonly ORDER_TYPE_TAKE_PROFIT_LIMIT = 5; static readonly ORDER_TYPE_TWAP = 6; static readonly ORDER_TIME_IN_FORCE_POST_ONLY = 2; static readonly CANCEL_ALL_TIF_IMMEDIATE = 0; static readonly CANCEL_ALL_TIF_SCHEDULED = 1; static readonly CANCEL_ALL_TIF_ABORT = 2; static readonly NIL_TRIGGER_PRICE = 0; static readonly DEFAULT_28_DAY_ORDER_EXPIRY = -1; static readonly DEFAULT_IOC_EXPIRY = 0; static readonly DEFAULT_10_MIN_AUTH_EXPIRY = -1; static readonly MINUTE = 60; /** @deprecated Use ApiTransactionStatus.PENDING. */ static readonly TX_STATUS_PENDING = 0; /** @deprecated Use ApiTransactionStatus.PENDING. */ static readonly TX_STATUS_QUEUED = 1; /** @deprecated Use ApiTransactionStatus.EXECUTED for native execution. */ static readonly TX_STATUS_COMMITTED = 2; /** @deprecated Use ApiTransactionStatus.PACKED for this raw value. */ static readonly TX_STATUS_EXECUTED = 3; /** @deprecated Use ApiTransactionStatus.FAILED. Raw 4 means COMMITTED. */ static readonly TX_STATUS_FAILED = 4; /** @deprecated Use ApiTransactionStatus.FAILED. Raw 5 means VERIFIED. */ static readonly TX_STATUS_REJECTED = 5; static readonly CROSS_MARGIN_MODE = 0; static readonly ISOLATED_MARGIN_MODE = 1; /** * Creates a new SignerClient instance * @param config - Configuration object containing API credentials and settings * @param config.url - Lighter Protocol API URL * @param config.privateKey - Private key for signing transactions * @param config.accountIndex - Account index (0 for master account) * @param config.apiKeyIndex - API key index for authentication * @param config.wasmConfig - Optional WASM signer configuration * @param config.logLevel - Optional logging level */ constructor(config: SignerConfig); private initializeOptimizations; private processOrderRequest; private processCancelRequest; /** * Process transaction with automatic retry and nonce recovery */ private processTransactionWithRetry; /** * Check if error is nonce-related */ private isNonceError; /** * Hard refresh nonce from API */ private hardRefreshNonce; /** * Acknowledge transaction failure */ private acknowledgeFailure; /** * Initialize the signer (required for WASM signers) */ initialize(): Promise; ensureWasmClient(): Promise; private validateConfig; checkClient(): string | null; /** * Creates a new order (limit, market, or conditional) * @param params - Order parameters * @param params.marketIndex - Market index (0 for ETH-USD) * @param params.clientOrderIndex - Unique client order identifier * @param params.baseAmount - Order size in base units * @param params.price - Order price (for limit orders) * @param params.isAsk - True for sell orders, false for buy orders * @param params.orderType - Order type (0=limit, 1=market, 2=stop, 3=take_profit) * @param params.timeInForce - Time in force (0=GTC, 1=IOC, 2=FOK) * @param params.reduceOnly - True for reduce-only orders * @param params.triggerPrice - Trigger price for conditional orders * @param params.orderExpiry - Order expiry timestamp (optional) * @param params.nonce - Transaction nonce (optional, auto-fetched if not provided) * @returns Promise resolving to [orderInfo, transactionHash, error] */ createOrder(params: CreateOrderParams): Promise<[any, string, string | null]>; private createOrderOptimized; private getNextNonce; private getNextNonces; /** * Pre-warm the nonce cache for better performance */ preWarmNonceCache(): Promise; /** * Get nonce cache statistics for monitoring */ getNonceCacheStats(): Record | null; createMarketOrder(params: CreateMarketOrderParams): Promise<[any, string, string | null]>; /** * Create market order with maximum slippage limit * Will only execute the amount such that slippage is limited to the value provided */ createMarketOrder_maxSlippage(params: { marketIndex: number; clientOrderIndex: number; baseAmount: number; maxSlippage: number; isAsk: boolean; reduceOnly?: boolean; idealPrice?: number; }): Promise<[any, string, string | null]>; /** * Create market order only if slippage is acceptable * Will only execute if slippage <= max_slippage */ createMarketOrder_ifSlippage(params: { marketIndex: number; clientOrderIndex: number; baseAmount: number; maxSlippage: number; isAsk: boolean; reduceOnly?: boolean; idealPrice?: number; }): Promise<[any, string, string | null]>; cancelOrder(params: CancelOrderParams): Promise<[any, string, string | null]>; /** * Change API key (register new public key) * @param ethSigner - Ethereum signer for L1 signature * @param newPubkey - New public key to register * @returns [txHash, txInfo, error] */ changeApiKey(params: ChangeApiKeyParams): Promise<[any, string, string | null]>; /** * Creates an authentication token with default expiry (10 minutes) * @returns Promise resolving to auth token string */ createAuthToken(): Promise; /** * Creates an authentication token with custom expiry duration * @param expirySeconds - Token expiry duration in seconds (default: 10 minutes) * @returns Promise resolving to auth token string */ createAuthTokenWithExpiry(expirySeconds?: number): Promise; /** * Generate a new API key pair using WASM signer */ generateAPIKey(): Promise<{ privateKey: string; publicKey: string; } | null>; /** * Create a sub account */ createSubAccount(_nonce?: number): Promise<[any, string | null]>; /** * Cancel all orders */ cancelAllOrders(timeInForce: number, time: number, nonce?: number): Promise<[any, any, string | null]>; /** * Close all positions by creating opposite market orders * This method gets all open positions and creates market orders to close them */ closeAllPositions(): Promise<[any[], any[], string[]]>; /** * Create a unified order with optional stop-loss and take-profit orders * Signs all orders individually then sends as batch transaction * Includes comprehensive error handling (acknowledgeFailure on code !== 200) * * @param params - Unified order parameters * @returns Promise resolving to unified order result * * @example * const result = await client.createUnifiedOrder({ * marketIndex: 0, * clientOrderIndex: Date.now(), * baseAmount: 1000000, * isAsk: false, * orderType: OrderType.MARKET, * avgExecutionPrice: 300000, * stopLoss: { triggerPrice: 285000, isLimit: false }, * takeProfit: { triggerPrice: 315000, isLimit: false } * }); */ createUnifiedOrder(params: { marketIndex: number; clientOrderIndex: number; baseAmount: number; isAsk: boolean; orderType: OrderType; price?: number; avgExecutionPrice?: number; maxSlippage?: number; idealPrice?: number; stopLoss?: { triggerPrice: number; price?: number; isLimit?: boolean; }; takeProfit?: { triggerPrice: number; price?: number; isLimit?: boolean; }; reduceOnly?: boolean; timeInForce?: TimeInForce; orderExpiry?: number; }): Promise<{ mainOrder: { tx: any; hash: string; error: string | null; }; stopLoss?: { tx: any; hash: string; error: string | null; }; takeProfit?: { tx: any; hash: string; error: string | null; }; batchResult: { hashes: string[]; errors: string[]; }; success: boolean; message: string; }>; modifyOrder(_marketIndex: number, _orderIndex: number, _baseAmount: number, _price: number, _triggerPrice: number, _nonce?: number): Promise<[any, string, string | null]>; /** * Transfer USDC between accounts (L2-to-L2 transfer) * @param params - Transfer parameters * @returns Promise resolving to [transferInfo, transactionHash, error] */ transfer(params: TransferParams, txInfoCallback?: (data: { txInfo: string; error?: string; }) => Promise): Promise<[any, string, string | null]>; /** * Withdraw USDC from L2 to L1 (L2-to-L1 withdrawal) * @param params - Withdraw parameters * @returns Promise resolving to [withdrawInfo, transactionHash, error] */ withdraw(params: WithdrawParams, txInfoCallback?: (data: { txInfo: string; error?: string; }) => Promise): Promise<[any, string, string | null]>; /** * Update leverage for a specific market * @param marketIndex - Market index to update leverage for * @param marginMode - Margin mode: 0 for CROSS, 1 for ISOLATED * @param leverage - Desired leverage (e.g., 3 for 3x) * @param nonce - Optional nonce (will be fetched automatically if not provided) * @returns Promise resolving to [leverageInfo, transactionHash, error] */ updateLeverage(marketIndex: number, marginMode: number, leverage: number, nonce?: number): Promise<[any, string, string | null]>; /** * Get fast bridge information including limits * @returns Promise */ getFastBridgeInfo(): Promise; /** * Get supported bridge networks * @returns Promise */ getSupportedNetworks(): Promise; /** * Get deposit history for the current account * @param l1Address - L1 address * @param cursor - Pagination cursor * @param filter - Filter criteria * @returns Promise */ getDepositHistory(l1Address: string, cursor?: string, filter?: string): Promise; /** * Get withdraw history for the current account * @param l1Address - L1 address * @param cursor - Pagination cursor * @param filter - Filter criteria * @returns Promise */ getWithdrawHistory(l1Address: string, cursor?: string, filter?: string): Promise; /** * Deposit USDC from L1 to L2 * @param params - L1 deposit parameters * @returns Promise */ depositFromL1(params: L1DepositParams): Promise; /** * Get USDC balance on L1 * @param address - Ethereum address * @returns Promise - Balance in USDC units */ getL1USDCBalance(address: string): Promise; /** * Get USDC allowance for bridge contract * @param address - Ethereum address * @returns Promise - Allowance in USDC units */ getL1USDCAllowance(address: string): Promise; /** * Get L1 transaction status * @param txHash - Transaction hash * @returns Promise */ getL1TransactionStatus(txHash: string): Promise; getTransaction(txHash: string): Promise; waitForTransaction(txHash: string, maxWaitTime?: number, pollInterval?: number): Promise; /** * Get list of subaccounts for the current master account * @returns Array of subaccount indices */ getSubAccounts(): Promise; /** * Check if a specific account index is a subaccount of the current master account * @param accountIndex - Account index to check * @returns True if the account is a subaccount */ isSubAccount(accountIndex: number): Promise; /** * Check if the current account is a master account or subaccount * Master accounts have lower indices (typically < 2^47 - 1) * Subaccounts are created sequentially after their master * @returns Object with isMaster flag and estimated master index */ checkAccountType(): { isMaster: boolean; estimatedMasterIndex: number | null; }; /** * Close the API client connection */ close(): Promise; } //# sourceMappingURL=wasm-signer-client.d.ts.map