import { TransferClient } from '../../src/core/transfer'; import { Utils } from '../../src/utils'; import { DexalotClient } from '../../src/core/client'; import { ethers, Contract, MaxUint256 } from 'ethers'; import { ENV, DEFAULTS, ENDPOINTS } from '../../src/constants'; // Mock everything jest.mock('ethers'); jest.mock('../../src/utils'); // We need a concrete class to test the class class TestClient extends TransferClient {} describe('TransferClient', () => { let client: TestClient; let mockSigner: any; let mockContract: any; let mockProvider: any; const mockAddress = '0xUserAddress'; const mockToken = 'AVAX'; const mockTokenAddr = '0xAvaxTokenAddr'; beforeEach(() => { jest.clearAllMocks(); // Tolerated balance-lookup failures log a warning; keep test output quiet. jest.spyOn(console, 'warn').mockImplementation(() => {}); // Setup Signer mockSigner = { getAddress: jest.fn().mockResolvedValue(mockAddress), provider: { getBalance: jest.fn().mockResolvedValue(1000n) }, connect: jest.fn().mockImplementation(function (this: any) { return this; }) }; // Setup Contract Mock mockContract = { getAddress: jest.fn().mockResolvedValue('0xContractAddress'), getBalance: jest.fn(), balanceOf: jest.fn().mockResolvedValue(100n), // Add balanceOf depositNative: jest.fn().mockResolvedValue({ hash: '0xDepositNativeHash', wait: jest.fn().mockResolvedValue({ status: 1 }) }), depositToken: jest.fn().mockResolvedValue({ hash: '0xDepositTokenHash', wait: jest.fn().mockResolvedValue({ status: 1 }) }), withdrawToken: jest.fn().mockResolvedValue({ hash: '0xWithdrawTokenHash', wait: jest.fn().mockResolvedValue({ status: 1 }) }), transferToken: jest.fn().mockResolvedValue({ hash: '0xTransferTokenHash', wait: jest.fn().mockResolvedValue({ status: 1 }) }), withdrawNative: jest.fn().mockResolvedValue({ hash: '0xWithdrawNativeHash', wait: jest.fn().mockResolvedValue({ status: 1 }) }), getBalances: jest.fn(), allowance: jest.fn(), approve: jest.fn().mockResolvedValue({ wait: jest.fn().mockResolvedValue({}) }), portfolioBridge: jest.fn().mockResolvedValue('0xBridgeAddress'), runner: mockSigner, functions: {} }; // Gas estimation mocks mockContract.depositNative.estimateGas = jest.fn().mockResolvedValue(100000n); mockContract.depositToken.estimateGas = jest.fn().mockResolvedValue(100000n); mockContract.withdrawToken.estimateGas = jest.fn().mockResolvedValue(100000n); mockContract.transferToken.estimateGas = jest.fn().mockResolvedValue(100000n); mockContract.withdrawNative.estimateGas = jest.fn().mockResolvedValue(100000n); // Setup Contract Constructor Mock - return mockContract by default, but handle bridge contract specially (Contract as unknown as jest.Mock).mockImplementation((address, abi, runner) => { // If it's the bridge contract (has getBridgeFee in ABI) if (abi && abi.some((item: any) => item.includes('getBridgeFee'))) { return { getBridgeFee: jest.fn().mockResolvedValue(1000n) }; } return mockContract; }); // Utils Mocks (Utils.toBytes32 as jest.Mock).mockReturnValue('0xBytes32'); (Utils.fromBytes32 as jest.Mock).mockReturnValue('AVAX'); (Utils.unitConversion as jest.Mock).mockImplementation((val, dec, toWei) => { if (toWei) return val.toString() + '000000000000000000'; // Simply append zeros for mock return '10'; // Return '10' for fromWei }); client = new TestClient(mockSigner); // Manual setup of client properties that usually come from initializeClient() client.portfolioSubContractView = mockContract; client.portfolioMainContracts = { 'Avalanche': mockContract }; // Per-chain contracts client.portfolioSubContract = mockContract; client.deployments['PortfolioSub'] = { address: '0xPortfolioSub', abi: [] }; client.deployments['PortfolioMain'] = { Avalanche: { address: '0xPortfolioMain', abi: [] } }; // The L1 (subnet) provider must expose getBalance: the L1 balance // helpers read through it when it is present. mockProvider = { getBalance: jest.fn().mockResolvedValue(1000n) }; client.subnetProvider = mockProvider as any; client.subnetChainId = 12345; client.chainId = 43114; client.env = ENV.PROD_MULTI_AVAX; client.subnetEnv = ENV.PROD_MULTI_SUBNET; // Add subnet env client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX', env: ENV.PROD_MULTI_AVAX } as any, 'Destination': { chain_id: 999 } as any }; client.tokenData = { 'AVAX': { [ENV.PROD_MULTI_AVAX]: { address: mockTokenAddr, decimals: 18, chainId: 43114, env: ENV.PROD_MULTI_AVAX } as any, [ENV.PROD_MULTI_SUBNET]: { address: mockTokenAddr, decimals: 18, chainId: 12345, env: ENV.PROD_MULTI_SUBNET } as any }, 'USDT': { [ENV.PROD_MULTI_AVAX]: { address: '0xUSDT', decimals: 6, chainId: 43114, env: ENV.PROD_MULTI_AVAX } as any, [ENV.PROD_MULTI_SUBNET]: { address: '0xUSDT', decimals: 6, chainId: 12345, env: ENV.PROD_MULTI_SUBNET } as any } }; client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockResolvedValue(2000n) } as any }; }); describe('getPortfolioBalance', () => { it('should return parsed balance', async () => { mockContract.getBalance.mockResolvedValue([100n, 50n, 50n]); const result = await client.getPortfolioBalance('AVAX'); expect(result.success).toBe(true); expect(result.data!.total).toBe(10); // Mocked Utils returns '10' expect(mockContract.getBalance).toHaveBeenCalled(); }); it('should return error if token validation fails', async () => { // Use an invalid token symbol (lowercase) to trigger validation failure const result = await client.getPortfolioBalance('avax'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('should return error if Subnet View not initialized', async () => { delete (client.deployments as any)['PortfolioSub']; const result = await client.getPortfolioBalance('AVAX'); expect(result.success).toBe(false); expect(result.error).toContain('Subnet View Contract not initialized'); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.getPortfolioBalance('AVAX'); expect(result.success).toBe(false); expect(result.error).toContain('Address required'); }); it('should default to 18 decimals if token unknown', async () => { mockContract.getBalance.mockResolvedValue([10n, 5n, 5n]); client.tokenData = {}; client.subnetChainId = 12345; const result = await client.getPortfolioBalance('UNKNOWN'); expect(result.success).toBe(true); expect(result.data!.total).toBe(10); }); it('should handle getPortfolioBalance errors in catch block', async () => { // Force an error during getBalance call mockContract.getBalance.mockRejectedValue(new Error('Contract call failed')); const result = await client.getPortfolioBalance('AVAX'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('getTokenDetails', () => { it('returns token details from API', async () => { const spy = jest.spyOn(client as any, '_apiCall').mockResolvedValue([ { symbol: 'AVAX', address: '0xabc', evmdecimals: 18, env: ENV.PROD_MULTI_AVAX, name: 'Avalanche', chainid: 43114, }, ]); const result = await client.getTokenDetails('AVAX'); expect(result.success).toBe(true); expect(result.data).toMatchObject({ [ENV.PROD_MULTI_AVAX]: { symbol: 'AVAX', address: '0xabc', decimals: 18, }, }); spy.mockRestore(); }); it('returns fail when token not in list', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValue([]); const result = await client.getTokenDetails('MISSING'); expect(result.success).toBe(false); expect(result.error).toContain('not found'); }); it('propagates API failure', async () => { jest.spyOn(client as any, '_apiCall').mockRejectedValue(new Error('network down')); const result = await client.getTokenDetails('AVAX'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('getTokenUsdPrices', () => { // Backend currently returns a flat `Record` map of // token symbol → numeric price. The SDK normalizes to `Record` and silently drops malformed entries (missing symbol / // non-numeric / non-finite). Cache key is namespaced by `env` so // testnet and mainnet clients never collide on the same slot. beforeEach(() => { // Disable retry so a single rejection from the spy doesn't // get retried and folded into the rate-limited fetch path. client.config.retryEnabled = false; }); it('returns token-symbol → USD-price map from the public endpoint', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ ALOT: '0.0411', AVAX: '8.6811', USDC: '0.9996', }); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.0411, AVAX: 8.6811, USDC: 0.9996, }); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_USD_PRICES, { params: { env: client.config.parentEnv } } ); }); it('defaults env to config.parentEnv when not provided', async () => { client.config.parentEnv = 'fuji-multi-avax'; const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ ALOT: '0.04' }); await client.getTokenUsdPrices(); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_USD_PRICES, { params: { env: 'fuji-multi-avax' } } ); }); it('uses explicit env over config.parentEnv when provided', async () => { client.config.parentEnv = 'fuji-multi-avax'; const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ ALOT: '0.04' }); await client.getTokenUsdPrices('production-multi-avax'); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_USD_PRICES, { params: { env: 'production-multi-avax' } } ); }); it('returns Result.fail when the API call rejects', async () => { jest.spyOn(client as any, '_apiCall').mockRejectedValueOnce( new Error('upstream down') ); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('shares a cache slot for repeated identical calls within TTL', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue({ ALOT: '0.04' }); await client.getTokenUsdPrices('fuji-multi-avax'); await client.getTokenUsdPrices('fuji-multi-avax'); // Second call hits the semi-static cache; _apiCall fires once. expect(apiSpy).toHaveBeenCalledTimes(1); }); it('uses distinct cache slots per env so testnet and mainnet do not collide', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue({ ALOT: '0.04' }); await client.getTokenUsdPrices('fuji-multi-avax'); await client.getTokenUsdPrices('production-multi-avax'); expect(apiSpy).toHaveBeenCalledTimes(2); }); it('normalizes array-of-objects shape to a map (forward-compat)', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { symbol: 'ALOT', price: '0.0411' }, { symbol: 'AVAX', price: 8.6811 }, ]); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.0411, AVAX: 8.6811 }); }); it('handles scientific-notation string prices', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ COQ: '1.04662e-7', }); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data!.COQ).toBeCloseTo(1.04662e-7, 12); }); it('skips malformed entries silently (non-numeric / missing symbol / non-finite)', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ ALOT: '0.0411', BROKEN: 'not-a-number', EMPTY: '', INF: 'Infinity', NULLISH: null, AVAX: '8.6811', }); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.0411, AVAX: 8.6811 }); }); it('skips malformed array entries (missing symbol or non-numeric price)', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { symbol: 'ALOT', price: '0.0411' }, { symbol: '', price: '1.0' }, // missing symbol { price: '2.0' }, // no symbol field { symbol: 'BAD', price: 'oops' }, // non-numeric price { symbol: 'AVAX', price: '8.6811' }, ]); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.0411, AVAX: 8.6811 }); }); it('returns Result.fail when the API response is neither object nor array', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce('unexpected'); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('skips numeric entries that are negative or non-finite', async () => { // Exercises the `typeof raw === 'number'` branch of the price // coercer with values that should be rejected (NaN, Infinity, // negative). Plain JSON cannot carry NaN/Infinity, but the array // shape can carry any JS number via the price field. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { symbol: 'ALOT', price: 0.04 }, { symbol: 'NEG', price: -1 }, { symbol: 'NAN', price: Number.NaN }, { symbol: 'INF', price: Number.POSITIVE_INFINITY }, { symbol: 'AVAX', price: 8.6811 }, ]); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.04, AVAX: 8.6811 }); }); it('skips null and non-object rows in the array shape', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ null, 'not-an-object', 42, { symbol: 'ALOT', price: '0.04' }, ]); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.04 }); }); it('skips entries whose key is empty or whitespace in the map shape', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ '': '1.0', ' ': '2.0', ALOT: '0.04', }); const result = await client.getTokenUsdPrices(); expect(result.success).toBe(true); expect(result.data).toEqual({ ALOT: 0.04 }); }); }); describe('getTokenPriceHistory / getTokenHourlyPriceHistory', () => { // Backend returns `[{date: ISO-string, price: stringified-number}, ...]` // sorted descending by date. The SDK normalizes to ascending // unix-seconds + numeric `PricePoint[]`, tolerates alias keys // (`ts`/`timestamp`/`time` → `timestamp`), coerces string→number // prices, and drops malformed rows silently. Cache key is namespaced // by path so daily and hourly never collide on the static-tier slot. beforeEach(() => { client.config.retryEnabled = false; }); // Two ISO timestamps and their unix-second equivalents. const D1_ISO = '2026-05-01T00:00:00.000Z'; const D2_ISO = '2026-05-02T00:00:00.000Z'; const D1_TS = Math.floor(Date.parse(D1_ISO) / 1000); const D2_TS = Math.floor(Date.parse(D2_ISO) / 1000); describe('getTokenPriceHistory (daily)', () => { it('returns ascending-time PricePoint[] from descending API rows', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([ { date: D2_ISO, price: '0.042' }, { date: D1_ISO, price: '0.041' }, ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([ { timestamp: D1_TS, price: 0.041 }, { timestamp: D2_TS, price: 0.042 }, ]); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_PRICE_HISTORY, { params: { token: 'ALOT' } } ); }); it('forwards from/to query params when supplied', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([]); await client.getTokenPriceHistory('ALOT', { from: 100, to: 200 }); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_PRICE_HISTORY, { params: { token: 'ALOT', from: 100, to: 200 } } ); }); it('filters rows outside [from, to] client-side (defense in depth)', async () => { const D3_ISO = '2026-05-03T00:00:00.000Z'; const D3_TS = Math.floor(Date.parse(D3_ISO) / 1000); jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([ { date: D3_ISO, price: '0.043' }, { date: D2_ISO, price: '0.042' }, { date: D1_ISO, price: '0.041' }, ]); const result = await client.getTokenPriceHistory('ALOT', { from: D2_TS, to: D3_TS, }); expect(result.success).toBe(true); expect(result.data).toEqual([ { timestamp: D2_TS, price: 0.042 }, { timestamp: D3_TS, price: 0.043 }, ]); }); it('returns Result.fail when token is empty or non-string', async () => { const r1 = await client.getTokenPriceHistory(''); expect(r1.success).toBe(false); const r2 = await client.getTokenPriceHistory(null as any); expect(r2.success).toBe(false); }); it('returns empty array when the API returns an empty list', async () => { jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([]); const result = await client.getTokenPriceHistory('NEWTOKEN'); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('returns Result.fail when _apiCall rejects', async () => { jest.spyOn(client as any, '_apiCall').mockRejectedValueOnce( new Error('upstream down') ); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('shares a cache slot for repeated identical calls within TTL', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue([{ date: D1_ISO, price: '0.04' }]); await client.getTokenPriceHistory('ALOT'); await client.getTokenPriceHistory('ALOT'); expect(apiSpy).toHaveBeenCalledTimes(1); }); it('uses distinct cache slots per (token, from, to) tuple', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue([{ date: D1_ISO, price: '0.04' }]); await client.getTokenPriceHistory('ALOT'); await client.getTokenPriceHistory('AVAX'); await client.getTokenPriceHistory('ALOT', { from: 1, to: 2 }); await client.getTokenPriceHistory('ALOT', { from: 3, to: 4 }); expect(apiSpy).toHaveBeenCalledTimes(4); }); it('returns Result.fail when the API response is not an array', async () => { jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ not: 'an array' }); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('accepts numeric `ts` / `timestamp` / `time` alias fields', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { ts: D1_TS, price: '0.041' }, { timestamp: D2_TS, price: '0.042' }, { time: D2_TS + 86400, price: '0.043' }, ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([ { timestamp: D1_TS, price: 0.041 }, { timestamp: D2_TS, price: 0.042 }, { timestamp: D2_TS + 86400, price: 0.043 }, ]); }); it('coerces millisecond timestamps to seconds', async () => { const msNow = D1_TS * 1000; jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { ts: msNow, price: '0.041' }, ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([{ timestamp: D1_TS, price: 0.041 }]); }); it('accepts string-numeric `ts` alias and drops non-numeric/empty/non-string types', async () => { // Covers the string-parsing branch of `_coerceTimestampSeconds` // (string → Number()) plus the rejection branches: empty // string, non-numeric string, and non-string-non-number types // (boolean, object). Each malformed row falls through to // `null` and is dropped silently. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { ts: String(D1_TS), price: '0.041' }, // string number → ok { ts: ' ', price: '0.5' }, // empty after trim → null { ts: 'nope', price: '0.5' }, // non-numeric string → null { ts: true, price: '0.5' }, // boolean → null { ts: { v: 1 }, price: '0.5' }, // object → null ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([{ timestamp: D1_TS, price: 0.041 }]); }); it('accepts numeric prices (forward-compat with non-string shape)', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ { date: D1_ISO, price: 0.041 }, ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([{ timestamp: D1_TS, price: 0.041 }]); }); it('silently drops malformed rows (non-object, missing fields, bad ts, bad price)', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ null, 'not-an-object', 42, { date: D1_ISO, price: '0.041' }, { date: 'not-a-date', price: '0.5' }, // unparseable ts { price: '0.5' }, // missing ts { date: D2_ISO }, // missing price { date: D2_ISO, price: 'oops' }, // non-numeric price { date: D2_ISO, price: '' }, // empty string price { date: D2_ISO, price: ' ' }, // whitespace-only price { date: D2_ISO, price: -1 }, // negative { date: D2_ISO, price: Number.NaN }, // NaN { date: D2_ISO, price: Number.POSITIVE_INFINITY }, { date: D2_ISO, price: true }, // boolean price ]); const result = await client.getTokenPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([{ timestamp: D1_TS, price: 0.041 }]); }); }); describe('getTokenHourlyPriceHistory', () => { it('hits the hourly endpoint and returns normalized PricePoint[]', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([ { date: D2_ISO, price: '0.042' }, { date: D1_ISO, price: '0.041' }, ]); const result = await client.getTokenHourlyPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([ { timestamp: D1_TS, price: 0.041 }, { timestamp: D2_TS, price: 0.042 }, ]); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.INFO_HOURLY_PRICE_HISTORY, { params: { token: 'ALOT' } } ); }); it('returns Result.fail when _apiCall rejects', async () => { jest.spyOn(client as any, '_apiCall').mockRejectedValueOnce( new Error('boom') ); const result = await client.getTokenHourlyPriceHistory('ALOT'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('returns Result.fail when token is invalid', async () => { const r = await client.getTokenHourlyPriceHistory(''); expect(r.success).toBe(false); }); it('returns empty array when the API returns an empty list', async () => { jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce([]); const result = await client.getTokenHourlyPriceHistory('ALOT'); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('shares a cache slot per identical call within TTL', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue([{ date: D1_ISO, price: '0.04' }]); await client.getTokenHourlyPriceHistory('ALOT'); await client.getTokenHourlyPriceHistory('ALOT'); expect(apiSpy).toHaveBeenCalledTimes(1); }); it('uses a distinct cache slot from getTokenPriceHistory (path-namespaced)', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue([{ date: D1_ISO, price: '0.04' }]); await client.getTokenPriceHistory('ALOT'); await client.getTokenHourlyPriceHistory('ALOT'); // Daily and hourly do NOT share a cache slot even with the // same token + opts — the cache key includes the REST path. expect(apiSpy).toHaveBeenCalledTimes(2); expect(apiSpy).toHaveBeenNthCalledWith( 1, 'get', ENDPOINTS.INFO_PRICE_HISTORY, { params: { token: 'ALOT' } } ); expect(apiSpy).toHaveBeenNthCalledWith( 2, 'get', ENDPOINTS.INFO_HOURLY_PRICE_HISTORY, { params: { token: 'ALOT' } } ); }); }); }); describe('deposit', () => { it('should handle Native deposit (AVAX)', async () => { const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(true); expect(mockContract.depositNative).toHaveBeenCalled(); }); it('should handle ERC20 deposit with allowance', async () => { mockContract.allowance.mockResolvedValue(0n); const result = await client.deposit('USDT', 10, 'Avalanche'); expect(result.success).toBe(true); expect(mockContract.approve).toHaveBeenCalledWith(expect.any(String), MaxUint256); expect(mockContract.depositToken).toHaveBeenCalled(); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('Signer'); }); it('should return error if PortfolioMain contract missing for chain', async () => { client.deployments['PortfolioMain'] = {}; const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain("PortfolioMain contract not found"); }); it('should return error if chain config missing', async () => { delete (client.chainConfig as any)['Avalanche']; const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain("Chain config not found"); }); it('should return error if unknown token', async () => { const result = await client.deposit('UNKNOWN', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain("Token address for UNKNOWN not found"); }); it('should handle deposit errors in catch block', async () => { // Force an error during depositNative call mockContract.depositNative.estimateGas.mockRejectedValue(new Error('Transaction failed')); const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('encodes native deposit amount through toWei (precision-safe)', async () => { const result = await client.deposit('AVAX', 2933.0, 'Avalanche'); expect(result.success).toBe(true); const callArgs = mockContract.depositNative.mock.calls[0]; // depositNative(signerAddress, bridgeId, { value: amountWei + bridgeFee, ... }) // bridgeFee is mocked to 1000n; assert value = 2933e18 + 1000. expect(callArgs[2].value).toBe(2933000000000000000000n + 1000n); }); it('encodes ERC20 deposit amount through toWei (precision-safe)', async () => { const result = await client.deposit('USDT', 2933.0, 'Avalanche'); expect(result.success).toBe(true); const callArgs = mockContract.depositToken.mock.calls[0]; // depositToken(signerAddress, symbolBytes, amountWei, bridgeId, opts) // USDT in this fixture has 6 decimals. expect(callArgs[2]).toBe(2933000000n); }); }); describe('withdraw', () => { it('should withdraw token', async () => { const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(true); expect(mockContract.withdrawToken).toHaveBeenCalled(); }); it('should check allowance for withdrawal if subnet address exists', async () => { mockContract.allowance.mockResolvedValue(0n); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(true); expect(mockContract.approve).toHaveBeenCalled(); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.withdraw('AVAX', 10, 'Dest'); expect(result.success).toBe(false); expect(result.error).toContain('Signer'); }); it('should return error if destination chain invalid', async () => { const result = await client.withdraw('AVAX', 10, 'Invalid'); expect(result.success).toBe(false); expect(result.error).toContain('Destination chain'); }); it('should return error if PortfolioSub missing', async () => { delete (client.deployments as any)['PortfolioSub']; const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); expect(result.error).toContain('Portfolio Sub contract not available'); }); it('should handle withdraw errors in catch block', async () => { // Force an error during withdrawToken call mockContract.withdrawToken.estimateGas.mockRejectedValue(new Error('Withdrawal failed')); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('encodes withdraw amount through toWei (precision-safe)', async () => { const result = await client.withdraw('AVAX', 2933.0, 'Destination'); expect(result.success).toBe(true); const callArgs = mockContract.withdrawToken.mock.calls[0]; // withdrawToken(signerAddress, symbolBytes, amountWei, ...) expect(callArgs[2]).toBe(2933000000000000000000n); }); }); describe('transferPortfolio precision', () => { const validAddress = '0x1234567890123456789012345678901234567890'; it('encodes transferPortfolio amount through toWei (precision-safe)', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 10000, available: 10000, locked: 0 }, } as any); const result = await client.transferPortfolio('AVAX', 2933.0, validAddress); expect(result.success).toBe(true); const callArgs = mockContract.transferToken.mock.calls[0]; // transferToken(toAddress, symbolBytes, amountWei) expect(callArgs[2]).toBe(2933000000000000000000n); }); }); describe('getDepositBridgeFee precision', () => { it('encodes the amount argument through toWei (precision-safe)', async () => { const bridgeContract = { getBridgeFee: jest.fn().mockResolvedValue(1234n), }; // Override the Contract constructor used inside getDepositBridgeFee for // the bridge contract. The default mock returns the AVAX/USDT contract. (Contract as unknown as jest.Mock).mockImplementation((_addr, abi) => { if (Array.isArray(abi) && abi.some((item: any) => String(item).includes('getBridgeFee'))) { return bridgeContract; } return mockContract; }); const result = await client.getDepositBridgeFee('AVAX', 2933.0, 'Avalanche'); expect(result.success).toBe(true); const fnCallArgs = bridgeContract.getBridgeFee.mock.calls[0]; // getBridgeFee(bridgeId, dstChainId, symbolBytes, amountWei, address, '0x00') expect(fnCallArgs[3]).toBe(2933000000000000000000n); }); }); describe('transferPortfolio', () => { const validAddress = '0x1234567890123456789012345678901234567890'; it('should transfer token if balance sufficient', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 20, available: 20, locked: 0 } } as any); const result = await client.transferPortfolio('AVAX', 10, validAddress); expect(result.success).toBe(true); expect(mockContract.transferToken).toHaveBeenCalled(); }); it('should use token decimals when available', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 20, available: 20, locked: 0 } } as any); client.tokenData['AVAX'][ENV.PROD_MULTI_SUBNET].decimals = 8; const result = await client.transferPortfolio('AVAX', 1, validAddress); expect(result.success).toBe(true); expect(mockContract.transferToken).toHaveBeenCalled(); }); it('should return error if balance insufficient', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 5, available: 5, locked: 0 } } as any); const result = await client.transferPortfolio('AVAX', 10, validAddress); expect(result.success).toBe(false); expect(result.error).toContain('Insufficient available balance'); }); it('should return error if init missing', async () => { delete (client.deployments as any)['PortfolioSub']; const result = await client.transferPortfolio('AVAX', 10, validAddress); expect(result.success).toBe(false); expect(result.error).toContain('Signer/Contract not initialized'); }); it('should return error if getPortfolioBalance fails', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: false, error: 'Balance check failed' } as any); const result = await client.transferPortfolio('AVAX', 10, validAddress); expect(result.success).toBe(false); expect(result.error).toBe('Balance check failed'); }); it('should handle transferPortfolio errors in catch block', async () => { jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 20, available: 20, locked: 0 } } as any); // Force an error during transferToken call mockContract.transferToken.estimateGas.mockRejectedValue(new Error('Transfer failed')); const result = await client.transferPortfolio('AVAX', 10, validAddress); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('transferToken', () => { it('should call transferPortfolio with (token, toAddress, amount) and return message string', async () => { const toAddr = '0x1234567890123456789012345678901234567890'; jest.spyOn(client, 'transferPortfolio').mockResolvedValue({ success: true, data: { txHash: '0xabc', operation: 'transfer_portfolio' }, error: null, } as any); const result = await client.transferToken('AVAX', toAddr, 10); expect(client.transferPortfolio).toHaveBeenCalledWith('AVAX', 10, toAddr, true); expect(result.success).toBe(true); expect(result.data).toContain('0xabc'); }); }); describe('addGas & removeGas', () => { it('should call withdrawNative for addGas', async () => { const result = await client.addGas(10); expect(result.success).toBe(true); expect(mockContract.withdrawNative).toHaveBeenCalled(); }); it('should call depositNative for removeGas', async () => { const result = await client.removeGas(10); expect(result.success).toBe(true); expect(mockContract.depositNative).toHaveBeenCalled(); }); it('should return error if init missing', async () => { delete (client.deployments as any)['PortfolioSub']; const addResult = await client.addGas(10); expect(addResult.success).toBe(false); expect(addResult.error).toContain('Signer/Contract not initialized'); const removeResult = await client.removeGas(10); expect(removeResult.success).toBe(false); expect(removeResult.error).toContain('Signer/Contract not initialized'); }); it('should handle addGas errors in catch block', async () => { // Force an error during withdrawNative call mockContract.withdrawNative.estimateGas.mockRejectedValue(new Error('Add gas failed')); const result = await client.addGas(10); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('should handle removeGas errors in catch block', async () => { // Force an error during depositNative call mockContract.depositNative.estimateGas.mockRejectedValue(new Error('Remove gas failed')); const result = await client.removeGas(10); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('encodes addGas amount through toWei (precision-safe, no float drift)', async () => { // The naive `BigInt(Math.floor(2933.0 * 10**18))` yields // 2932999999999999737856n. toWei must produce the exact value. const result = await client.addGas(2933.0); expect(result.success).toBe(true); const callArgs = mockContract.withdrawNative.mock.calls[0]; expect(callArgs[1]).toBe(2933000000000000000000n); }); it('encodes removeGas amount through toWei (precision-safe, no float drift)', async () => { const result = await client.removeGas(2933.0); expect(result.success).toBe(true); const callArgs = mockContract.depositNative.mock.calls[0]; expect(callArgs[2].value).toBe(2933000000000000000000n); }); }); describe('getAllPortfolioBalances', () => { it('issues pages in parallel batches of 5 and stops when a page is empty', async () => { // The first batch of 5 pages: page 0 has data, pages 1-4 are empty. // The empty page in the batch signals end-of-data — no further batch // is issued, so the call count is exactly BATCH_SIZE (5). mockContract.getBalances.mockImplementation(async (_addr: string, page: number) => { if (page === 0) return [['0xAvax'], [100n], [50n]]; return [[], [], []]; }); const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(result.data!['AVAX']).toBeDefined(); expect(mockContract.getBalances).toHaveBeenCalledTimes(5); }); it('aggregates balances across multiple non-empty batches', async () => { // Pages 0-5 have data; pages 6+ are empty. With BATCH_SIZE=5 the // first batch returns all-data, the second batch contains the empty // page and the loop terminates → 10 total calls (two batches). mockContract.getBalances.mockImplementation(async (_addr: string, page: number) => { if (page <= 5) return [[`0xPage${page}`], [BigInt(page * 10)], [BigInt(page * 5)]]; return [[], [], []]; }); (Utils.fromBytes32 as jest.Mock).mockImplementation((b: string) => b.replace(/^0x/, '')); const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(Object.keys(result.data!).length).toBe(6); // pages 0..5 expect(mockContract.getBalances).toHaveBeenCalledTimes(10); // Reset the fromBytes32 mock back to its describe-level default. (Utils.fromBytes32 as jest.Mock).mockReturnValue('AVAX'); }); it('should compute locked from totals and availables', async () => { const original = (Utils.unitConversion as jest.Mock).getMockImplementation(); (Utils.unitConversion as jest.Mock).mockImplementation((val, _dec, _toWei) => val.toString()); mockContract.getBalances.mockImplementation(async (_addr: string, page: number) => { if (page === 0) return [['0xAvax'], [200n], [150n]]; return [[], [], []]; }); const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(result.data!['AVAX'].locked).toBe(50); (Utils.unitConversion as jest.Mock).mockImplementation(original as any); }); it('bails at PAGE_HARD_CAP when the backend keeps returning data', async () => { // Always return data — the loop must terminate at PAGE_HARD_CAP=50. mockContract.getBalances.mockResolvedValue([['0xAvax'], [100n], [50n]]); const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(mockContract.getBalances).toHaveBeenCalledTimes(50); }); it('should return error if init missing', async () => { delete (client.deployments as any)['PortfolioSub']; const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(false); expect(result.error).toContain('Subnet View Contract not initialized'); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(false); expect(result.error).toContain('Address required'); }); it('should handle getAllPortfolioBalances errors in catch block', async () => { // Force an error during getAddress call mockSigner.getAddress.mockRejectedValueOnce(new Error('Address fetch failed')); const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('getChainWalletBalance', () => { it('should return L1 ALOT balance', async () => { const result = await client.getChainWalletBalance('Dexalot L1', 'ALOT'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Dexalot L1'); expect(result.data!.symbol).toBe('ALOT'); expect(result.data!.type).toBe('Native'); expect(result.data!.balance).toBe('10'); // numeric string from mocked unitConversion expect(result.data!.error).toBeUndefined(); }); it('should fail when the L1 RPC read throws instead of returning an error string', async () => { mockProvider.getBalance.mockRejectedValue(new Error('500 Internal Server Error')); const result = await client.getChainWalletBalance('Dexalot L1', 'ALOT'); expect(result.success).toBe(false); expect(result.data).toBeNull(); expect(result.error).toContain('fetching L1 native balance'); }); it('should fail when Dexalot L1 is not connected', async () => { client.subnetProvider = null as any; client.provider = undefined as any; (client.signer as any).provider = undefined; const result = await client.getChainWalletBalance('Dexalot L1', 'ALOT'); expect(result.success).toBe(false); expect(result.error).toBe('Dexalot L1 not connected'); }); it('should return error for non-ALOT on L1', async () => { const result = await client.getChainWalletBalance('Dexalot L1', 'USDC'); expect(result.success).toBe(false); expect(result.error).toContain('not available on Dexalot L1'); }); it('should return error for unknown chain', async () => { const result = await client.getChainWalletBalance('UnknownChain', 'AVAX'); expect(result.success).toBe(false); expect(result.error).toContain('not connected'); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.getChainWalletBalance('Dexalot L1', 'ALOT'); expect(result.success).toBe(false); expect(result.error).toBe('Address required (pass as param or set signer)'); }); it('should return mainnet native token balance', async () => { client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockResolvedValue(25n * 10n**18n) } as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; const result = await client.getChainWalletBalance('Avalanche', 'AVAX'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Avalanche'); expect(result.data!.symbol).toBe('AVAX'); expect(result.data!.type).toBe('Native'); }); it('should return ERC20 token balance', async () => { client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockResolvedValue(0n) } as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'USDC': { 'prod': { address: '0xUSDC', chainId: 43114, decimals: 6, env: 'prod' } as any } }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(1000n * 10n**6n) })); const result = await client.getChainWalletBalance('Avalanche', 'USDC'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Avalanche'); expect(result.data!.symbol).toBe('USDC'); expect(result.data!.type).toBe('ERC20'); }); it('should return error if chain ID not configured', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { native_symbol: 'AVAX' } as any }; // No chain_id const result = await client.getChainWalletBalance('Avalanche', 'USDC'); expect(result.success).toBe(false); expect(result.error).toContain('Chain ID not configured'); }); it('should return error for token not in tokenData', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = {}; const result = await client.getChainWalletBalance('Avalanche', 'UNKNOWN'); expect(result.success).toBe(false); expect(result.error).toContain('not found in token data'); }); it('should return error for token not on chain', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'SPECIAL': { 'eth': { address: '0xSPEC', chainId: 1, env: 'eth' } as any } // Different chain }; const result = await client.getChainWalletBalance('Avalanche', 'SPECIAL'); expect(result.success).toBe(false); expect(result.error).toContain('not available on chain'); }); it('should return error for token with zero address', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'ZERO': { 'prod': { address: DEFAULTS.ZERO_ADDRESS, chainId: 43114, env: 'prod' } as any } }; const result = await client.getChainWalletBalance('Avalanche', 'ZERO'); expect(result.success).toBe(false); expect(result.error).toContain('not available on chain'); }); it('should handle ERC20 contract errors', async () => { client.connectedChainProviders = { Avalanche: { getBalance: jest.fn().mockResolvedValue(0n) } as any, }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'ERR': { 'prod': { address: '0xERR', chainId: 43114, decimals: 18, env: 'prod' } as any } }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockRejectedValue(new Error('Contract Error')) })); const result = await client.getChainWalletBalance('Avalanche', 'ERR'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('should fallback to env string matching for Fuji', async () => { client.connectedChainProviders = { 'Fuji': {} as any }; client.chainConfig = { 'Fuji': { chain_id: 43113, native_symbol: 'AVAX' } as any }; client.tokenData = { 'DAI': { 'env-key': { address: '0xDAI', chainId: 9999, decimals: 18, env: 'fuji-multi' } as any } }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(100n) })); const result = await client.getChainWalletBalance('Fuji', 'DAI'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Fuji'); expect(result.data!.symbol).toBe('DAI'); }); it('should fallback to env string matching for Avalanche/prod', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'USDT': { 'env-key': { address: '0xUSDT', chainId: 9999, decimals: 6, env: 'prod-multi' } as any } }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(500n) })); const result = await client.getChainWalletBalance('Avalanche', 'USDT'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Avalanche'); expect(result.data!.symbol).toBe('USDT'); }); it('should fallback to empty chainConfig and ETH symbol', async () => { client.connectedChainProviders = { 'CustomChain': { getBalance: jest.fn().mockResolvedValue(10n) } as any }; client.chainConfig = {}; // No config for CustomChain - will fallback to {} const result = await client.getChainWalletBalance('CustomChain', 'ETH'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('CustomChain'); expect(result.data!.symbol).toBe('ETH'); // Fallback native symbol expect(result.data!.type).toBe('Native'); }); it('should fallback to default 18 decimals for ERC20', async () => { client.connectedChainProviders = { 'Avalanche': {} as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; client.tokenData = { 'NODEC': { 'prod': { address: '0xNODEC', chainId: 43114, env: 'prod' } as any } // No decimals field }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(100n) // Raw value })); const result = await client.getChainWalletBalance('Avalanche', 'NODEC'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Avalanche'); expect(result.data!.symbol).toBe('NODEC'); // Utils.unitConversion with 18 decimals: 100 / 10^18 = very small number expect(result.data!.balance).toBeDefined(); expect(result.data!.type).toBe('ERC20'); }); it('should handle getChainWalletBalance errors in catch block', async () => { // Force an error during getAddress call mockSigner.getAddress.mockRejectedValueOnce(new Error('Address fetch failed')); const result = await client.getChainWalletBalance('Avalanche', 'AVAX'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('getChainWalletBalances', () => { it('should return L1 balances', async () => { const result = await client.getChainWalletBalances('Dexalot L1'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Dexalot L1'); expect(result.data!.address).toBe(mockAddress); expect(result.data!.chain_balances.length).toBeGreaterThanOrEqual(1); const l1 = result.data!.chain_balances.find((x: any) => x.chain === 'Dexalot L1'); expect(l1).toBeDefined(); expect(l1.balance).toBe('10'); expect(result.data!.errors).toEqual([]); }); it('should return error for unknown chain', async () => { const result = await client.getChainWalletBalances('UnknownChain'); expect(result.success).toBe(false); expect(result.error).toContain('not connected'); }); it('should return error if signer missing', async () => { client.signer = undefined as any; const result = await client.getChainWalletBalances('Dexalot L1'); expect(result.success).toBe(false); expect(result.error).toBe('Address required (pass as param or set signer)'); }); it('should return mainnet chain balances', async () => { client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockResolvedValue(15n * 10n**18n) } as any }; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX' } as any }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(500n) })); const result = await client.getChainWalletBalances('Avalanche'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('Avalanche'); expect(result.data!.address).toBe(mockAddress); const native = result.data!.chain_balances.find((x: any) => x.type === 'Native'); expect(native).toBeDefined(); }); it('should fail when the only L1 lookup errors', async () => { const mockL1 = { getBalance: jest.fn().mockRejectedValue(new Error("L1 Error")) }; client.subnetProvider = null as any; client.provider = mockL1 as any; (client.signer as any).provider = mockL1; const result = await client.getChainWalletBalances('Dexalot L1'); // Every lookup failed, so the plural call fails instead of returning // a success with an error string in the balance field. expect(result.success).toBe(false); expect(result.error).toContain('Dexalot L1 ALOT: '); expect(result.error).toContain('L1 Error'); }); it('should report a failed native lookup in errors while keeping ERC20 entries', async () => { client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockRejectedValue(new Error('RPC 500')) } as any }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(500n) })); const result = await client.getChainWalletBalances('Avalanche'); expect(result.success).toBe(true); expect(result.data!.chain_balances.every((x: any) => x.type === 'ERC20')).toBe(true); expect(result.data!.chain_balances.every((x: any) => x.balance === '10')).toBe(true); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('Avalanche AVAX: '); expect(result.data!.errors[0]).toContain('RPC 500'); }); it('should skip ERC20 balances if no chainId', async () => { client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockResolvedValue(10n) } as any }; client.chainConfig = { 'Avalanche': { native_symbol: 'AVAX' } as any }; // No chain_id const result = await client.getChainWalletBalances('Avalanche'); expect(result.success).toBe(true); // Should only have native, no ERC20s expect(result.data!.chain_balances.filter((x: any) => x.type === 'ERC20').length).toBe(0); }); it('should fallback to empty chainConfig and ETH symbol', async () => { client.connectedChainProviders = { 'CustomChain': { getBalance: jest.fn().mockResolvedValue(10n) } as any }; client.chainConfig = {}; // No config for CustomChain - will fallback to {} const result = await client.getChainWalletBalances('CustomChain'); expect(result.success).toBe(true); expect(result.data!.chain).toBe('CustomChain'); const native = result.data!.chain_balances.find((x: any) => x.type === 'Native'); expect(native.symbol).toBe('ETH'); // Fallback native symbol }); it('should handle getChainWalletBalances errors in catch block', async () => { // Force an error during getAddress call mockSigner.getAddress.mockRejectedValueOnce(new Error('Address fetch failed')); const result = await client.getChainWalletBalances('Avalanche'); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('getAllChainWalletBalances', () => { it('should return correct structure', async () => { // Mock Contract for ERC20 (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockResolvedValue(500n) })); const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); expect(result.data!.address).toBe(mockAddress); const l1 = result.data!.chain_balances.find((x: any) => x.chain === 'Dexalot L1'); expect(l1.balance).toBe('10'); expect(result.data!.chain_balances).toHaveLength(4); // Dexalot L1 + Native AVAX + ERC20 AVAX + ERC20 USDT expect(result.data!.chain_balances.every((x: any) => x.balance === '10')).toBe(true); expect(result.data!.errors).toEqual([]); }); it('should handle signer missing', async () => { client.signer = undefined as any; const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(false); expect(result.error).toBe('Address required (pass as param or set signer)'); }); it('should handle provider errors gracefully', async () => { // Mock console.warn to suppress output jest.spyOn(console, 'warn').mockImplementation(() => {}); client.subnetProvider = null as any; (client.signer!.provider!.getBalance as jest.Mock).mockRejectedValue(new Error("RPC Error")); const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); // Avalanche lookups still succeeded expect(result.data!.chain_balances.find((x: any) => x.chain === 'Dexalot L1')).toBeUndefined(); expect(result.data!.chain_balances.every((x: any) => x.balance === '10')).toBe(true); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('Dexalot L1 ALOT: '); expect(result.data!.errors[0]).toContain('RPC Error'); }); it('should handle mainnet provider errors', async () => { const mockProv = { getBalance: jest.fn().mockRejectedValue(new Error("Mainnet RPC Fail")) }; client.connectedChainProviders = { 'Avalanche': mockProv as any }; const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); // L1 and the ERC20 reads still succeeded expect( result.data!.chain_balances.find((x: any) => x.chain === 'Avalanche' && x.type === 'Native') ).toBeUndefined(); expect(result.data!.chain_balances.every((x: any) => x.balance === '10')).toBe(true); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('Avalanche AVAX: '); expect(result.data!.errors[0]).toContain('Mainnet RPC Fail'); }); it('should fail when every lookup across chains fails', async () => { client.subnetProvider = null as any; client.provider = undefined as any; (client.signer as any).provider = undefined; client.connectedChainProviders = { 'Avalanche': { getBalance: jest.fn().mockRejectedValue(new Error("Mainnet RPC Fail")) } as any }; (Contract as unknown as jest.Mock).mockImplementation(() => ({ balanceOf: jest.fn().mockRejectedValue(new Error('balanceOf failed')) })); const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(false); expect(result.error).toContain('Dexalot L1 ALOT: Dexalot L1 not connected'); expect(result.error).toContain('Avalanche AVAX: '); expect(result.error).toContain('Avalanche USDT: '); }); it('should fallback to string matching for ERC20s', async () => { // Setup tokenData without matching chainId, but matching env string client.tokenData = { 'USDC': { 'some-env': { address: '0xUSDC', chainId: 9999, env: 'prod-multi-avax' } as any } }; // Call internal method directly to test logic const info: any = { chain_balances: [] }; await client._fetchErc20Balances(info, 1111, 'Avalanche', {} as any, '0xAddr'); expect(info.chain_balances).toHaveLength(1); expect(info.chain_balances[0].symbol).toBe('USDC'); }); it('should fallback to string matching for ERC20s (Fuji)', async () => { client.tokenData = { 'DAI': { 'env-key': { address: '0xDAI', chainId: 9999, env: 'fuji-multi-subnet' } as any } }; const info: any = { chain_balances: [] }; await client._fetchErc20Balances(info, 1112, 'Fuji', {} as any, '0xAddr'); expect(info.chain_balances).toHaveLength(1); expect(info.chain_balances[0].symbol).toBe('DAI'); }); it('should iterate mainnet providers and handle errors', async () => { // Setup mainnet provider const failingProvider = { getBalance: jest.fn().mockRejectedValue(new Error("RPC Fail")) }; client.connectedChainProviders['Avalanche'] = failingProvider as any; client.chainConfig['Avalanche'] = { chain_id: 43114, native_symbol: 'AVAX' } as any; // Setup secondary logic to ensure loop happened const successProvider = { getBalance: jest.fn().mockResolvedValue(100n) }; client.connectedChainProviders['Ethereum'] = successProvider as any; client.chainConfig['Ethereum'] = { chain_id: 1, native_symbol: 'ETH' } as any; const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); expect( result.data!.chain_balances.find((x: any) => x.chain === 'Avalanche' && x.type === 'Native') ).toBeUndefined(); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('Avalanche AVAX: '); expect(result.data!.errors[0]).toContain('RPC Fail'); const ethEntry = result.data!.chain_balances.find((x: any) => x.chain === 'Ethereum'); expect(ethEntry.balance).toBe("10"); // Mock returns '10' }); it('should handle L1 provider error', async () => { const mockL1 = { getBalance: jest.fn().mockRejectedValue(new Error("L1 Fail")) }; client.subnetProvider = null as any; client.provider = mockL1 as any; (client.signer as any).provider = mockL1; // Ensure signer.provider matches const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); expect(result.data!.chain_balances.find((x: any) => x.chain === 'Dexalot L1')).toBeUndefined(); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('Dexalot L1 ALOT: '); expect(result.data!.errors[0]).toContain('L1 Fail'); }); it('should report ERC20 tokens whose contract read fails in errors', async () => { // Force contract logic to error (Contract as unknown as jest.Mock).mockImplementation(() => { throw new Error("Contract Error"); }); const info: any = { chain_balances: [] }; await client._fetchErc20Balances(info, 1111, 'Avalanche', {} as any, '0xAddr'); expect(info.chain_balances).toHaveLength(0); // AVAX and USDT both resolve on 'Avalanche' via the env-string fallback. expect(info.errors).toHaveLength(2); expect(info.errors.every((e: string) => e.startsWith('Avalanche '))).toBe(true); expect(info.errors.every((e: string) => e.includes('Contract Error'))).toBe(true); }); it('should handle getAllChainWalletBalances errors in catch block', async () => { // Force an error during getAddress call mockSigner.getAddress.mockRejectedValueOnce(new Error('Address fetch failed')); const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); }); describe('Helpers', () => { it('_getBridgeId should return correct ID', () => { // 'Avalanche' is in ICM_CHAINS, so it returns ICM (2) expect(client._getBridgeId('Avalanche', false)).toBe(2); expect(client._getBridgeId('Other', false)).toBe(0); // LZ }); it('_getBridgeFee should return fee or 0', async () => { mockContract.portfolioBridge.mockResolvedValue('0xBridge'); const mockBridge = { getBridgeFee: jest.fn().mockResolvedValue(123n) }; // We need to return mockBridge when new Contract is called (Contract as unknown as jest.Mock).mockImplementation(() => mockBridge); const fee = await client._getBridgeFee(mockContract, 1, '0xSym', 100n); expect(fee).toBe(123n); }); it('_getBridgeFee should handle errors', async () => { const spyWarn = jest.spyOn(console, 'warn').mockImplementation(() => {}); mockContract.portfolioBridge.mockRejectedValue(new Error("Fail")); const fee = await client._getBridgeFee(mockContract, 1, '0xSym', 100n); expect(fee).toBe(0n); expect(spyWarn).toHaveBeenCalled(); }); it('_getBridgeFee should return 0 if bridge address zero/null', async () => { // The implementation checks !bridgeAddr, so null/undefined returns 0n // Zero address string is truthy, so it would try to create contract // For this test, we'll check null case mockContract.portfolioBridge.mockResolvedValue(null as any); const fee = await client._getBridgeFee(mockContract, 1, '0xSym', 100n); expect(fee).toBe(0n); }); }); describe('Missing Configs & Fallbacks', () => { it('should use signer provider if client provider missing in getAllChainWalletBalances', async () => { client.subnetProvider = null as any; client.provider = undefined as any; const signerGetBalance = jest.fn().mockResolvedValue(100n); client.signer = { getAddress: jest.fn().mockResolvedValue(mockAddress), provider: { getBalance: signerGetBalance } } as any; const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); const l1 = result.data!.chain_balances.find((x: any) => x.chain === 'Dexalot L1'); expect(l1.balance).toBe('10'); expect(signerGetBalance).toHaveBeenCalledWith(mockAddress); }); it('should handle missing chainConfig in getAllChainWalletBalances loop', async () => { client.connectedChainProviders = { 'UnknownChain': {} as any }; client.chainConfig = {}; // No config const result = await client.getAllChainWalletBalances(); expect(result.success).toBe(true); // L1 still succeeded // The provider stub has no getBalance, so the lookup fails and is // reported under the default native symbol. expect(result.data!.chain_balances.find((x: any) => x.chain === 'UnknownChain')).toBeUndefined(); expect(result.data!.errors).toHaveLength(1); expect(result.data!.errors[0]).toContain('UnknownChain ETH: '); }); it('should default to 18 decimals in deposit if token unknown', async () => { // Need address to pass first check, but missing decimals client.tokenData = { 'UNKNOWN': { [ENV.PROD_MULTI_AVAX]: { address: '0xValidAddr', env: ENV.PROD_MULTI_AVAX, chainId: 43114 } as any } }; // Ensure chainId matches so it finds the entry client.chainId = 43114; client.env = ENV.PROD_MULTI_AVAX; client.chainConfig = { 'Avalanche': { chain_id: 43114, native_symbol: 'AVAX', env: ENV.PROD_MULTI_AVAX } as any }; client.portfolioMainContracts = { 'Avalanche': mockContract }; // Logic: _getTokenDecimals returns 18 because decimals prop is undefined mockContract.depositNative.estimateGas.mockResolvedValue(100n); // UNKNOWN token -> ERC20 path. // We need to ensure _ensureAllowance doesn't crash? Mocked? mockContract.allowance.mockResolvedValue(1000n); await client.deposit('UNKNOWN', 10, 'Avalanche'); expect(mockContract.depositToken).toHaveBeenCalled(); }); it('should not wait for receipt when waitForReceipt=false in deposit', async () => { const tx = { hash: '0xDepositNativeHash' }; mockContract.depositNative.mockResolvedValue(tx); const result = await client.deposit('AVAX', 10, 'Avalanche', false, false); expect(result.success).toBe(true); expect(result.data!.txHash).toBe('0xDepositNativeHash'); // When waitForReceipt=false, tx.wait() is never called }); it('should not wait for receipt when waitForReceipt=false in withdraw', async () => { const tx = { hash: '0xWithdrawTokenHash' }; mockContract.withdrawToken.mockResolvedValue(tx); const result = await client.withdraw('AVAX', 10, 'Avalanche', false, false); expect(result.success).toBe(true); expect(result.data!.txHash).toBe('0xWithdrawTokenHash'); // When waitForReceipt=false, tx.wait() is never called }); it('should not wait for receipt when waitForReceipt=false in transferPortfolio', async () => { const validAddress = '0x1234567890123456789012345678901234567890'; jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 20, available: 20, locked: 0 } } as any); const tx = { hash: '0xTransferTokenHash' }; mockContract.transferToken.mockResolvedValue(tx); const result = await client.transferPortfolio('AVAX', 10, validAddress, false); expect(result.success).toBe(true); expect(result.data!.txHash).toBe('0xTransferTokenHash'); // When waitForReceipt=false, tx.wait() is never called }); it('should not wait for receipt when waitForReceipt=false in addGas', async () => { const tx = { hash: '0xWithdrawNativeHash' }; mockContract.withdrawNative.mockResolvedValue(tx); const result = await client.addGas(10, false); expect(result.success).toBe(true); expect(result.data!.txHash).toBe('0xWithdrawNativeHash'); // When waitForReceipt=false, tx.wait() is never called }); it('should not wait for receipt when waitForReceipt=false in removeGas', async () => { const tx = { hash: '0xDepositNativeHash' }; mockContract.depositNative.mockResolvedValue(tx); const result = await client.removeGas(10, false); expect(result.success).toBe(true); expect(result.data!.txHash).toBe('0xDepositNativeHash'); // When waitForReceipt=false, tx.wait() is never called }); it('should return error when receipt status is not 1 in deposit', async () => { const tx = { hash: '0xDepositNativeHash', wait: jest.fn().mockResolvedValue({ status: 0, hash: '0xDepositNativeHash' }) }; mockContract.depositNative.mockResolvedValue(tx); const result = await client.deposit('AVAX', 10, 'Avalanche', false, true); expect(result.success).toBe(false); expect(result.error).toBe("Transaction reverted"); }); it('should return error when receipt status is not 1 in withdraw', async () => { const tx = { hash: '0xWithdrawTokenHash', wait: jest.fn().mockResolvedValue({ status: 0, hash: '0xWithdrawTokenHash' }) }; mockContract.withdrawToken.mockResolvedValue(tx); const result = await client.withdraw('AVAX', 10, 'Avalanche', false, true); expect(result.success).toBe(false); expect(result.error).toBe("Transaction reverted"); }); it('should return error when receipt status is not 1 in transferPortfolio', async () => { const validAddress = '0x1234567890123456789012345678901234567890'; jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 20, available: 20, locked: 0 } } as any); const tx = { hash: '0xTransferTokenHash', wait: jest.fn().mockResolvedValue({ status: 0, hash: '0xTransferTokenHash' }) }; mockContract.transferToken.mockResolvedValue(tx); const result = await client.transferPortfolio('AVAX', 10, validAddress, true); expect(result.success).toBe(false); expect(result.error).toBe("Transaction reverted"); }); it('should return error when receipt status is not 1 in addGas', async () => { const tx = { hash: '0xWithdrawNativeHash', wait: jest.fn().mockResolvedValue({ status: 0, hash: '0xWithdrawNativeHash' }) }; mockContract.withdrawNative.mockResolvedValue(tx); const result = await client.addGas(10, true); expect(result.success).toBe(false); expect(result.error).toBe("Transaction reverted"); }); it('should return error when receipt status is not 1 in removeGas', async () => { const tx = { hash: '0xDepositNativeHash', wait: jest.fn().mockResolvedValue({ status: 0, hash: '0xDepositNativeHash' }) }; mockContract.depositNative.mockResolvedValue(tx); const result = await client.removeGas(10, true); expect(result.success).toBe(false); expect(result.error).toBe("Transaction reverted"); }); it('should default to 18 decimals in transferPortfolio/getAllPortfolioBalances', async () => { const validAddress = '0x1234567890123456789012345678901234567890'; client.tokenData = {}; // Clear token data to force fallback // transferPortfolio check jest.spyOn(client, 'getPortfolioBalance').mockResolvedValue({ success: true, data: { total: 100, available: 100, locked: 0 } } as any); mockContract.transferToken.estimateGas.mockResolvedValue(100n); client.subnetChainId = 12345; const result = await client.transferPortfolio('UNKNOWN', 10, validAddress); expect(result.success).toBe(true); expect(mockContract.transferToken).toHaveBeenCalled(); // getAllPortfolioBalances check // Ensure view contract is set client.portfolioSubContractView = mockContract; mockContract.getBalances.mockResolvedValue([['0xSym'], [100n], [50n]]); const bals = await client.getAllPortfolioBalances(); expect(bals.success).toBe(true); expect(bals.data).toBeDefined(); }); }); describe('getDepositBridgeFee', () => { it('should return bridge fee in native units', async () => { mockContract.portfolioBridge.mockResolvedValue('0xBridgeAddr'); const result = await client.getDepositBridgeFee('AVAX', 10, 'Avalanche'); expect(result.success).toBe(true); expect(result.data).toBeCloseTo(1000 / 1e18, 12); }); it('should fail without signer', async () => { client.signer = undefined as any; const result = await client.getDepositBridgeFee('AVAX', 1, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('Signer required'); }); it('should fail when token not on source chain', async () => { client.tokenData = {}; const result = await client.getDepositBridgeFee('AVAX', 1, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('not supported'); }); }); describe('Branch Coverage - Fallbacks', () => { it('deposit should use "ETH" when native_symbol missing', async () => { // Chain config without native_symbol client.chainConfig = { 'Ethereum': { chain_id: 1, env: ENV.PROD_MULTI_AVAX } as any // No native_symbol }; client.portfolioMainContracts = { 'Ethereum': mockContract }; client.deployments['PortfolioMain'] = { ...client.deployments['PortfolioMain'], Ethereum: { address: '0xPortfolioMainEth', abi: [] }, }; client.connectedChainProviders['Ethereum'] = {} as any; client.tokenData = { 'ETH': { [ENV.PROD_MULTI_AVAX]: { address: '0x0', decimals: 18, chainId: 1, env: ENV.PROD_MULTI_AVAX } as any } }; mockContract.depositNative.estimateGas.mockResolvedValue(100n); // ETH is the default native symbol await client.deposit('ETH', 1, 'Ethereum'); expect(mockContract.depositNative).toHaveBeenCalled(); }); it('deposit should return error when token address not found (chainEnv null)', async () => { client.chainConfig = { 'Ethereum': { chain_id: 1 } as any // No env property }; client.portfolioMainContracts = { 'Ethereum': mockContract }; client.deployments['PortfolioMain'] = { ...client.deployments['PortfolioMain'], Ethereum: { address: '0xPortfolioMainEth', abi: [] }, }; client.connectedChainProviders['Ethereum'] = {} as any; client.tokenData = { 'USDC': { 'some-other-env': { address: '0xUSDC', decimals: 6 } as any } }; // USDC is not native, so ERC20 path with no chainEnv const result = await client.deposit('USDC', 100, 'Ethereum'); expect(result.success).toBe(false); expect(result.error).toContain('Token address for USDC not found on Ethereum'); }); it('_getBridgeFee should use signer when portfolioContract.runner missing', async () => { // Contract without runner but with portfolioBridge const contractNoRunner = { ...mockContract, runner: null, // No runner portfolioBridge: jest.fn().mockResolvedValue('0xBridgeAddr') }; const mockBridge = { getBridgeFee: jest.fn().mockResolvedValue(100n) }; (Contract as unknown as jest.Mock).mockImplementation(() => mockBridge); const fee = await client._getBridgeFee(contractNoRunner as any, 1, '0xSym', 100n); expect(fee).toBe(100n); }); it('_getBridgeFee should use provider when signer also missing', async () => { const contractNoRunner = { ...mockContract, runner: null, portfolioBridge: jest.fn().mockResolvedValue('0xBridgeAddr') }; client.signer = undefined as any; client.provider = { getBalance: jest.fn() } as any; // Provider exists const mockBridge = { getBridgeFee: jest.fn().mockResolvedValue(50n) }; (Contract as unknown as jest.Mock).mockImplementation(() => mockBridge); const fee = await client._getBridgeFee(contractNoRunner as any, 1, '0xSym', 100n); expect(fee).toBe(50n); }); it('_getBridgeFee should return 0n when signer.getAddress fails', async () => { const contractNoRunner = { ...mockContract, runner: null, portfolioBridge: jest.fn().mockResolvedValue('0xBridgeAddr') }; client.signer = {} as any; // Signer without getAddress - will throw const mockBridge = { getBridgeFee: jest.fn().mockResolvedValue(75n) }; (Contract as unknown as jest.Mock).mockImplementation(() => mockBridge); // When signer.getAddress() fails, the catch block returns 0n const fee = await client._getBridgeFee(contractNoRunner as any, 1, '0xSym', 100n); expect(fee).toBe(0n); }); it('_getBridgeFee should use subnetChainId fallback of 0', async () => { client.subnetChainId = undefined as any; // No subnetChainId mockContract.portfolioBridge.mockResolvedValue('0xBridgeAddr'); const mockBridge = { getBridgeFee: jest.fn().mockResolvedValue(25n) }; (Contract as unknown as jest.Mock).mockImplementation(() => mockBridge); const fee = await client._getBridgeFee(mockContract as any, 1, '0xSym', 100n); expect(fee).toBe(25n); expect(mockBridge.getBridgeFee).toHaveBeenCalledWith( 1, 0, '0xSym', 100n, expect.any(String), '0x00' ); }); }); describe('decimals fallback from subnetChainId to chainId', () => { it('getPortfolioBalance should use chainId decimals when subnetChainId decimals not found', async () => { mockContract.getBalance.mockResolvedValue([100n, 50n, 50n]); // Token only has decimals for chainId (43114), NOT for subnetChainId (12345) client.tokenData = { 'SPECIAL': { 'prod': { address: '0xSPEC', decimals: 8, chainId: 43114, env: 'prod' } as any } }; client.subnetChainId = 12345; client.chainId = 43114; const result = await client.getPortfolioBalance('SPECIAL'); expect(result.success).toBe(true); // The fallback path: _getTokenDecimals(SPECIAL, 12345) returns null, // then _getTokenDecimals(SPECIAL, 43114) returns 8 }); it('getAllPortfolioBalances should use chainId decimals when subnetChainId decimals not found', async () => { // Return one page with a symbol, then empty page to stop mockContract.getBalances .mockResolvedValueOnce([['0xSpecial'], [200n], [150n]]) .mockResolvedValueOnce([[], [], []]); // fromBytes32 should return the symbol name (Utils.fromBytes32 as jest.Mock).mockReturnValue('SPECIAL'); // Token only has decimals for chainId (43114), NOT for subnetChainId (12345) client.tokenData = { 'SPECIAL': { 'prod': { address: '0xSPEC', decimals: 8, chainId: 43114, env: 'prod' } as any } }; client.subnetChainId = 12345; client.chainId = 43114; const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(result.data!['SPECIAL']).toBeDefined(); }); it('getPortfolioBalance should fallback to 18 decimals when token unknown on all chains', async () => { mockContract.getBalance.mockResolvedValue([100n, 50n, 50n]); // Empty tokenData so _getTokenDecimals returns null for every chainId client.tokenData = {}; client.subnetChainId = 12345; client.chainId = 43114; const result = await client.getPortfolioBalance('NOTOKEN'); expect(result.success).toBe(true); // _getTokenDecimals('NOTOKEN', 12345) -> null (enter if block) // _getTokenDecimals('NOTOKEN', 43114) -> null, so null ?? 18 = 18 expect(result.data!.total).toBe(10); // Mocked Utils returns '10' }); it('getAllPortfolioBalances should fallback to 18 decimals when token unknown on all chains', async () => { mockContract.getBalances .mockResolvedValueOnce([['0xNoToken'], [300n], [200n]]) .mockResolvedValueOnce([[], [], []]); (Utils.fromBytes32 as jest.Mock).mockReturnValue('NOTOKEN'); // Empty tokenData so _getTokenDecimals returns null for every chainId client.tokenData = {}; client.subnetChainId = 12345; client.chainId = 43114; const result = await client.getAllPortfolioBalances(); expect(result.success).toBe(true); expect(result.data!['NOTOKEN']).toBeDefined(); // _getTokenDecimals('NOTOKEN', 12345) -> null (enter if block) // _getTokenDecimals('NOTOKEN', 43114) -> null, so null ?? 18 = 18 }); }); describe('_resolveTokenDecimals', () => { it('should return subnet decimals when available', () => { client.subnetChainId = 12345; client.chainId = 43114; client.tokenData = { 'AVAX': { 'subnet': { decimals: 8, chainId: 12345 } as any } }; expect((client as any)._resolveTokenDecimals('AVAX')).toBe(8); }); it('should fall back to connected chain decimals', () => { client.subnetChainId = 12345; client.chainId = 43114; client.tokenData = { 'AVAX': { 'mainnet': { decimals: 6, chainId: 43114 } as any } }; expect((client as any)._resolveTokenDecimals('AVAX')).toBe(6); }); it('should fall back to 18 when no decimals found anywhere', () => { client.subnetChainId = 12345; client.chainId = 43114; client.tokenData = {}; expect((client as any)._resolveTokenDecimals('UNKNOWN')).toBe(18); }); }); describe('ERC20 allowance revoke on tx failure', () => { it('revokes allowance when depositToken throws', async () => { const txError = new Error('depositToken reverted'); mockContract.depositToken.mockRejectedValueOnce(txError); const result = await client.deposit('USDT', 10, 'Avalanche'); expect(result.success).toBe(false); const approveCalls = (mockContract.approve as jest.Mock).mock.calls; const revokeCall = approveCalls.find(args => args[1] === 0n); expect(revokeCall).toBeDefined(); expect(revokeCall![0]).toBe('0xContractAddress'); }); it('revokes allowance when deposit receipt reports revert (status=0)', async () => { mockContract.depositToken.mockResolvedValueOnce({ hash: '0xRevertedHash', wait: jest.fn().mockResolvedValue({ status: 0 }), }); const result = await client.deposit('USDT', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('Transaction reverted'); const approveCalls = (mockContract.approve as jest.Mock).mock.calls; expect(approveCalls.some(args => args[1] === 0n)).toBe(true); }); it('does not call approve(_, 0n) when native deposit fails (no allowance was granted)', async () => { mockContract.depositNative.estimateGas.mockRejectedValueOnce(new Error('native fail')); const result = await client.deposit('AVAX', 10, 'Avalanche'); expect(result.success).toBe(false); const approveCalls = (mockContract.approve as jest.Mock).mock.calls; expect(approveCalls.some(args => args[1] === 0n)).toBe(false); }); it('original deposit tx error wins when secondary revoke also fails', async () => { const txError = new Error('original depositToken error'); mockContract.depositToken.mockRejectedValueOnce(txError); (mockContract.approve as jest.Mock).mockImplementation((_spender: string, amount: bigint) => { if (amount === 0n) return Promise.reject(new Error('revoke failure')); return Promise.resolve({ wait: jest.fn().mockResolvedValue({}) }); }); const result = await client.deposit('USDT', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('original depositToken error'); expect(result.error).not.toContain('revoke failure'); }); it('revokes allowance when withdrawToken throws', async () => { const txError = new Error('withdrawToken reverted'); mockContract.withdrawToken.mockRejectedValueOnce(txError); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); const approveCalls = (mockContract.approve as jest.Mock).mock.calls; expect(approveCalls.some(args => args[1] === 0n)).toBe(true); }); it('does not call approve(_, 0n) when no subnet token address exists', async () => { // Drop the subnet token entry so the withdraw allowance branch is skipped delete client.tokenData['AVAX'][ENV.PROD_MULTI_SUBNET]; mockContract.withdrawToken.mockRejectedValueOnce(new Error('withdraw fail')); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); const approveCalls = (mockContract.approve as jest.Mock).mock.calls; expect(approveCalls.some(args => args[1] === 0n)).toBe(false); }); it('swallows secondary revoke failure when deposit receipt reverts', async () => { mockContract.depositToken.mockResolvedValueOnce({ hash: '0xRevertedHash', wait: jest.fn().mockResolvedValue({ status: 0 }), }); (mockContract.approve as jest.Mock).mockImplementation((_spender: string, amount: bigint) => { if (amount === 0n) return Promise.reject(new Error('revoke failure')); return Promise.resolve({ wait: jest.fn().mockResolvedValue({}) }); }); const result = await client.deposit('USDT', 10, 'Avalanche'); expect(result.success).toBe(false); expect(result.error).toContain('Transaction reverted'); expect(result.error).not.toContain('revoke failure'); }); it('original withdraw tx error wins when secondary revoke also fails', async () => { const txError = new Error('original withdrawToken error'); mockContract.withdrawToken.mockRejectedValueOnce(txError); (mockContract.approve as jest.Mock).mockImplementation((_spender: string, amount: bigint) => { if (amount === 0n) return Promise.reject(new Error('revoke failure')); return Promise.resolve({ wait: jest.fn().mockResolvedValue({}) }); }); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); expect(result.error).toContain('original withdrawToken error'); expect(result.error).not.toContain('revoke failure'); }); it('_revokeAllowance falls back to this.signer when no runner is provided', async () => { await (client as any)._revokeAllowance('0xtok', '0xspender'); expect(Contract).toHaveBeenCalledWith('0xtok', expect.any(Array), mockSigner); expect(mockContract.approve).toHaveBeenCalledWith('0xspender', 0n); }); it('swallows secondary revoke failure when withdraw receipt reverts', async () => { mockContract.withdrawToken.mockResolvedValueOnce({ hash: '0xRevertedHash', wait: jest.fn().mockResolvedValue({ status: 0 }), }); (mockContract.approve as jest.Mock).mockImplementation((_spender: string, amount: bigint) => { if (amount === 0n) return Promise.reject(new Error('revoke failure')); return Promise.resolve({ wait: jest.fn().mockResolvedValue({}) }); }); const result = await client.withdraw('AVAX', 10, 'Destination'); expect(result.success).toBe(false); expect(result.error).toContain('Transaction reverted'); expect(result.error).not.toContain('revoke failure'); }); }); describe('getChainTokenBalances', () => { const validAddress = '0x1234567890123456789012345678901234567890'; beforeEach(() => { // resolveChainReference exists on the base client; in this fixture // the mock just returns the chain name as canonical. jest.spyOn(client, 'resolveChainReference').mockImplementation( ((c: string | number) => ({ success: true, data: { canonicalName: String(c), chainId: 0, originalInput: c, isDexalotL1: c === 'Dexalot L1' }, })) as any ); jest.spyOn(client, 'getChainWalletBalance').mockImplementation( async (chain: string, token: string) => { if (token === 'UNK') { return { success: false, error: `Token ${token} not available on chain ${chain}.` } as any; } if (token === 'BOOM') { return { success: false, error: 'something broke' } as any; } return { success: true, data: { chain, symbol: token, balance: `${token.length}.0` } } as any; } ); }); it('returns a flat token -> balance map for an explicit token list', async () => { const result = await client.getChainTokenBalances('Avalanche', ['AVAX', 'USDC'], validAddress); expect(result.success).toBe(true); expect(result.data).toEqual({ AVAX: '4.0', USDC: '4.0' }); }); it('sorts and dedupes tokens before delegating (order-insensitive cache key)', async () => { const r1 = await client.getChainTokenBalances('Avalanche', ['AVAX', 'USDC'], validAddress); (client.getChainWalletBalance as jest.Mock).mockClear(); // Second call with the same set in different order + a duplicate must // serve from cache (no further getChainWalletBalance calls). const r2 = await client.getChainTokenBalances('Avalanche', ['USDC', 'AVAX', 'AVAX'], validAddress); expect(r1.success).toBe(true); expect(r2.success).toBe(true); expect(r1.data).toEqual(r2.data); expect(client.getChainWalletBalance).not.toHaveBeenCalled(); }); it('aggregates unknown tokens into a single error', async () => { const result = await client.getChainTokenBalances('Avalanche', ['AVAX', 'UNK'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('Unknown tokens on chain Avalanche'); expect(result.error).toContain('UNK'); }); it('aggregates non-unknown errors into a semicolon-joined list', async () => { const result = await client.getChainTokenBalances('Avalanche', ['AVAX', 'BOOM'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('BOOM: something broke'); }); it('captures thrown errors via _sanitizeError', async () => { (client.getChainWalletBalance as jest.Mock).mockImplementationOnce(async () => { throw new Error('network blip'); }); const result = await client.getChainTokenBalances('Avalanche', ['AVAX'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('AVAX'); expect(result.error).toContain('network blip'); }); it('rejects an empty or non-array tokens argument', async () => { expect((await client.getChainTokenBalances('Avalanche', [], validAddress)).success).toBe(false); expect((await client.getChainTokenBalances('Avalanche', null as any, validAddress)).success).toBe(false); }); it('rejects an empty / non-string chain argument', async () => { expect((await client.getChainTokenBalances('', ['AVAX'], validAddress)).success).toBe(false); expect((await client.getChainTokenBalances(' ', ['AVAX'], validAddress)).success).toBe(false); expect((await client.getChainTokenBalances(123 as any, ['AVAX'], validAddress)).success).toBe(false); }); it('rejects malformed token symbols', async () => { const result = await client.getChainTokenBalances('Avalanche', ['AVAX', 'bad token'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('tokens'); }); it('propagates an unresolved chain error', async () => { (client.resolveChainReference as jest.Mock).mockReturnValueOnce({ success: false, error: "Chain 'Solana' is not recognized", }); const result = await client.getChainTokenBalances('Solana', ['AVAX'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('not recognized'); }); it('uses a static fallback when resolveChainReference returns no error string', async () => { (client.resolveChainReference as jest.Mock).mockReturnValueOnce({ success: false, }); const result = await client.getChainTokenBalances('Solana', ['AVAX'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain("Could not resolve chain 'Solana'"); }); it('treats a failing per-token Result with no error string as unknown', async () => { (client.getChainWalletBalance as jest.Mock).mockImplementation(async (_c, t) => { if (t === 'AVAX') return { success: true, data: { balance: '1.0' } }; return { success: false } as any; // no error message }); const result = await client.getChainTokenBalances('Avalanche', ['AVAX', 'X'], validAddress); expect(result.success).toBe(false); expect(result.error).toContain('X: unknown error'); }); it('emits empty-string balance when getChainWalletBalance returns data without a balance field', async () => { (client.getChainWalletBalance as jest.Mock).mockImplementation(async (_c, t) => ({ success: true, data: { chain: 'Avalanche', symbol: t }, // balance omitted })); const result = await client.getChainTokenBalances('Avalanche', ['AVAX'], validAddress); expect(result.success).toBe(true); expect(result.data).toEqual({ AVAX: '' }); }); it('returns a fail Result when address is required but not provided and signer is missing', async () => { client.signer = undefined as any; const result = await client.getChainTokenBalances('Avalanche', ['AVAX']); expect(result.success).toBe(false); expect(result.error).toContain('Address required'); }); }); describe('getCombinedTransfers', () => { // Real backend route is `/api/trading/signed/transferscombined` (signed). // Verified empirically via OPTIONS preflight: the `/privapi/...` variant // 404s while `/api/trading/signed/transferscombined` 204s. Response // shape is `{ count, rows: DBTransfer[] }` with snake_case fields and // numeric enums for `status` / `action_type` / `bridge`. Quantities and // fees arrive as already-display-decimal numeric strings (the official // frontend reads them straight through Big.js with no decimals divide). beforeEach(() => { // Disable retry so rejection from the spy doesn't get retried. client.config.retryEnabled = false; // Default x-signature header so _getAuthHeaders doesn't try to // re-sign during the test; individual tests may override. (client as any)._cachedSignature = `${mockAddress}:sig`; }); const ROW_DEPOSIT_COMPLETED = { status: 0, // COMPLETED traderaddress: '0xtrader', action_type: 1, // DEPOSITED bridge: 0, // LAYER0 bridge_url: 'https://layerzeroscan.com/tx/0xsrc', nonce: 42, symbol: 'USDC', quantity: '100.5', fee: '0.001', source_env: 'production-multi-avax', source_chain_id: 43114, source_tx: '0xsrc', source_ts: '2026-05-01T00:00:00.000Z', target_env: 'subnet', target_chain_id: 12345, target_tx: '0xtgt', target_ts: '2026-05-01T00:01:00.000Z', nbrof_rows: '17', }; const ROW_GAS_INFLIGHT = { status: 1, // INFLIGHT traderaddress: '0xtrader', action_type: 8, // ADD_GAS bridge: -1, // NATIVE bridge_url: '', nonce: -1, symbol: 'ALOT', quantity: '5.0', fee: '0', source_env: 'subnet', source_chain_id: 12345, source_tx: '0xgas', source_ts: '2026-05-02T00:00:00.000Z', target_env: null, target_chain_id: null, target_tx: null, target_ts: null, nbrof_rows: '17', }; it('returns Result.fail when no signer is configured', async () => { client.signer = undefined as any; const result = await client.getCombinedTransfers(); expect(result.success).toBe(false); expect(result.error).toContain('Signer not configured'); }); it('returns canonical Transfer[] normalized from the {count, rows} envelope', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ count: 2, rows: [ROW_DEPOSIT_COMPLETED, ROW_GAS_INFLIGHT], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([ { actionType: 'DEPOSITED', status: 'COMPLETED', symbol: 'USDC', quantity: 100.5, fee: 0.001, traderAddress: '0xtrader', bridge: 'LAYER0', bridgeUrl: 'https://layerzeroscan.com/tx/0xsrc', nonce: 42, sourceEnv: 'production-multi-avax', sourceChainId: 43114, sourceTx: '0xsrc', sourceTs: 1777593600, // 2026-05-01T00:00:00.000Z as unix seconds targetEnv: 'subnet', targetChainId: 12345, targetTx: '0xtgt', targetTs: 1777593660, // 2026-05-01T00:01:00.000Z as unix seconds }, { actionType: 'ADD_GAS', status: 'INFLIGHT', symbol: 'ALOT', quantity: 5, fee: 0, traderAddress: '0xtrader', bridge: 'NATIVE', bridgeUrl: '', nonce: -1, sourceEnv: 'subnet', sourceChainId: 12345, sourceTx: '0xgas', sourceTs: 1777680000, // 2026-05-02T00:00:00.000Z as unix seconds targetEnv: null, targetChainId: null, targetTx: null, targetTs: null, }, ]); // Timestamps are coerced to unix seconds (numbers, not ISO strings). expect(typeof result.data![0].sourceTs).toBe('number'); expect(typeof result.data![0].targetTs).toBe('number'); // A row with no target leg yields targetTs === null alongside the // other nullable target-* fields. expect(typeof result.data![1].sourceTs).toBe('number'); expect(result.data![1].targetTs).toBeNull(); expect(result.data![1].targetEnv).toBeNull(); expect(result.data![1].targetChainId).toBeNull(); expect(result.data![1].targetTx).toBeNull(); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.TRADING_COMBINED_TRANSFERS, expect.objectContaining({ headers: expect.objectContaining({ 'x-signature': `${mockAddress}:sig` }), params: expect.objectContaining({ itemsperpage: 100, pageno: 1, }), }) ); }); it('accepts a top-level array response shape as a fallback', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce([ ROW_DEPOSIT_COMPLETED, ]); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toHaveLength(1); expect(result.data![0].symbol).toBe('USDC'); }); it('translates limit/offset -> itemsperpage/pageno and fromTs/toTs -> periodfrom/periodto', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ count: 0, rows: [] }); await client.getCombinedTransfers({ symbol: 'usdc', // lowercase to verify normalization fromTs: 1777593600, // 2026-05-01T00:00:00Z unix seconds toTs: 1780185600, // 2026-05-31T00:00:00Z unix seconds limit: 50, offset: 100, // floor(100 / 50) + 1 = page 3 }); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.TRADING_COMBINED_TRANSFERS, expect.objectContaining({ params: { itemsperpage: 50, pageno: 3, symbol: 'USDC', // fromTs/toTs (unix seconds) are converted to ISO-8601 // strings — the backend's periodfrom/periodto reject raw // unix integers with "ISO Date format problem". periodfrom: new Date(1777593600 * 1000).toISOString(), periodto: new Date(1780185600 * 1000).toISOString(), }, }) ); }); it('defaults to itemsperpage=100 and pageno=1 when no opts supplied', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ count: 0, rows: [] }); await client.getCombinedTransfers(); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.TRADING_COMBINED_TRANSFERS, expect.objectContaining({ params: { itemsperpage: 100, pageno: 1 }, }) ); }); it('caches per (address, opts) — repeated identical calls share one fetch', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue({ count: 0, rows: [] }); await client.getCombinedTransfers(); await client.getCombinedTransfers(); expect(apiSpy).toHaveBeenCalledTimes(1); }); it('uses distinct cache slots per opts tuple', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue({ count: 0, rows: [] }); await client.getCombinedTransfers(); await client.getCombinedTransfers({ symbol: 'USDC' }); await client.getCombinedTransfers({ offset: 100 }); // maps to a different page expect(apiSpy).toHaveBeenCalledTimes(3); }); it('returns Result.fail when _apiCall rejects', async () => { jest.spyOn(client as any, '_apiCall').mockRejectedValueOnce( new Error('upstream down') ); const result = await client.getCombinedTransfers(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('returns an empty array when the API returns an empty rows list', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 0, rows: [], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('skips malformed rows that are missing required fields', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 3, rows: [ ROW_DEPOSIT_COMPLETED, { status: 0 }, // missing nearly everything null, // not even an object ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toHaveLength(1); expect(result.data![0].symbol).toBe('USDC'); }); it('skips rows whose action_type or status is not a known enum value', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 2, rows: [ { ...ROW_DEPOSIT_COMPLETED, action_type: 999 }, { ...ROW_DEPOSIT_COMPLETED, status: 999 }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('falls back to BRIDGES.NATIVE-like label when bridge enum is unrecognised', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 1, rows: [{ ...ROW_DEPOSIT_COMPLETED, bridge: 999 }], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toHaveLength(1); // Unknown bridge id is mapped to the catch-all `NATIVE` label — // the row is still returned because action_type + status are valid. expect(result.data![0].bridge).toBe('NATIVE'); }); it('tolerates a non-array `rows` field by returning empty', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 0, rows: 'not-an-array', }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('returns Result.fail when the response is neither object nor array', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce( 'just a string' ); const result = await client.getCombinedTransfers(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('reuses _getAuthHeaders to attach the x-signature header', async () => { // Force fresh sign by clearing the cached header and config. (client as any)._cachedSignature = undefined; mockSigner.signMessage = jest.fn().mockResolvedValue('0xdeadbeef'); const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValueOnce({ count: 0, rows: [] }); await client.getCombinedTransfers(); expect(apiSpy).toHaveBeenCalledWith( 'get', ENDPOINTS.TRADING_COMBINED_TRANSFERS, expect.objectContaining({ headers: expect.objectContaining({ 'x-signature': `${mockAddress}:0xdeadbeef`, }), }) ); }); it('uses distinct cache slots per signer address', async () => { const apiSpy = jest .spyOn(client as any, '_apiCall') .mockResolvedValue({ count: 0, rows: [] }); await client.getCombinedTransfers(); mockSigner.getAddress.mockResolvedValueOnce('0xOtherUser'); await client.getCombinedTransfers(); expect(apiSpy).toHaveBeenCalledTimes(2); }); it('returns Result.fail when signer.getAddress rejects', async () => { mockSigner.getAddress.mockRejectedValueOnce(new Error('locked')); const result = await client.getCombinedTransfers(); expect(result.success).toBe(false); expect(result.error).toBeDefined(); }); it('accepts numeric quantity / fee values as a forward-compat fallback', async () => { // Backend currently emits Big-strings, but the SDK also // accepts plain numbers in case the wire shape ever flips. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 1, rows: [{ ...ROW_DEPOSIT_COMPLETED, quantity: 200, fee: 0.5 }], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toHaveLength(1); expect(result.data![0].quantity).toBe(200); expect(result.data![0].fee).toBe(0.5); }); it('drops rows whose numeric quantity is not a finite non-negative value', async () => { jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 3, rows: [ { ...ROW_DEPOSIT_COMPLETED, quantity: -1 }, { ...ROW_DEPOSIT_COMPLETED, quantity: Number.POSITIVE_INFINITY }, { ...ROW_DEPOSIT_COMPLETED, quantity: Number.NaN }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('drops rows whose status/symbol fields are the wrong type', async () => { // Status as a string (instead of number) → row dropped. // Symbol as a number (instead of string) → row dropped. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 2, rows: [ { ...ROW_DEPOSIT_COMPLETED, status: 'COMPLETED' as any }, { ...ROW_DEPOSIT_COMPLETED, symbol: 999 as any }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('drops rows whose quantity is an empty / non-parseable string', async () => { // Empty string → null → row dropped. // Non-numeric string → parseFloat returns NaN → null → dropped. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 2, rows: [ { ...ROW_DEPOSIT_COMPLETED, quantity: ' ' }, { ...ROW_DEPOSIT_COMPLETED, quantity: 'not-a-number' }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toEqual([]); }); it('fills in safe defaults when optional fields have wrong types or are missing', async () => { // Minimal row — only the required `action_type` + `status` + // `symbol` + `quantity` are well-typed; every other field is // either missing, the wrong type, or has an unknown enum // value. The normalizer should still emit a row with the // sentinel defaults documented on the Transfer type. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 1, rows: [ { action_type: 1, // DEPOSITED status: 0, // COMPLETED symbol: 'USDC', quantity: '100', // fee missing → defaults to 0 // traderaddress wrong type → defaults to '' traderaddress: 999, // bridge missing → defaults to -1 / NATIVE // bridge_url wrong type → defaults to '' bridge_url: null, // nonce missing → defaults to -1 // source_env wrong type → defaults to '' source_env: 5, // source_chain_id missing → defaults to 0 // source_tx missing → defaults to '' // source_ts missing → coerces to 0 (non-null sentinel) // target_env / target_chain_id / target_tx wrong // type → default to null; target_ts is a bare number // → coerced to unix seconds (11) target_env: 7, target_chain_id: 'not-a-number', target_tx: 9, target_ts: 11, }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); expect(result.data).toHaveLength(1); expect(result.data![0]).toEqual({ actionType: 'DEPOSITED', status: 'COMPLETED', symbol: 'USDC', quantity: 100, fee: 0, traderAddress: '', bridge: 'NATIVE', bridgeUrl: '', nonce: -1, sourceEnv: '', sourceChainId: 0, sourceTx: '', sourceTs: 0, targetEnv: null, targetChainId: null, targetTx: null, targetTs: 11, }); }); it('coerces source_ts/target_ts across ISO-string, numeric, and unparseable inputs', async () => { // Exercises both branches of _coerceTransferTs: // - source_ts: numeric-string (non-ISO) → _coerceTimestampSeconds path // - target_ts: ISO-8601 string → Date.parse path // and the missing/unparseable fallbacks on a second row. jest.spyOn(client as any, '_apiCall').mockResolvedValueOnce({ count: 3, rows: [ { ...ROW_DEPOSIT_COMPLETED, source_ts: '1777593600', // numeric string (seconds) target_ts: '2026-05-01T00:01:00.000Z', // ISO string }, { ...ROW_GAS_INFLIGHT, source_ts: 'not-a-date', // unparseable string → 0 sentinel target_ts: null, // absent target leg → null }, { ...ROW_GAS_INFLIGHT, source_ts: ' ', // whitespace-only string → 0 sentinel target_ts: 1777680000, // bare numeric (seconds) }, ], }); const result = await client.getCombinedTransfers(); expect(result.success).toBe(true); // Numeric-string seconds pass straight through. expect(result.data![0].sourceTs).toBe(1777593600); // ISO string is parsed to unix seconds. expect(result.data![0].targetTs).toBe(1777593660); // Unparseable source string falls back to the 0 sentinel. expect(result.data![1].sourceTs).toBe(0); // Null target leg stays null. expect(result.data![1].targetTs).toBeNull(); // Whitespace-only string is treated as empty → 0 sentinel; // bare numeric target_ts passes through _coerceTimestampSeconds. expect(result.data![2].sourceTs).toBe(0); expect(result.data![2].targetTs).toBe(1777680000); }); }); });