import axios, { AxiosInstance } from 'axios'; import { Contract, Signer, Provider, JsonRpcProvider, Wallet } from 'ethers'; import { API_URL, ENDPOINTS, KNOWN_CHAIN_IDS, ENV } from '../constants.js'; import { Pair, TokenInfo, DeploymentInfo, ChainConfig } from '../types/index.js'; import { parseRevertReason } from '../errors.js'; import { DexalotConfig, createConfig, loadConfigFromEnv } from './config.js'; import { WebSocketManager } from '../utils/websocketManager.js'; import { Result } from '../utils/result.js'; import { AsyncRateLimiter } from '../utils/rateLimit.js'; import { AsyncNonceManager } from '../utils/nonceManager.js'; import { ProviderManager } from '../utils/providerManager.js'; import { sanitizeErrorMessage } from '../utils/errorSanitizer.js'; import { asyncRetry, RetryOptions } from '../utils/retry.js'; import { MemoryCache, withInstanceCache, getStaticCache, getSemiStaticCache, getBalanceCache, getOrderbookCache, configureCaches, } from '../utils/cache.js'; import { getLogger, Logger, configureLogging, LogLevel, trackOperation } from '../utils/observability.js'; import { normalizeTokenSymbol, normalizeTradingPair } from '../utils/tokenNormalization.js'; import { ChainResolver, ResolvedChain } from '../utils/chainResolver.js'; /** * HTTP methods accepted by `_apiCall`. The compile-time union on the parameter * is the primary guard; this runtime allowlist is defense-in-depth against * `as any` bypasses and the type-erased `axios.request({ method })` call below. */ const ALLOWED_HTTP_METHODS = new Set(['get', 'post', 'put', 'delete']); export class BaseClient { public signer: Signer | null = null; public provider: Provider | null = null; public subnetProvider: Provider | null = null; /** WebSocket manager when enabled (see CLOBClient subscribeToEvents). */ public _wsManager: WebSocketManager | null = null; public apiBaseUrl: string; public axios: AxiosInstance; // Configuration public config: DexalotConfig; // Utilities (public for mixin access) public _apiRateLimiter: AsyncRateLimiter | null = null; public _rpcRateLimiter: AsyncRateLimiter | null = null; public _nonceManager: AsyncNonceManager | null = null; public _providerManager: ProviderManager | null = null; public _logger: Logger; public _cacheEnabled: boolean; // Caches public _staticCache: MemoryCache; public _semiStaticCache: MemoryCache; public _balanceCache: MemoryCache; public _orderbookCache: MemoryCache; // State public pairs: Record = {}; public tokenData: Record> = {}; public deployments: Record = {}; public chainConfig: Record = {}; public environmentsCache: any[] = []; // Contracts - L1/Subnet public tradePairsContract: Contract | null = null; public portfolioSubContract: Contract | null = null; public portfolioSubContractView: Contract | null = null; // Contracts - Per-Chain Mainnet (dynamically discovered) public portfolioMainContracts: Record = {}; public mainnetRfqContracts: Record = {}; public get portfolioMainAvaxContract(): Contract | null { return this.portfolioMainContracts['Fuji'] || this.portfolioMainContracts['Avalanche'] || Object.values(this.portfolioMainContracts)[0] || null; } // Providers - Per-Chain public connectedChainProviders: Record = {}; // Environment - discovered dynamically public env: string = ''; public subnetEnv: string = ''; public chainId: number = 0; public subnetChainId: number | null = null; public parentEnv: string = ''; /** * Create a new BaseClient. * @param configOrSigner - DexalotConfig, Signer, or API URL string * @param baseUrl - Optional API base URL (only used if first arg is Signer) */ constructor(configOrSigner?: DexalotConfig | Signer | string, baseUrl?: string) { // Determine configuration if (configOrSigner && typeof configOrSigner === 'object' && 'parentEnv' in configOrSigner) { // DexalotConfig provided — merge with defaults and validate this.config = createConfig(configOrSigner as Partial); this.parentEnv = this.config.parentEnv; this.apiBaseUrl = this.config.apiBaseUrl || API_URL.TESTNET; this._setupSignerFromPrivateKey(); } else if (typeof configOrSigner === 'string') { this.config = createConfig(); this.parentEnv = this.config.parentEnv; this.apiBaseUrl = configOrSigner; } else if (configOrSigner) { this.config = createConfig(); this.signer = configOrSigner; this.parentEnv = this.config.parentEnv; const network = this.parentEnv.toLowerCase().includes('production') ? 'MAINNET' : 'TESTNET'; this.apiBaseUrl = baseUrl || API_URL[network]; if (this.signer.provider) { this.provider = this.signer.provider; } } else { // No arguments - load from environment this.config = loadConfigFromEnv(); this.parentEnv = this.config.parentEnv; this.apiBaseUrl = this.config.apiBaseUrl || API_URL.TESTNET; this._setupSignerFromPrivateKey(); } // Initialize logger configureLogging(this.config.logLevel as LogLevel, this.config.logFormat as 'console' | 'json'); this._logger = getLogger('dexalot_sdk.base'); // Caches are module-level singletons shared across all client // instances; this constructor merely applies the per-instance // TTL overrides (mutating the singleton in place) and stores // references for the existing call sites and `invalidateCache`. // The previous per-instance `new MemoryCache(...)` calls also // double-converted seconds-to-ms, so caches effectively never // expired; module-level singletons fix that too. this._cacheEnabled = this.config.cacheEnabled; configureCaches({ cacheTtlStatic: this.config.cacheTtlStatic, cacheTtlSemiStatic: this.config.cacheTtlSemiStatic, cacheTtlBalance: this.config.cacheTtlBalance, cacheTtlOrderbook: this.config.cacheTtlOrderbook, }); this._staticCache = getStaticCache(); this._semiStaticCache = getSemiStaticCache(); this._balanceCache = getBalanceCache(); this._orderbookCache = getOrderbookCache(); // Initialize rate limiters if (this.config.rateLimitEnabled) { this._apiRateLimiter = new AsyncRateLimiter(this.config.rateLimitRequestsPerSecond); this._rpcRateLimiter = new AsyncRateLimiter(this.config.rateLimitRpcPerSecond); } // Initialize nonce manager if (this.config.nonceManagerEnabled) { this._nonceManager = new AsyncNonceManager(); } // Initialize provider manager if (this.config.providerFailoverEnabled) { this._providerManager = new ProviderManager({ failoverCooldown: this.config.providerFailoverCooldown * 1000, maxFailures: this.config.providerFailoverMaxFailures, }); } // Initialize axios (read timeout matches Python aiohttp ClientTimeout total) this.axios = axios.create({ baseURL: this.apiBaseUrl, timeout: this.config.timeoutRead * 1000, }); } /** * Construct a Wallet from `config.privateKey` and immediately clear the key * from config in both the success and failure paths. Once the Wallet exists * the raw key should no longer live in the in-memory config. Callers that * pass a pre-built `Signer` never populate `config.privateKey`, so this * helper is only invoked from the config / env-load constructor branches. */ private _setupSignerFromPrivateKey(): void { const pk = this.config.privateKey; if (!pk) return; try { this.signer = new Wallet(pk); } finally { this.config.privateKey = undefined; } } /** * Reject http:// RPC URLs unless `allowInsecureRpc` is enabled. */ public _rejectInsecureRpcUrls(urls: string[]): string[] { const insecure = urls.filter(u => u.toLowerCase().startsWith('http://')); if (insecure.length > 0 && !this.config.allowInsecureRpc) { throw new Error( `Insecure RPC URL(s) rejected (http://): ${insecure.join(', ')}. ` + 'Set allowInsecureRpc=true or DEXALOT_ALLOW_INSECURE_RPC=true to permit http:// endpoints.' ); } return urls; } /** * Resolve RPC URL list: env override DEXALOT_RPC_{chainId} / DEXALOT_RPC_{SYMBOL}, else API value (comma-separated). */ public _getRpcUrls( chainId: number | undefined, nativeSymbol: string | undefined, apiRpc: string | undefined ): string[] { const env = typeof process !== 'undefined' && process.env ? process.env : ({} as NodeJS.ProcessEnv); if (chainId !== undefined && chainId !== null) { const envRpc = env[`DEXALOT_RPC_${chainId}`]; if (envRpc) { const urls = envRpc.split(',').map(u => u.trim()).filter(Boolean); return this._rejectInsecureRpcUrls(urls); } } if (nativeSymbol) { const envRpc = env[`DEXALOT_RPC_${nativeSymbol.toUpperCase()}`]; if (envRpc) { const urls = envRpc.split(',').map(u => u.trim()).filter(Boolean); return this._rejectInsecureRpcUrls(urls); } } if (apiRpc) { const urls = apiRpc.split(',').map(u => u.trim()).filter(Boolean); return this._rejectInsecureRpcUrls(urls); } return []; } /** * Sanitize error message to prevent information leaks. */ public _sanitizeError(error: Error | unknown, context: string): string { const err = error instanceof Error ? error : new Error(String(error)); // First lift any contract revert reason code (e.g. T-FOKF-01) to a // friendly ": " string via the shared error catalog, // then sanitize (the code itself is preserved by the sanitizer). // Error sanitization must never itself throw, so revert-code lifting is // best-effort: any failure falls through to plain sanitization. try { const parsed = parseRevertReason(err.message); if (parsed !== err.message) { return sanitizeErrorMessage(parsed, context); } } catch { // fall through to plain sanitization } return sanitizeErrorMessage(err, context); } /** * Make an API call with rate limiting and retry. * * On failure, lifts backend `reasonCode` + `reason` from the axios * response body (when present) into the thrown Error's `message`. * The Dexalot REST API encodes failures as * `{ reasonCode: "FQ-015", reason: "..." }` (also tolerates the * snake_case `reason_code` and the alternate `message` field that * some endpoints emit). Without this lift the raw axios message * collapses everything to `"Request failed with status code N"`, * which swallows the backend-level reason and makes user-visible * `Result.fail` strings useless for diagnosis. */ public async _apiCall( method: 'get' | 'post' | 'put' | 'delete', url: string, options?: { params?: any; data?: any; headers?: any } ): Promise { if (typeof method !== 'string' || !ALLOWED_HTTP_METHODS.has(method.toLowerCase())) { throw new Error(`Invalid HTTP method: ${String(method)}`); } // Rate limiting if (this._apiRateLimiter) { await this._apiRateLimiter.acquire(); } // Build the request function const makeRequest = async (): Promise => { const response = await this.axios.request({ method, url, ...options, }); return response.data; }; try { // Apply retry if enabled if (this.config.retryEnabled) { const retryOpts: RetryOptions = { maxAttempts: this.config.retryMaxAttempts, initialDelay: this.config.retryInitialDelay * 1000, maxDelay: this.config.retryMaxDelay * 1000, exponentialBase: this.config.retryExponentialBase, retryOnStatus: this.config.retryOnStatus, retryOnExceptions: this.config.retryOnExceptions, }; return await asyncRetry(makeRequest, retryOpts)(); } return await makeRequest(); } catch (e) { if ( axios.isAxiosError(e) && e.response?.data && typeof e.response.data === 'object' ) { const body = e.response.data as Record; const reasonCode = (body.reasonCode ?? body.reason_code) as | string | undefined; const reason = (body.reason ?? body.message) as string | undefined; if (typeof reasonCode === 'string') { const tail = typeof reason === 'string' ? reason : e instanceof Error ? e.message : String(e); throw new Error(`${reasonCode}: ${tail}`); } if (typeof reason === 'string') { throw new Error(reason); } } throw e; } } public getRevertReason(error: any): string { return parseRevertReason(error); } /** * Load environments, tokens, RFQ pairs, deployments, and CLOB pairs into the client. */ public async initializeClient(): Promise> { return trackOperation( this._logger, 'initializeClient', async () => { // Fetch environments first (sets providers needed for deployments) await this._fetchEnvironments(); // Then fetch other data in parallel await Promise.all([ this._fetchTokens(), this._fetchRfqPairs(), this._fetchDeployments(), this._fetchClobPairs(), ]); return Result.ok('Client initialized with all configurations.'); }, { parentEnv: this.parentEnv } ).catch((error) => { const msg = this._sanitizeError(error, 'initializing client'); return Result.fail(msg); }); } /** * Explicit open hook; axios is already created in the constructor, so this resolves immediately. */ public async connect(): Promise { return Promise.resolve(); } /** * Transform API token response to match standardized field names. * Maps lowercase/snake_case API fields to camelCase SDK fields. * Preserves existing camelCase fields if present, otherwise transforms from alternative formats. */ private _transformTokenFromAPI(token: any): any { const transformed: any = { ...token }; // Transform evmDecimals: prefer existing camelCase, fallback to lowercase/snake_case if (!transformed.evmDecimals) { transformed.evmDecimals = token.evmdecimals || token.evm_decimals || token.decimals; } // Transform chainId: prefer existing camelCase, fallback to lowercase/snake_case if (!transformed.chainId) { transformed.chainId = token.chainid || token.chain_id; } // Transform network: prefer existing, fallback to chain_display_name if (!transformed.network) { transformed.network = token.chain_display_name; } return transformed; } /** * Transform API environment response to match standardized field names. * Maps lowercase/snake_case API fields to camelCase SDK fields. * Preserves existing camelCase fields if present, otherwise transforms from alternative formats. */ private _transformEnvironmentFromAPI(env: any): any { const transformed: any = { ...env }; // Transform chainId: prefer existing camelCase, fallback to lowercase/snake_case if (!transformed.chainId) { transformed.chainId = env.chainid || env.chain_id; } // Transform envType: prefer existing camelCase, fallback to snake_case/lowercase if (!transformed.envType) { transformed.envType = env.env_type || env.type; } // Transform rpc: prefer existing, fallback to chain_instance if (!transformed.rpc) { transformed.rpc = env.chain_instance; } // Transform network: prefer existing, fallback to chain_display_name if (!transformed.network) { transformed.network = env.chain_display_name; } return transformed; } /** * Transform API deployment response to match standardized field names. * Maps lowercase/camelCase API fields to lowercase SDK fields. * Preserves existing lowercase fields if present, otherwise transforms from alternative formats. */ private _transformDeploymentFromAPI(item: any): any { const transformed: any = { ...item }; // Transform env: prefer existing lowercase, fallback to variations if (!transformed.env) { transformed.env = item.Env || item.environment; } // Transform address: prefer existing lowercase, fallback to variations if (!transformed.address) { transformed.address = item.Address || item.contractAddress; } // Transform abi: prefer existing lowercase, fallback to variations // Note: ABI can be an array or nested object, so we preserve the structure if (!transformed.abi) { transformed.abi = item.Abi || item.ABI; } return transformed; } public async _fetchEnvironments(): Promise { try { const environments = await this._apiCall('get', ENDPOINTS.TRADING_ENVIRONMENTS); // Transform environments and store in cache this.environmentsCache = environments.map(env => this._transformEnvironmentFromAPI(env)); for (const env of environments) { const chainId = env.chainid || env.chain_id; const envType = env.env_type || env.type; const envString = env.env; const rpc = env.rpc || env.chain_instance; const name = env.network || env.chain_display_name; // Process subnet environments if (envType === 'subnet') { this.subnetChainId = chainId; this.subnetEnv = envString; const subnetNative = env.native_token_symbol || 'ALOT'; const rpcUrls = this._getRpcUrls(chainId, subnetNative, rpc); if (rpcUrls.length > 0) { const primaryRpc = rpcUrls[0]; try { if (this._providerManager) { this._providerManager.addProviders('DEXALOT_L1', rpcUrls); const primary = this._providerManager.getProvider('DEXALOT_L1'); this.subnetProvider = (primary as JsonRpcProvider) ?? new JsonRpcProvider(primaryRpc); } else { this.subnetProvider = new JsonRpcProvider(primaryRpc); } if (!this.provider) { this.provider = this.subnetProvider; } } catch (e) { this._logger.warn('Failed to init subnet provider', { error: String(e) }); } } // Ensure Signer is connected to subnet Provider if (this.signer && !this.signer.provider && this.provider) { try { this.signer = this.signer.connect(this.provider); } catch (e) { // Ignore if signer cannot be re-connected } } } // Process mainnet environments if (envType === 'mainnet' && name) { const nativeSymbol = env.native_token_symbol || 'ETH'; this.chainConfig[name] = { chain_id: chainId, rpc: rpc, explorer: env.explorer, native_symbol: nativeSymbol, env: envString }; const rpcUrls = this._getRpcUrls(chainId, nativeSymbol, rpc); if (rpcUrls.length > 0) { try { const primaryRpc = rpcUrls[0]; if (this._providerManager) { this._providerManager.addProviders(name, rpcUrls); const primary = this._providerManager.getProvider(name); this.connectedChainProviders[name] = (primary as JsonRpcProvider) ?? new JsonRpcProvider(primaryRpc); } else { this.connectedChainProviders[name] = new JsonRpcProvider(primaryRpc); } } catch (e) { this._logger.warn(`Failed to init provider for ${name}`, { error: String(e) }); } } // Set primary chainId/env if (!this.chainId || chainId === KNOWN_CHAIN_IDS.AVAX_MAINNET || chainId === KNOWN_CHAIN_IDS.AVAX_FUJI) { this.chainId = chainId; this.env = envString; } } } } catch (e) { this._logger.error('Error fetching environments', { error: this._sanitizeError(e, 'fetching environments') }); } } public async _fetchTokens(): Promise { try { const tokens = await this._apiCall('get', ENDPOINTS.TRADING_TOKENS); for (const t of tokens) { if (!this.tokenData[t.symbol]) { this.tokenData[t.symbol] = {}; } const decimals = t.evmdecimals !== undefined ? t.evmdecimals : 18; this.tokenData[t.symbol][t.env] = { address: t.address, symbol: t.symbol, name: t.name, decimals: decimals, chainId: t.chainid || t.chain_id || 0, env: t.env }; } } catch (e) { this._logger.error('Error fetching tokens', { error: this._sanitizeError(e, 'fetching tokens') }); } } /** * Fetch RFQ pairs for all configured chains. * Stores results in this.rfqPairs[chainId] (from SwapMixin). */ private async _fetchRfqPairs(): Promise { try { // Initialize rfqPairs if not already present (may be in SwapMixin) if (!(this as any).rfqPairs) { (this as any).rfqPairs = {}; } const fetchTasks: Promise[] = []; // Fetch RFQ pairs for each chain in parallel for (const [chainName, config] of Object.entries(this.chainConfig)) { const chainId = config.chain_id; if (chainId) { fetchTasks.push( this._fetchRfqPairsForChain(chainId, chainName) ); } } // Also fetch for Avalanche mainnet if not already in chainConfig const avaxMainnetId = KNOWN_CHAIN_IDS.AVAX_MAINNET; const hasAvaxMainnet = Object.values(this.chainConfig).some( config => config.chain_id === avaxMainnetId ); if (!hasAvaxMainnet) { fetchTasks.push( this._fetchRfqPairsForChain(avaxMainnetId, 'Avalanche') ); } if (fetchTasks.length > 0) { await Promise.all(fetchTasks); } } catch (e) { this._logger.warn('Error fetching RFQ pairs', { error: this._sanitizeError(e, 'fetching RFQ pairs') }); } } /** * Fetch RFQ pairs for a specific chain. */ private async _fetchRfqPairsForChain(chainId: number, chainName: string): Promise { try { const data = await this._apiCall('get', ENDPOINTS.RFQ_PAIRS, { params: { chainid: chainId } }); (this as any).rfqPairs[chainId] = data; } catch (e) { // Chains without an RFQ deployment legitimately return 404 here; // logging at warn would create noise on every initialize. Keep the // signal at debug — the failure is recoverable and the caller can // still operate against chains that do have RFQ. this._logger.debug('RFQ pairs unavailable for chain', { chainId, chainName, error: this._sanitizeError(e, `fetching RFQ pairs for chain ${chainId}`) }); } } /** * Fetch CLOB pairs if getClobPairs method is available. * * This is a wrapper around getClobPairs() to make it consistent * with other _fetch_* methods that handle errors internally. */ private async _fetchClobPairs(): Promise { try { // Check if getClobPairs method exists (from CLOBMixin) if (typeof (this as any).getClobPairs === 'function') { const result = await (this as any).getClobPairs(); if (!result.success) { throw new Error(`Failed to fetch CLOB pairs: ${result.error}`); } } else { this._logger.warn('getClobPairs method not available, skipping CLOB pairs fetch'); } } catch (e) { this._logger.warn('Error fetching CLOB pairs', { error: this._sanitizeError(e, 'fetching CLOB pairs') }); // Don't throw - allow initialization to continue } } public async _fetchDeployments(): Promise { await this._fetchContractDeployment('TradePairs'); await this._fetchContractDeployment('Portfolio'); await this._fetchContractDeployment('MainnetRFQ'); // The RFQ router is newer than the other contract types; a backend // that does not publish it only logs (errors are caught below) and // the swap path falls back to MainnetRFQ.trustedForwarder() on-chain. await this._fetchContractDeployment('DexalotRouter'); } public async _fetchContractDeployment(contractType: string): Promise { try { const items = await this._apiCall('get', ENDPOINTS.TRADING_DEPLOYMENT, { params: { contracttype: contractType, returnabi: 'true' } }); for (const item of items) { // Transform deployment item to standardized field names const transformed = this._transformDeploymentFromAPI(item); const envString = transformed.env; // Parse ABI let abi: any[] = []; if (transformed.abi) { if (Array.isArray(transformed.abi)) abi = transformed.abi; else if (transformed.abi.abi) abi = transformed.abi.abi; } const address = transformed.address; // Store raw deployment if (!this.deployments[contractType]) this.deployments[contractType] = {}; this.deployments[contractType][envString] = { address, abi }; // Initialize contracts based on type const runner = this.signer || this.provider; if (contractType === 'TradePairs') { if (envString === this.subnetEnv || envString === ENV.PROD_MULTI_SUBNET || envString === ENV.FUJI_MULTI_SUBNET) { if (runner && address) { this.tradePairsContract = new Contract(address, abi, runner); } } } else if (contractType === 'Portfolio') { if (envString === this.subnetEnv || envString === ENV.PROD_MULTI_SUBNET || envString === ENV.FUJI_MULTI_SUBNET) { this.deployments['PortfolioSub'] = { address, abi }; if (runner && address) { this.portfolioSubContract = new Contract(address, abi, runner); } if (this.subnetProvider && address) { this.portfolioSubContractView = new Contract(address, abi, this.subnetProvider); } } else { const chainName = this._getChainNameFromEnv(envString); if (chainName && address) { const provider = this.connectedChainProviders[chainName]; if (!this.deployments['PortfolioMain']) this.deployments['PortfolioMain'] = {}; this.deployments['PortfolioMain'][chainName] = { address, abi }; if (provider) { this.portfolioMainContracts[chainName] = new Contract(address, abi, provider); } } } } else if (contractType === 'MainnetRFQ') { const chainName = this._getChainNameFromEnv(envString); if (chainName && address) { this.deployments['MainnetRFQ'][chainName] = { address, abi }; const provider = this.connectedChainProviders[chainName]; if (provider) { this.mainnetRfqContracts[chainName] = new Contract(address, abi, provider); } } } else if (contractType === 'DexalotRouter') { const chainName = this._getChainNameFromEnv(envString); if (chainName && address) { this.deployments['DexalotRouter'][chainName] = { address, abi }; } } } } catch (e) { this._logger.error(`Error fetching deployment for ${contractType}`, { error: this._sanitizeError(e, `fetching ${contractType} deployment`) }); } } // --- Helper Methods --- public _getChainNameFromEnv(envString: string): string | null { const envLower = envString.toLowerCase(); for (const [chainName, config] of Object.entries(this.chainConfig)) { if (config.env === envString) { return chainName; } if (envLower.includes(chainName.toLowerCase())) { return chainName; } } if (envLower.includes('fuji')) return 'Fuji'; if (envLower.includes('avax') || envLower.includes('avalanche')) return 'Avalanche'; return null; } public _resolveChainId(identifier: string | number): number | null { if (typeof identifier === 'number') return identifier; const config = this.chainConfig[identifier]; if (config) return config.chain_id; for (const [name, cfg] of Object.entries(this.chainConfig)) { if (name.toLowerCase() === identifier.toLowerCase()) { return cfg.chain_id; } } return null; } public _getChainNameFromId(chainId: number): string | null { for (const [name, config] of Object.entries(this.chainConfig)) { if (config.chain_id === chainId) { return name; } } return null; } /** * Get token decimals for a symbol on a chain. */ public _getTokenDecimals(symbol: string, chainId: number): number | null { const tokenEnvs = this.tokenData[symbol]; if (!tokenEnvs) return null; for (const info of Object.values(tokenEnvs)) { if (info.chainId === chainId) { return info.decimals; } } return null; } /** * Fetch and return the list of environments. * Cached for 1 hour (static data). */ public async getEnvironments(): Promise> { const cachedFn = withInstanceCache( this, this._staticCache, 'getEnvironments', async (): Promise> => { try { const data = await this._apiCall('get', ENDPOINTS.TRADING_ENVIRONMENTS); // Transform environments before storing and returning const transformed = data.map(env => this._transformEnvironmentFromAPI(env)); this.environmentsCache = transformed; return Result.ok(transformed); } catch (e) { if (this.environmentsCache.length > 0) { // Return cached transformed data return Result.ok(this.environmentsCache); } return Result.fail(this._sanitizeError(e, 'fetching environments')); } } ); return cachedFn(); } /** * Map of chain IDs to network display names from the environments API (static cache tier). */ public async getChains(): Promise>> { const cachedFn = withInstanceCache( this, this._staticCache, 'getChains', async (): Promise>> => { const envsResult = await this.getEnvironments(); if (!envsResult.success) { return Result.fail( `Failed to fetch environments: ${envsResult.error}` ); } const chains: Record = {}; for (const env of envsResult.data || []) { const cid = env.chainId ?? env.chain_id; const name = env.network; if (cid != null && cid !== '') { const id = typeof cid === 'number' ? cid : Number(cid); if (!Number.isNaN(id)) { chains[id] = name ?? ''; } } } return Result.ok(chains); } ); return cachedFn(); } /** * Assign the signer and rebuild cached contract instances to use it as the transaction runner. */ public async setSigner(newSigner: Signer): Promise> { this.signer = newSigner; if (newSigner.provider) { this.provider = newSigner.provider; } return Promise.resolve(this._reconnectContractsForSigner()); } /** * Rebuild subnet/mainnet contract instances for the current signer. */ private _reconnectContractsForSigner(): Result { try { const runner = this.signer; if (!runner) { return Result.fail('Signer not configured.'); } // Reconnect subnet contracts if (this.tradePairsContract && this.deployments['TradePairs']) { const subnetDeploy = Object.values(this.deployments['TradePairs'])[0] as DeploymentInfo; if (subnetDeploy) { this.tradePairsContract = new Contract(subnetDeploy.address, subnetDeploy.abi, runner); } } if (this.deployments['PortfolioSub']) { const subDeploy = this.deployments['PortfolioSub'] as DeploymentInfo; if (subDeploy) { this.portfolioSubContract = new Contract(subDeploy.address, subDeploy.abi, runner); } } // Reconnect mainnet contracts if (this.deployments['PortfolioMain']) { for (const [chainName, deployment] of Object.entries(this.deployments['PortfolioMain'])) { const deploy = deployment as DeploymentInfo; this.portfolioMainContracts[chainName] = new Contract(deploy.address, deploy.abi, runner); } } if (this.deployments['MainnetRFQ']) { for (const [chainName, deployment] of Object.entries(this.deployments['MainnetRFQ'])) { const deploy = deployment as DeploymentInfo; this.mainnetRfqContracts[chainName] = new Contract(deploy.address, deploy.abi, runner); } } this._logger.debug('Signer updated and contracts reconnected'); return Result.ok('Signer updated successfully'); } catch (error) { return Result.fail(this._sanitizeError(error, 'updating signer')); } } /** * Get list of available tokens on Dexalot. * Cached for 15 minutes (semi-static data). */ public async getTokens(): Promise> { const cachedFn = withInstanceCache( this, this._semiStaticCache, 'getTokens', async (): Promise> => { try { const mainnetChainIds = new Set(); for (const config of Object.values(this.chainConfig)) { if (config.chain_id) { mainnetChainIds.add(config.chain_id); } } if (Object.keys(this.tokenData).length > 0) { const uniqueTokens: any[] = []; const seenSymbols = new Set(); for (const [symbol, envData] of Object.entries(this.tokenData)) { if (seenSymbols.has(symbol)) continue; for (const [envKey, tokenInfo] of Object.entries(envData)) { const token = tokenInfo as TokenInfo; const chainId = token.chainId || 0; if (chainId && mainnetChainIds.has(chainId)) { // tokenData already has standardized format (from _fetchTokens) uniqueTokens.push({ symbol: symbol, name: token.name || symbol, decimals: token.decimals || 18, address: token.address, chain: this._getChainNameFromId(chainId) || '', chain_id: chainId, }); seenSymbols.add(symbol); break; } } } return Result.ok(uniqueTokens); } const tokens = await this._apiCall('get', ENDPOINTS.TRADING_TOKENS); // Transform tokens before processing const transformedTokens = tokens.map(token => this._transformTokenFromAPI(token)); const uniqueTokens: any[] = []; const seenSymbols = new Set(); for (const token of transformedTokens) { const symbol = token.symbol; const chainId = token.chainId || 0; if (symbol && !seenSymbols.has(symbol) && chainId) { if (mainnetChainIds.has(chainId)) { uniqueTokens.push({ symbol: symbol, name: token.name || symbol, decimals: token.evmDecimals || token.decimals || 18, address: token.address, chain: token.network || '', chain_id: chainId, }); seenSymbols.add(symbol); } } } return Result.ok(uniqueTokens); } catch (e) { return Result.fail(this._sanitizeError(e, 'fetching tokens')); } } ); return cachedFn(); } public getConnectedChains(): string[] { return Object.keys(this.chainConfig); } /** * Get deployment configuration from the REST API. * Cached for 1 hour (static data). * * Backward-compatible: no-args call still works and uses defaults * (`env = config.parentEnv`, `contracttype = 'All'`, `returnabi = true`). * The backend expects lowercase query param names (`contracttype`, * `returnabi`), not the TS camelCase form on the opts object. * * The cache key includes all three resolved params so filter * variants do not collide on the same static-cache slot. */ public async getDeployment(opts?: { env?: string; contractType?: | 'All' | 'Portfolio' | 'TradePairs' | 'MainnetRFQ' | 'PortfolioMain' | 'PortfolioSub' | 'OrderBooks' | string; returnAbi?: boolean; }): Promise> { const env = opts?.env ?? this.config.parentEnv; const contracttype = opts?.contractType ?? 'All'; const returnabi = opts?.returnAbi ?? true; const cachedFn = withInstanceCache( this, this._staticCache, `getDeployment|${env}|${contracttype}|${returnabi}`, async (): Promise> => { try { const data = await this._apiCall( 'get', ENDPOINTS.TRADING_DEPLOYMENT, { params: { env, contracttype, returnabi } } ); return Result.ok(data); } catch (e) { return Result.fail(this._sanitizeError(e, 'fetching deployment')); } } ); return cachedFn(); } public getSubnetNetworkInfo(): { chainId: number; rpc: string; name: string } | null { if (!this.subnetChainId) return null; const envData = this.environmentsCache.find((e: any) => e.envType === 'subnet'); return { chainId: this.subnetChainId, rpc: envData?.rpc || '', name: envData?.network || 'Dexalot Subnet' }; } /** * Reinitialize all client configuration data. * * Refreshes all data loaded during `initializeClient()`: * - Environments (chainConfig, providers, chainId, subnetChainId, env) * - Tokens (tokenData) * - RFQ pairs (rfqPairs) * - Deployments (deployments, contract instances) * - CLOB pairs (pairs) * * @param forceRefresh - If true, clears relevant caches before reinitializing. * This ensures fresh data is fetched even if cache TTL hasn't expired. * @returns Result with success message on success, or error message on failure */ public async reinitialize(forceRefresh: boolean = false): Promise> { return trackOperation( this._logger, 'reinitialize', async () => { // Clear caches if force_refresh is requested if (forceRefresh) { this.invalidateCache('static'); this.invalidateCache('semi_static'); } // Fetch environments first (sets providers needed for deployments) await this._fetchEnvironments(); // Then fetch other data in parallel await Promise.all([ this._fetchTokens(), this._fetchRfqPairs(), this._fetchDeployments(), this._fetchClobPairs(), ]); return Result.ok('Client reinitialized with all configurations.'); }, { parentEnv: this.parentEnv, forceRefresh } ).catch((error) => { const msg = this._sanitizeError(error, 'reinitializing client'); return Result.fail(msg); }); } /** * Invalidate cache entries. * * @param level - Cache level to invalidate, or 'all' for all caches */ public invalidateCache(level: 'static' | 'semi_static' | 'balance' | 'orderbook' | 'all' = 'all'): void { switch (level) { case 'static': this._staticCache.clear(); break; case 'semi_static': this._semiStaticCache.clear(); break; case 'balance': this._balanceCache.clear(); break; case 'orderbook': this._orderbookCache.clear(); break; case 'all': this._staticCache.clear(); this._semiStaticCache.clear(); this._balanceCache.clear(); this._orderbookCache.clear(); break; } } // --- Token & Chain Normalization --- /** * Normalize a user-supplied token symbol (strip, uppercase, apply alias map). */ public normalizeToken(token: string): string { return normalizeTokenSymbol(token); } /** * Normalize a user-supplied trading pair (e.g., "eth/usdc" -> "ETH/USDC"). */ public normalizePair(pair: string): string { return normalizeTradingPair(pair); } /** * Resolve a human-friendly chain alias to the canonical connected chain. */ public resolveChainReference(chainReference: string | number, includeDexalotL1: boolean = false): Result { const resolver = new ChainResolver( this.chainConfig as any, this.chainId || null, this.subnetChainId ); return resolver.resolve(chainReference, includeDexalotL1); } /** * Map user-facing chain name to ProviderManager registry key (`Dexalot L1` → `DEXALOT_L1`). */ public _providerManagerChainKey(chainDisplayName: string): string { return chainDisplayName === 'Dexalot L1' ? 'DEXALOT_L1' : chainDisplayName; } /** * Current JsonRpcProvider for a chain: ProviderManager selection first, else subnet / connected map. */ public getProviderForChain(chainDisplayName: string): JsonRpcProvider | null { const key = this._providerManagerChainKey(chainDisplayName); if (this._providerManager) { const p = this._providerManager.getProvider(key); if (p) { return p as JsonRpcProvider; } } if (chainDisplayName === 'Dexalot L1') { return (this.subnetProvider as JsonRpcProvider) ?? null; } return this.connectedChainProviders[chainDisplayName] ?? null; } /** Whether balance-style RPC can be attempted for this chain display name. */ public isChainRpcAvailable(chainDisplayName: string): boolean { if (chainDisplayName === 'Dexalot L1') { return ( this.subnetProvider != null || (!!this._providerManager && this._providerManager.getProviderCount('DEXALOT_L1') > 0) ); } return ( chainDisplayName in this.connectedChainProviders || (!!this._providerManager && this._providerManager.getProviderCount(chainDisplayName) > 0) ); } /** * Connected mainnet-style chain names plus any chain_config entry that has providers registered. */ public getAvailableChainNames(): string[] { const chains = new Set(Object.keys(this.connectedChainProviders)); if (this._providerManager) { for (const chainName of Object.keys(this.chainConfig)) { if (this._providerManager.getProviderCount(chainName) > 0) { chains.add(chainName); } } } return Array.from(chains); } /** * Display name for the Dexalot subnet used as ProviderManager key `DEXALOT_L1`. */ protected _dexalotL1DisplayName(): string { return 'Dexalot L1'; } protected _tradePairsDeployment(): { address: string; abi: any[] } | null { const d = this.deployments['TradePairs']; if (!d || typeof d !== 'object') return null; const first = Object.values(d)[0] as { address?: string; abi?: unknown }; if (!first?.address) return null; const abi = Array.isArray(first.abi) ? first.abi : []; return { address: first.address, abi }; } protected _portfolioSubDeployment(): { address: string; abi: any[] } | null { const d = this.deployments['PortfolioSub'] as { address?: string; abi?: unknown } | undefined; if (!d?.address) return null; const abi = Array.isArray(d.abi) ? d.abi : []; return { address: d.address, abi }; } protected _portfolioMainDeployment( chainName: string ): { address: string; abi: any[] } | null { const m = this.deployments['PortfolioMain'] as Record | undefined; const dep = m?.[chainName]; if (!dep?.address) return null; const abi = Array.isArray(dep.abi) ? dep.abi : []; return { address: dep.address, abi }; } protected _mainnetRfqDeployment( chainName: string ): { address: string; abi: any[] } | null { const m = this.deployments['MainnetRFQ'] as Record | undefined; const dep = m?.[chainName]; if (!dep?.address) return null; const abi = Array.isArray(dep.abi) ? dep.abi : []; return { address: dep.address, abi }; } /** * `DexalotRouter` deployment published by the deployments endpoint for a * connected chain, or `null` when the backend did not list it. */ protected _dexalotRouterDeployment( chainName: string ): { address: string; abi: any[] } | null { const m = this.deployments['DexalotRouter'] as Record | undefined; const dep = m?.[chainName]; if (!dep?.address) return null; const abi = Array.isArray(dep.abi) ? dep.abi : []; return { address: dep.address, abi }; } /** Signed contract on a specific RPC (failover-aware). */ protected _contractForSigner( provider: JsonRpcProvider, address: string, abi: any[] ): Contract { const signer = this.signer; if (!signer) { throw new Error('Signer required'); } try { return new Contract(address, abi, signer.connect(provider)); } catch (e: unknown) { // Browser/injected signers (e.g. Privy, MetaMask) cannot reconnect to an arbitrary JsonRpcProvider. // Use the signer's own provider so L1 txs broadcast through the wallet after the correct chain switch. const code = e !== null && typeof e === 'object' && 'code' in e ? String((e as { code?: unknown }).code) : ''; const message = e instanceof Error ? e.message : String(e); const unsupported = code === 'UNSUPPORTED_OPERATION' || message.includes('UNSUPPORTED_OPERATION') || message.includes('cannot reconnect'); if (unsupported && signer.provider) { return new Contract(address, abi, signer); } throw e; } } /** Read-only contract for view calls on a specific RPC. */ protected _contractReadOnly(provider: JsonRpcProvider, address: string, abi: any[]): Contract { return new Contract(address, abi, provider); } protected _rpcRetryOptions(): RetryOptions { return { maxAttempts: this.config.retryMaxAttempts, initialDelay: this.config.retryInitialDelay * 1000, maxDelay: this.config.retryMaxDelay * 1000, exponentialBase: this.config.retryExponentialBase, retryOnStatus: this.config.retryOnStatus, retryOnNetworkError: true, }; } protected async acquireRpcRateLimiter(): Promise { if (this._rpcRateLimiter) { await this._rpcRateLimiter.acquire(); } } /** * Run an RPC operation with per-provider retry and failover across registered URLs. */ public async withRpcFailover( chainDisplayName: string, op: (provider: JsonRpcProvider) => Promise ): Promise { const key = this._providerManagerChainKey(chainDisplayName); const pm = this._providerManager; const count = pm ? pm.getProviderCount(key) : 0; const useFailover = !!pm && this.config.providerFailoverEnabled && count > 0; const runWithRetry = async (p: JsonRpcProvider) => { if (this.config.retryEnabled) { const wrapped = asyncRetry(async () => op(p), this._rpcRetryOptions()); return wrapped(); } return op(p); }; if (!useFailover) { const p = this.getProviderForChain(chainDisplayName); if (!p) { throw new Error(`No RPC provider for chain '${chainDisplayName}'`); } await this.acquireRpcRateLimiter(); return runWithRetry(p); } let lastError: unknown; for (let attempt = 0; attempt < count; attempt++) { const prov = pm!.getProvider(key); if (!prov) { break; } const idx = pm!.getProviderIndex(key, prov) ?? 0; try { await this.acquireRpcRateLimiter(); const result = await runWithRetry(prov as JsonRpcProvider); pm!.markSuccess(key, idx); return result; } catch (e) { lastError = e; pm!.markFailure(key, idx); } } if (lastError instanceof Error) { throw lastError; } throw new Error( `All RPC providers failed for chain '${chainDisplayName}'` + (lastError !== undefined ? `: ${String(lastError)}` : '') ); } /** * Tear down WebSockets, rate limiters, and nonce manager state. */ public async close(): Promise { if (this._wsManager) { this._wsManager.disconnect(); this._wsManager = null; } // Reset rate limiters if (this._apiRateLimiter) { this._apiRateLimiter.reset(); } if (this._rpcRateLimiter) { this._rpcRateLimiter.reset(); } // Clear nonce manager if (this._nonceManager) { this._nonceManager.clearAll(); } this._logger.debug('Dexalot client closed'); return Promise.resolve(); } }