{"_id":"lighter-sdk-client","_rev":"74-c8d00e4b80c242ecbddc03cf1e5c9dcb","name":"lighter-sdk-client","dist-tags":{"latest":"0.2.34"},"versions":{"0.2.28":{"name":"lighter-sdk-client","version":"0.2.28","keywords":[],"author":"","license":"ISC","_id":"lighter-sdk-client@0.2.28","maintainers":[{"name":"0xpye","email":"pye@swellnetwork.io"}],"dist":{"shasum":"0bdf9be09fbf0bbe53eb5936dae7574fa854508e","tarball":"https://registry.npmjs.org/lighter-sdk-client/-/lighter-sdk-client-0.2.28.tgz","fileCount":378,"integrity":"sha512-WtdojOxDydcYG0lCbWTd8XuXRuWEDUB6gvfs546/J8+tkRmUFiFncYuL1W0okfapH4ZFV3NAsc1b+HYkPfUUgg==","signatures":[{"sig":"MEUCIQCSCwqZ71+OlorpB5LXw70T+Ed8Cw2twgOLCIiqaOmDIQIgNV/D7DigKEhSXX8Njy6bdLH0TUtPK870XtQParLdk3o=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":527365},"main":"./dist/index.js","type":"module","_from":"file:lighter-sdk-client-0.2.28.tgz","types":"./dist/index.d.ts","module":"./dist/index.cjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.cjs","require":"./dist/index.js"}},"scripts":{"lint":"eslint . --ext .ts,.tsx","build":"tsup src --dts","lint:fix":"eslint . --ext .ts,.tsx --fix"},"_npmUser":{"name":"0xpye","email":"pye@swellnetwork.io"},"_resolved":"/private/var/folders/w0/xbxl76mn08g6fgyk86cf76v40000gn/T/47f9774c3c9d4b99aa04197f1ee81349/lighter-sdk-client-0.2.28.tgz","_integrity":"sha512-WtdojOxDydcYG0lCbWTd8XuXRuWEDUB6gvfs546/J8+tkRmUFiFncYuL1W0okfapH4ZFV3NAsc1b+HYkPfUUgg==","_npmVersion":"11.4.2","description":"Unofficial Lighter SDK Client for TypeScript/JavaScript","directories":{},"_nodeVersion":"24.4.1","dependencies":{"tsx":"^4.21.0","viem":"~2.47.5","axios":"1.13.6","wagmi":"^3.5.0","@tanstack/react-query":"^5.91.0","reconnecting-websocket":"^4.4.0"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.5.1","eslint":"^10.0.3","globals":"^17.4.0","@eslint/js":"^10.0.1","typescript":"^5.9.3","@types/node":"^25.5.0","@eslint/compat":"^2.0.3","@eslint/eslintrc":"^3.3.5","eslint-config-next":"16.2.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.5","@typescript-eslint/parser":"^8.57.1","eslint-plugin-react-hooks":"^7.0.1","@typescript-eslint/eslint-plugin":"^8.57.1","eslint-plugin-simple-import-sort":"^12.1.1"},"_npmOperationalInternal":{"tmp":"tmp/lighter-sdk-client_0.2.28_1773893589274_0.8819506787694567","host":"s3://npm-registry-packages-npm-production"}},"0.2.32":{"name":"lighter-sdk-client","version":"0.2.32","keywords":[],"author":"","license":"ISC","_id":"lighter-sdk-client@0.2.32","maintainers":[{"name":"0xpye","email":"pye@swellnetwork.io"}],"dist":{"shasum":"5c28fa57483f2efd41d9517eff87bc112313dde6","tarball":"https://registry.npmjs.org/lighter-sdk-client/-/lighter-sdk-client-0.2.32.tgz","fileCount":378,"integrity":"sha512-tti7h+dxFz9uzQ2BXTeLu1vGKdJEPahylPtwJfpTHZuPEdZAp51biwyKQ338KQv8wzbnuzRfGH8nNIDoBaK62g==","signatures":[{"sig":"MEQCIGhrEqzqD6wQjyPp3TgR5gQsQ3Kz5eIllBzAD3rTvk/JAiAUo/N9E/EohbAkb2tZbPWtqv1xRbnWDMp1s6WX8rzC+Q==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":527529},"main":"./dist/index.js","type":"module","_from":"file:lighter-sdk-client-0.2.32.tgz","types":"./dist/index.d.ts","module":"./dist/index.cjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.cjs","require":"./dist/index.js"}},"scripts":{"lint":"eslint . --ext .ts,.tsx","build":"tsup src --dts","lint:fix":"eslint . --ext .ts,.tsx --fix"},"_npmUser":{"name":"0xpye","email":"pye@swellnetwork.io"},"_resolved":"/private/var/folders/w0/xbxl76mn08g6fgyk86cf76v40000gn/T/0cc0736e2a1d274d9e7fa0a43713fbf8/lighter-sdk-client-0.2.32.tgz","_integrity":"sha512-tti7h+dxFz9uzQ2BXTeLu1vGKdJEPahylPtwJfpTHZuPEdZAp51biwyKQ338KQv8wzbnuzRfGH8nNIDoBaK62g==","_npmVersion":"11.4.2","description":"Unofficial Lighter SDK Client for TypeScript/JavaScript","directories":{},"_nodeVersion":"24.4.1","dependencies":{"tsx":"^4.21.0","viem":"~2.47.5","axios":"1.13.6","wagmi":"^3.5.0","@tanstack/react-query":"^5.91.0","reconnecting-websocket":"^4.4.0"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.5.1","eslint":"^10.0.3","globals":"^17.4.0","@eslint/js":"^10.0.1","typescript":"^5.9.3","@types/node":"^25.5.0","@eslint/compat":"^2.0.3","@eslint/eslintrc":"^3.3.5","eslint-config-next":"16.2.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.5","@typescript-eslint/parser":"^8.57.1","eslint-plugin-react-hooks":"^7.0.1","@typescript-eslint/eslint-plugin":"^8.57.1","eslint-plugin-simple-import-sort":"^12.1.1"},"_npmOperationalInternal":{"tmp":"tmp/lighter-sdk-client_0.2.32_1774424492001_0.1393600850441441","host":"s3://npm-registry-packages-npm-production"}},"0.2.33":{"name":"lighter-sdk-client","version":"0.2.33","keywords":[],"author":"","license":"ISC","_id":"lighter-sdk-client@0.2.33","maintainers":[{"name":"0xpye","email":"pye@swellnetwork.io"}],"dist":{"shasum":"57d61422e66c3e26dbd9d419ed306742165569c5","tarball":"https://registry.npmjs.org/lighter-sdk-client/-/lighter-sdk-client-0.2.33.tgz","fileCount":378,"integrity":"sha512-EEpAawNQp8Cehc21Z4YY7UCJnBlS0PLL6SY7wFIJAntNZVQPsjTJGyNXJe6WYtts7+1TzCjQ06LvkBhZCzdjjg==","signatures":[{"sig":"MEQCICpXdR9FcWNgzRdNgqtnoG0/pJi/1L674TY6M/D1CxOMAiBHheIr7lw9/eQJqXLvpp8KKc2GYsDjGwPtYbSqMQV4Rg==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":527530},"main":"./dist/index.js","type":"module","_from":"file:lighter-sdk-client-0.2.33.tgz","types":"./dist/index.d.ts","module":"./dist/index.cjs","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.cjs","require":"./dist/index.js"}},"scripts":{"lint":"eslint . --ext .ts,.tsx","build":"tsup src --dts","lint:fix":"eslint . --ext .ts,.tsx --fix"},"_npmUser":{"name":"0xpye","email":"pye@swellnetwork.io"},"_resolved":"/private/var/folders/w0/xbxl76mn08g6fgyk86cf76v40000gn/T/2651952f8e2502301d4c510a810b8c98/lighter-sdk-client-0.2.33.tgz","_integrity":"sha512-EEpAawNQp8Cehc21Z4YY7UCJnBlS0PLL6SY7wFIJAntNZVQPsjTJGyNXJe6WYtts7+1TzCjQ06LvkBhZCzdjjg==","_npmVersion":"11.4.2","description":"Unofficial Lighter SDK Client for TypeScript/JavaScript","directories":{},"_nodeVersion":"24.4.1","dependencies":{"tsx":"^4.21.0","viem":"~2.47.17","axios":"1.15.0","wagmi":"^3.6.1","@tanstack/react-query":"^5.99.0","reconnecting-websocket":"^4.4.0"},"_hasShrinkwrap":false,"devDependencies":{"tsup":"^8.5.1","eslint":"^10.2.0","globals":"^17.5.0","@eslint/js":"^10.0.1","typescript":"^6.0.2","@types/node":"^25.6.0","@eslint/compat":"^2.0.5","@eslint/eslintrc":"^3.3.5","eslint-config-next":"16.2.3","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.5","@typescript-eslint/parser":"^8.58.2","eslint-plugin-react-hooks":"^7.0.1","@typescript-eslint/eslint-plugin":"^8.58.2","eslint-plugin-simple-import-sort":"^13.0.0"},"_npmOperationalInternal":{"tmp":"tmp/lighter-sdk-client_0.2.33_1776140918266_0.21332741154641766","host":"s3://npm-registry-packages-npm-production"}},"0.2.34":{"name":"lighter-sdk-client","version":"0.2.34","description":"Unofficial Lighter SDK Client for TypeScript/JavaScript","keywords":[],"license":"ISC","author":"","type":"module","exports":{".":{"types":"./dist/index.d.ts","require":"./dist/index.js","import":"./dist/index.cjs"}},"types":"./dist/index.d.ts","main":"./dist/index.js","module":"./dist/index.cjs","dependencies":{"@tanstack/react-query":"^5.100.9","axios":"1.16.0","reconnecting-websocket":"^4.4.0","tsx":"^4.21.0","viem":"~2.48.8","wagmi":"^3.6.9"},"devDependencies":{"@eslint/compat":"^2.0.5","@eslint/eslintrc":"^3.3.5","@eslint/js":"^10.0.1","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.2","@typescript-eslint/parser":"^8.59.2","eslint":"^10.3.0","eslint-config-next":"16.2.4","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.5","eslint-plugin-react-hooks":"^7.1.1","eslint-plugin-simple-import-sort":"^13.0.0","globals":"^17.6.0","tsup":"^8.5.1","typescript":"^6.0.3"},"scripts":{"build":"tsup src --dts","lint":"eslint . --ext .ts,.tsx","lint:fix":"eslint . --ext .ts,.tsx --fix"},"_id":"lighter-sdk-client@0.2.34","_integrity":"sha512-HNo2ChjItDrIoxfsFHLHFh1grt5rrdAKVRy920FYllQw0hCZLOu9DVdYyo+6NmWnhhR4a7kyxPoTo1YMGqHwsA==","_resolved":"/private/var/folders/w0/xbxl76mn08g6fgyk86cf76v40000gn/T/4a63d4ee868be1f10a887b965cb313f3/lighter-sdk-client-0.2.34.tgz","_from":"file:lighter-sdk-client-0.2.34.tgz","_nodeVersion":"24.4.1","_npmVersion":"11.4.2","dist":{"integrity":"sha512-HNo2ChjItDrIoxfsFHLHFh1grt5rrdAKVRy920FYllQw0hCZLOu9DVdYyo+6NmWnhhR4a7kyxPoTo1YMGqHwsA==","shasum":"07c6f3bf87644a9e04b68cc5b50ab868986c443f","tarball":"https://registry.npmjs.org/lighter-sdk-client/-/lighter-sdk-client-0.2.34.tgz","fileCount":378,"unpackedSize":527530,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQDNweQSQCDxoM8yGFrDcctrw34l6NX1V5AvhO6NPHNvRAIgDmZ0cOWKtBGYiW0mU/BCIQsKInOpGQc1aUrPh0YV0R0="}]},"_npmUser":{"name":"0xpye","email":"pye@swellnetwork.io"},"directories":{},"maintainers":[{"name":"0xpye","email":"pye@swellnetwork.io"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/lighter-sdk-client_0.2.34_1777969557944_0.2220603398706591"},"_hasShrinkwrap":false}},"time":{"created":"2026-01-22T08:56:05.243Z","modified":"2026-05-05T08:25:58.201Z","0.1.5":"2026-01-22T08:56:05.388Z","0.1.6":"2026-01-22T09:04:04.754Z","0.1.7":"2026-01-22T09:15:46.378Z","0.1.8":"2026-01-22T09:46:58.878Z","0.2.0":"2026-01-22T10:40:29.565Z","0.2.1":"2026-01-23T04:00:04.244Z","0.2.2":"2026-01-23T04:09:23.800Z","0.2.3":"2026-01-23T04:24:24.455Z","0.2.4":"2026-01-23T04:41:32.015Z","0.2.5":"2026-01-23T04:49:23.738Z","0.2.6":"2026-01-23T04:57:10.346Z","0.2.7":"2026-01-23T05:03:16.446Z","0.2.8":"2026-01-23T07:07:12.713Z","0.2.9":"2026-01-23T07:42:46.711Z","0.2.10":"2026-01-23T07:55:08.807Z","0.2.11":"2026-01-23T07:55:46.444Z","0.2.12":"2026-01-23T09:58:23.240Z","0.2.13":"2026-01-25T06:21:25.221Z","0.2.14":"2026-01-25T06:39:22.156Z","0.2.15":"2026-01-25T06:47:09.482Z","0.2.16":"2026-01-25T06:54:15.158Z","0.2.17":"2026-01-25T06:57:37.209Z","0.2.18":"2026-01-25T07:12:13.668Z","0.2.19":"2026-01-26T07:26:42.601Z","0.2.20":"2026-01-26T10:12:16.656Z","0.2.21":"2026-01-27T06:39:01.859Z","0.2.22":"2026-01-27T08:59:00.088Z","0.2.23":"2026-01-28T04:16:32.973Z","0.2.24":"2026-01-28T04:18:57.162Z","0.2.25":"2026-01-28T04:35:59.899Z","0.2.26":"2026-01-29T04:34:23.294Z","0.2.27":"2026-01-29T04:50:38.293Z","0.2.28":"2026-03-19T04:13:09.436Z","0.2.29":"2026-03-25T07:11:13.263Z","0.2.30":"2026-03-25T07:14:44.865Z","0.2.31":"2026-03-25T07:18:50.092Z","0.2.32":"2026-03-25T07:41:32.147Z","0.2.33":"2026-04-14T04:28:38.408Z","0.2.34":"2026-05-05T08:25:58.087Z"},"license":"ISC","keywords":[],"description":"Unofficial Lighter SDK Client for TypeScript/JavaScript","maintainers":[{"name":"0xpye","email":"pye@swellnetwork.io"}],"readme":"# Lighter SDK Client\n\nUnofficial TypeScript/JavaScript SDK client for the Lighter protocol - a high-performance decentralized exchange built on zkSync.\n\n[![npm version](https://img.shields.io/npm/v/lighter-sdk-client.svg)](https://www.npmjs.com/package/lighter-sdk-client)\n[![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)\n\n## Features\n\n- 🔄 **Full API Coverage** - Complete access to public, private, and exchange endpoints\n- 🔐 **WASM Signing** - Built-in transaction signing with WebAssembly support\n- 🌉 **L1 Bridge Integration** - Direct integration with L1 bridging functionality\n- 📡 **WebSocket Support** - Real-time market data and account updates\n- 🎯 **TypeScript First** - Full type safety and IntelliSense support\n- 📋 **Protocol Constants** - Comprehensive enums and constants for type-safe interactions\n- ⚡ **High Performance** - Optimized for speed with minimal dependencies\n\n## Installation\n\n```bash\npnpm add lighter-sdk-client\n```\n\n## Quick Start\n\n### Public API (InfoClient)\n\nAccess public market data without authentication:\n\n```typescript\nimport { InfoClient } from 'lighter-sdk-client';\n\nconst client = new InfoClient({\n  baseURL: 'https://mainnet.zklighter.elliot.ai'\n});\n\n// Get account information\nconst account = await client.getAccountInfo({ \n  by: 'index', \n  value: '0' \n});\n\n// Get order books\nconst orderBooks = await client.getOrderBooks();\n\n// Get asset details\nconst allAssets = await client.getAssetDetails();\nconst specificAsset = await client.getAssetDetails({ asset_index: 0 });\n\n// Get recent trades\nconst trades = await client.getRecentTrades({\n  market_id: 1,\n  limit: 50\n});\n\n// Get candlestick data\nconst candles = await client.getCandlesticks({\n  market_id: 1,\n  resolution: '1h',\n  start_timestamp: Math.floor(Date.now() / 1000) - 86400,\n  end_timestamp: Math.floor(Date.now() / 1000)\n});\n\n// Get withdrawal delay\nconst withdrawalDelay = await client.getWithdrawalDelay();\n\n// Get root status\nconst rootStatus = await client.getRootStatus();\n```\n\n### Exchange Operations (ExchangeClient)\n\nSend transactions and manage orders:\n\n```typescript\nimport { ExchangeClient } from 'lighter-sdk-client';\n\nconst client = new ExchangeClient({\n  baseURL: 'https://mainnet.zklighter.elliot.ai'\n});\n\n// Send a transaction\nconst result = await client.sendTransaction({\n  account_index: 0,\n  api_key_index: 0,\n  transaction: '0x...'\n});\n\n// Send a batch of transactions\nconst batchResult = await client.sendTransactionBatch({\n  account_index: 0,\n  api_key_index: 0,\n  transactions: ['0x...', '0x...']\n});\n\n// Change account tier\nconst tierResult = await client.changeAccountTier({\n  account_index: 0,\n  new_tier: 'premium'\n}, 'auth-token');\n\n// Fast withdraw\nconst withdrawResult = await client.fastWithdraw({\n  tx_info: '0x...',\n  to_address: '0x...'\n}, 'auth-token');\n\n// Create intent address for deposits\nconst intentAddress = await client.createIntentAddress({\n  chain_id: 101, // Solana chain ID\n  from_addr: '0x47Af141529dd73CD4Ca07416ad449b29df6F3c9e',\n  amount: '0',\n  is_external_deposit: true\n}, 'auth-token');\n\n// Create API token\nconst newToken = await client.createToken({\n  name: 'My API Token',\n  account_index: 0,\n  expiry: Math.floor(Date.now() / 1000) + 86400 * 30, // 30 days\n  sub_account_access: true,\n  scopes: 'read.*'\n}, 'auth-token');\n\n// Revoke API token\nconst revokeResult = await client.revokeToken({\n  token_id: 123,\n  account_index: 0\n}, 'auth-token');\n\n// Generate L1 sign message for changing public key\nconst signMessage = await client.generateChangePubKeyL1SignMessage(\n  '0xabcdef...', // pubKeyHex\n  1, // nonce\n  0, // accountIndex\n  0  // newApiKeyIndex\n);\nconsole.log('Sign this message:', signMessage);\n```\n\n### Private API (InfoPrivateClient)\n\nAccess authenticated account data with automatic WASM signing:\n\n```typescript\nimport { InfoPrivateClient, WasmSigner } from 'lighter-sdk-client';\n\n// Initialize WASM signer\nconst wasmSigner = new WasmSigner({\n  wasmPath: './public/wasm/lighter-signer.wasm',\n  wasmExecPath: './public/wasm/lighter-wasm-exec.js'\n});\n\n// Create private client - authentication is handled automatically\nconst client = new InfoPrivateClient({\n  baseURL: 'https://mainnet.zklighter.elliot.ai',\n  wasmSigning: wasmSigner\n});\n\n// Get active orders\nconst activeOrders = await client.getAccountActiveOrders({\n  account_index: 0,\n  market_id: 1\n});\n\n// Get inactive orders with pagination\nconst inactiveOrders = await client.getAccountInactiveOrders({\n  account_index: 0,\n  limit: 50,\n  market_id: 1\n});\n\n// Get account limits and tier info\nconst limits = await client.getAccountLimits({\n  account_index: 0\n});\n\n// Get L1 metadata\nconst l1Metadata = await client.getL1Metadata({\n  l1_address: '0x...'\n});\n\n// Get API tokens for account\nconst tokens = await client.getTokens({\n  account_index: 0\n});\n\n// Get deposit history\nconst deposits = await client.getDepositHistory({\n  account_index: 0,\n  l1_address: '0x...',\n  filter: 'pending'\n});\n\n// Get bridges for L1 address\nconst bridges = await client.getBridges({\n  l1_address: '0x47Af141529dd73CD4Ca07416ad449b29df6F3c9e'\n});\n\n// Get withdrawal history\nconst withdraws = await client.getWithdrawHistory({\n  account_index: 0,\n  l1_address: '0x...',\n  filter: 'completed'\n});\n\n// Get fast withdraw information\nconst fastWithdrawInfo = await client.getFastWithdrawInfo({\n  account_index: 0\n});\n\n// Get transfer fee information\nconst transferFeeInfo = await client.getTransferFeeInfo({\n  account_index: 0,\n  to_account_index: 1\n});\n\n// Get transfer history\nconst transfers = await client.getTransferHistory({\n  account_index: 0,\n  cursor: 'optional-cursor-for-pagination'\n});\n\n// Get liquidation history\nconst liquidations = await client.getLiquidations({\n  account_index: 0,\n  limit: 50,\n  market_id: 1\n});\n\n// Get profit and loss data\nconst pnl = await client.getPnL({\n  by: 'account_index',\n  value: '0',\n  resolution: '1d',\n  start_timestamp: Math.floor(Date.now() / 1000) - 86400 * 30,\n  end_timestamp: Math.floor(Date.now() / 1000),\n  count_back: 30\n});\n\n// Get position funding history\nconst funding = await client.getPositionFunding({\n  account_index: 0,\n  limit: 50,\n  market_id: 1,\n  side: 'long'\n});\n\n// Get public pools metadata\nconst pools = await client.getPublicPools({\n  filter: 'all',\n  limit: 10,\n  index: 0\n});\n\n// Get referral points\nconst referralPoints = await client.getReferralPoints({\n  account_index: 0\n});\n\n// Get trades for account or market\nconst trades = await client.getTrades({\n  sort_by: 'timestamp',\n  limit: 50,\n  account_index: 0,\n  market_id: 1,\n  sort_dir: 'desc'\n});\n\n// Export data\nconst exportData = await client.getExport({\n  type: 'trade',\n  account_index: 0,\n  market_id: 1\n});\nconsole.log('Download URL:', exportData.data_url);\n```\n\n### L1 Bridge Operations\n\nDeposit and withdraw assets:\n\n```typescript\nimport { L1BridgeClient } from 'lighter-sdk-client';\nimport { arbitrum } from 'viem/chains';\n\nconst bridgeClient = new L1BridgeClient({\n  chain: arbitrum,\n  l1RpcUrl: 'https://arb1.arbitrum.io/rpc',\n  privateKey: '0x...',\n  bridgeContractAddress: '0x...',\n  usdcAddress: '0x...'\n});\n\n// Deposit USDC from L1 to L2\nconst result = await bridgeClient.depositUSDC({\n  amount: '100.00',\n  lighterAccountIndex: 0\n});\n\nconsole.log('Transaction hash:', result.transactionHash);\nconsole.log('Amount deposited:', result.amountDeposited);\n```\n\n### WebSocket Client\n\nSubscribe to real-time market data and account updates with automatic reconnection:\n\n```typescript\nimport { WsClient } from 'lighter-sdk-client';\n\nconst wsClient = new WsClient({\n  url: 'wss://mainnet.zklighter.elliot.ai/stream',\n  reconnectInterval: 5000,        // Initial reconnect delay (ms)\n  maxReconnectAttempts: Infinity, // Unlimited reconnection attempts\n  onOpen: () => console.log('WebSocket connected'),\n  onClose: () => console.log('WebSocket disconnected'),\n  onError: (error) => console.error('WebSocket error:', error),\n  onMessage: (data) => console.log('Raw message:', data)\n});\n\n// Connect to WebSocket server\nawait wsClient.connect();\n\n// Subscribe to order book updates\nwsClient.subscribeOrderBook(1, (update) => {\n  console.log('Order book:', update.order_book);\n  console.log('Bids:', update.order_book.bids);\n  console.log('Asks:', update.order_book.asks);\n});\n\n// Subscribe to market statistics\nwsClient.subscribeMarketStats('all', (update) => {\n  console.log('Market stats:', update.market_stats);\n});\n\n// Subscribe to trade updates for a specific market\nwsClient.subscribeTrades(1, (update) => {\n  update.trades.forEach(trade => {\n    console.log('Trade:', {\n      price: trade.price,\n      size: trade.size,\n      side: trade.is_maker_ask ? 'sell' : 'buy'\n    });\n  });\n});\n\n// Subscribe to block height updates\nwsClient.subscribeHeight((update) => {\n  console.log('Current block height:', update.height);\n});\n\n// Subscribe to account updates (requires authentication)\nconst authToken = 'your-auth-token';\n\n// Subscribe to all account data\nwsClient.subscribeAccountAll(0, (update) => {\n  console.log('Positions:', update.positions);\n  console.log('Orders:', update.trades);\n  console.log('Pool shares:', update.shares);\n});\n\n// Subscribe to specific market for an account\nwsClient.subscribeAccountMarket(1, 0, authToken, (update) => {\n  console.log('Account orders:', update.orders);\n  console.log('Account position:', update.position);\n  console.log('Account trades:', update.trades);\n});\n\n// Subscribe to user statistics\nwsClient.subscribeUserStats(0, (update) => {\n  console.log('Portfolio value:', update.stats.portfolio_value);\n  console.log('Available balance:', update.stats.available_balance);\n  console.log('Leverage:', update.stats.leverage);\n});\n\n// Subscribe to notifications\nwsClient.subscribeNotifications(0, authToken, (update) => {\n  update.notifs.forEach(notif => {\n    console.log('Notification:', notif.kind, notif.content);\n  });\n});\n\n// Unsubscribe from specific channels\nwsClient.unsubscribeOrderBook(1);\nwsClient.unsubscribeMarketStats('all');\n\n// Check connection status\nconst isConnected = wsClient.isConnectedToWebSocket();\nconsole.log('Connected:', isConnected);\n\n// Get all active subscriptions\nconst subscriptions = wsClient.getSubscriptions();\nconsole.log('Active subscriptions:', subscriptions);\n\n// Disconnect when done (stops automatic reconnection)\nwsClient.disconnect();\n```\n\n**Features:**\n- ✅ **Automatic Reconnection** - Uses `reconnecting-websocket` library for reliable connections\n- ✅ **Exponential Backoff** - Gradually increases reconnection delay (up to 30 seconds)\n- ✅ **Auto-Resubscription** - Automatically resubscribes to all channels after reconnection\n- ✅ **Type-Safe** - Full TypeScript support with typed update handlers\n- ✅ **Connection Management** - Built-in connection state tracking and lifecycle hooks\n\n### Bridge Operations\n\nThe SDK provides comprehensive support for cross-chain bridge operations, including creating intent addresses for deposits and tracking bridge status.\n\n#### Creating Intent Addresses (ExchangeClient)\n\nCreate an intent address for depositing funds from external chains (e.g., Solana):\n\n```typescript\nimport { ExchangeClient } from 'lighter-sdk-client';\n\nconst exchangeClient = new ExchangeClient({\n  baseURL: 'https://mainnet.zklighter.elliot.ai',\n  wasmSigner: wasmSigner\n});\n\n// Create intent address for Solana deposit\nconst intentResult = await exchangeClient.createIntentAddress({\n  chain_id: 101, // Solana chain ID\n  from_addr: '0x47Af141529dd73CD4Ca07416ad449b29df6F3c9e',\n  amount: '0',\n  is_external_deposit: true\n}, authToken);\n\nconsole.log('Intent address:', intentResult.data?.intent_address);\n```\n\n#### Tracking Bridge Status (InfoPrivateClient)\n\nMonitor the status of bridge transactions:\n\n```typescript\nimport { InfoPrivateClient } from 'lighter-sdk-client';\n\nconst privateClient = new InfoPrivateClient({\n  baseURL: 'https://mainnet.zklighter.elliot.ai',\n  wasmSigner: wasmSigner\n});\n\n// Get all bridges for an L1 address\nconst bridges = await privateClient.getBridges({\n  l1_address: '0x47Af141529dd73CD4Ca07416ad449b29df6F3c9e'\n});\n\n// Process bridge information\nbridges.bridges?.forEach(bridge => {\n  console.log(`Bridge ID: ${bridge.id}`);\n  console.log(`Source: ${bridge.source} (Chain ${bridge.source_chain_id})`);\n  console.log(`Intent Address: ${bridge.intent_address}`);\n  console.log(`Amount: ${bridge.amount}`);\n  console.log(`Status: ${bridge.status} - ${bridge.description}`);\n  console.log(`Step: ${bridge.step}`);\n  console.log(`External Deposit: ${bridge.is_external_deposit}`);\n  console.log('---');\n});\n```\n\n**Bridge Status Flow:**\n1. `pending` - Waiting for user to deposit to the intent address\n2. Transaction processing on source chain\n3. Cross-chain verification\n4. Funds credited to L2 account\n\n## API Reference\n\n### InfoClient\n\nPublic API client for market data and account information. No authentication required.\n\n#### Methods\n\n**Account Methods**\n- `getAccountInfo(params)` - Get account information by index or L2 address\n- `getAccountByL1Address(params)` - Get account information associated with an L1 address\n\n**API Keys & Announcements**\n- `getApiKeys(params)` - Get API keys for an account\n- `getAnnouncements()` - Get system announcements\n\n**Market Data**\n- `getAssetDetails(params?)` - Get asset details for a specific asset or all assets (symbol, decimals, limits, pricing)\n- `getCandlesticks(params)` - Get candlestick data with specified resolution and time range\n- `getFundings(params)` - Get funding history for a market\n- `getExchangeStats()` - Get exchange-wide statistics including volume and fees\n- `getFundingRates()` - Get current funding rates for all markets\n\n**Order Books**\n- `getOrderBooks()` - Get list of all order books with configurations\n- `getOrderBookDetails(params)` - Get detailed information about a specific order book\n- `getOrderBookOrders(params)` - Get bids and asks in an order book\n\n**Trades**\n- `getRecentTrades(params)` - Get recent trades for a market\n- `getTrades(params, authorization?)` - Get trades with optional filtering and authentication\n\n**Transactions**\n- `getTransaction(params)` - Get a specific transaction by hash\n- `getTransactions(params?)` - Get transactions with optional filtering\n- `getTransactionFromL1TxHash(params)` - Get L2 transaction from L1 transaction hash\n\n**Utilities**\n- `getNextNonce(params)` - Get the next nonce for an account\n- `getFastBridgeInfo()` - Get fast bridge configuration and status\n- `getWithdrawalDelay()` - Get withdrawal delay in seconds\n- `getRootStatus()` - Get root status information including network status and timestamp\n\n### ExchangeClient\n\nClient for sending transactions and managing exchange operations.\n\n#### Methods\n\n**Transaction Submission**\n- `sendTransaction(params)` - Send a signed transaction to the exchange\n- `sendTx(params)` - Send transaction with form data format\n- `sendTxWithIndices(params)` - Send transaction with account and API key indices\n- `sendTxJson(params)` - Send transaction with JSON payload format\n- `sendTransactionBatch(params)` - Send multiple transactions in a single batch for better efficiency\n\n**Account Management**\n- `changeAccountTier(params, authorization?)` - Change account tier (requires authorization)\n- `fastWithdraw(params, authorization?)` - Fast withdraw funds (requires authorization)\n- `createIntentAddress(params, authorization?)` - Create intent address for deposits (requires authorization)\n\n**API Tokens**\n- `createToken(params, authorization?)` - Create API token with specified permissions and expiry\n- `revokeToken(params, authorization?)` - Revoke an existing API token\n- `generateChangePubKeyL1SignMessage(pubKeyHex, nonce, accountIndex, newApiKeyIndex)` - Generate L1 sign message for changing public key\n\n**Notifications**\n- `acknowledgeNotification(params)` - Acknowledge receipt of a notification\n\n### InfoPrivateClient\n\nClient for authenticated/private endpoints. Authentication is handled automatically via WasmSigner.\n\n#### Methods\n\n**Account Orders**\n- `getAccountActiveOrders(params)` - Get active orders for an account in a specific market\n- `getAccountInactiveOrders(params)` - Get inactive orders with pagination support\n\n**Account Information**\n- `getAccountLimits(params)` - Get account limits including max LLP percentage, user tier, and pool creation permissions\n- `getAccountMetadata(params)` - Get account metadata by index or L1 address\n- `getL1Metadata(params)` - Get L1 metadata for an address including referral information\n- `getTokens(params)` - Get API tokens for an account with details including name, expiry, scopes, and status\n\n**Transaction History**\n- `getDepositHistory(params)` - Get deposit history with status and timestamps\n- `getBridges(params)` - Get bridges for an L1 address\n- `getWithdrawHistory(params)` - Get withdrawal history with status and timestamps\n- `getFastWithdrawInfo(params)` - Get fast withdraw limits and account information\n- `getTransferFeeInfo(params)` - Get transfer fee information between accounts\n- `getTransferHistory(params)` - Get transfer history with pagination support\n- `getLiquidations(params)` - Get liquidation history with pagination support\n\n**Analytics**\n- `getPnL(params)` - Get profit and loss data with customizable resolution and time range\n- `getPositionFunding(params)` - Get position funding history with pagination support\n\n**Liquidity Pools**\n- `getPublicPools(params?)` - Get public pool information including TVL, APY, and share details\n\n**Referral System**\n- `getReferralPoints(params)` - Get referral points data including user points and referral list\n\n**Trading**\n- `getTrades(params)` - Get trades for an account or market with sorting and filtering options\n\n**Data Export**\n- `getExport(params)` - Export data (funding or trade data) for downloading\n\n### L1BridgeClient\n\nClient for L1 bridge operations to move assets between Layer 1 and Layer 2.\n\n#### Methods\n\n**Bridge Operations**\n- `depositUSDC(params)` - Deposit USDC from L1 to L2 Lighter account\n\n**Balance & Allowance**\n- `checkUSDCBalance()` - Check USDC balance on L1\n- `checkAllowance()` - Check current USDC allowance for bridge contract\n- `approveUSDC(amount)` - Approve USDC spending for bridge contract\n\n### WsClient\n\nWebSocket client for real-time market data and account updates with automatic reconnection and resubscription.\n\n#### Configuration Options\n\n```typescript\ninterface WebSocketConfig {\n  url?: string;                    // WebSocket server URL (default: wss://mainnet.zklighter.elliot.ai/stream)\n  reconnectInterval?: number;      // Initial reconnect delay in ms (default: 5000)\n  maxReconnectAttempts?: number;   // Max reconnection attempts (default: Infinity)\n  onMessage?: (data: any) => void; // Raw message handler\n  onError?: (error: Error) => void; // Error handler\n  onClose?: () => void;            // Close event handler\n  onOpen?: () => void;             // Open event handler\n}\n```\n\n#### Methods\n\n**Connection Management**\n- `connect()` - Establish WebSocket connection with automatic reconnection support\n- `disconnect()` - Close WebSocket connection and stop automatic reconnection\n- `isConnectedToWebSocket()` - Check if currently connected to WebSocket server\n- `getSubscriptions()` - Get list of all active subscriptions\n\n**Market Data Subscriptions**\n- `subscribeOrderBook(marketIndex, handler)` - Subscribe to order book updates (bids/asks)\n- `unsubscribeOrderBook(marketIndex)` - Unsubscribe from order book updates\n- `subscribeTrades(marketIndex, handler)` - Subscribe to trade updates for a market\n- `unsubscribeTrades(marketIndex)` - Unsubscribe from trade updates\n- `subscribeMarketStats(market, handler)` - Subscribe to market statistics (market can be number or 'all')\n- `unsubscribeMarketStats(market)` - Unsubscribe from market statistics\n- `subscribeSpotMarketStats(market, handler)` - Subscribe to spot market statistics\n- `unsubscribeSpotMarketStats(market)` - Unsubscribe from spot market statistics\n\n**Account Subscriptions** (requires authentication)\n- `subscribeAccountAll(accountId, handler)` - Subscribe to all account data (positions, trades, shares)\n- `unsubscribeAccountAll(accountId)` - Unsubscribe from all account data\n- `subscribeAccountMarket(marketId, accountId, auth, handler)` - Subscribe to account updates for specific market\n- `unsubscribeAccountMarket(marketId, accountId)` - Unsubscribe from account market updates\n- `subscribeAccountOrders(marketIndex, accountId, auth, handler)` - Subscribe to order updates for specific market\n- `unsubscribeAccountOrders(marketIndex, accountId)` - Unsubscribe from order updates\n- `subscribeAccountAllOrders(accountId, auth, handler)` - Subscribe to all order updates across markets\n- `unsubscribeAccountAllOrders(accountId)` - Unsubscribe from all order updates\n- `subscribeAccountAllPositions(accountId, auth, handler)` - Subscribe to all position updates\n- `unsubscribeAccountAllPositions(accountId)` - Unsubscribe from position updates\n- `subscribeAccountAllTrades(accountId, auth, handler)` - Subscribe to all trade updates\n- `unsubscribeAccountAllTrades(accountId)` - Unsubscribe from trade updates\n- `subscribeUserStats(accountId, handler)` - Subscribe to user statistics (portfolio, balance, leverage)\n- `unsubscribeUserStats(accountId)` - Unsubscribe from user statistics\n\n**Pool Subscriptions** (requires authentication)\n- `subscribePoolData(accountId, auth, handler)` - Subscribe to pool data updates\n- `unsubscribePoolData(accountId)` - Unsubscribe from pool data\n- `subscribePoolInfo(accountId, auth, handler)` - Subscribe to pool information updates\n- `unsubscribePoolInfo(accountId)` - Unsubscribe from pool information\n\n**System Subscriptions**\n- `subscribeNotifications(accountId, auth, handler)` - Subscribe to system notifications\n- `unsubscribeNotifications(accountId)` - Unsubscribe from notifications\n- `subscribeTransactions(handler)` - Subscribe to all transaction updates\n- `unsubscribeTransactions()` - Unsubscribe from transaction updates\n- `subscribeExecutedTransactions(handler)` - Subscribe to executed transaction updates\n- `unsubscribeExecutedTransactions()` - Unsubscribe from executed transactions\n- `subscribeAccountTransactions(accountId, auth, handler)` - Subscribe to account-specific transactions\n- `unsubscribeAccountTransactions(accountId)` - Unsubscribe from account transactions\n- `subscribeHeight(handler)` - Subscribe to block height updates\n- `unsubscribeHeight()` - Unsubscribe from height updates\n\n**Advanced**\n- `subscribe<TPayload>(subscription)` - Generic subscribe method with custom subscription options\n- `unsubscribe(channel)` - Generic unsubscribe method for any channel\n- `send(message)` - Send raw message through WebSocket connection\n\n## Constants and Enums\n\nThe SDK provides comprehensive constants and enums for type-safe interaction with the Lighter protocol:\n\n### Transaction Types\n\n```typescript\nimport { TxType } from 'lighter-sdk-client';\n\n// L1 Transaction Types\nTxType.L1Deposit\nTxType.L1ChangePubKey\nTxType.L1CreateMarket\nTxType.L1UpdateMarket\nTxType.L1CancelAllOrders\nTxType.L1Withdraw\nTxType.L1CreateOrder\nTxType.L1BurnShares\n\n// L2 Transaction Types\nTxType.L2ChangePubKey\nTxType.L2CreateSubAccount\nTxType.L2CreatePublicPool\nTxType.L2UpdatePublicPool\nTxType.L2Transfer\nTxType.L2Withdraw\nTxType.L2CreateOrder\nTxType.L2CancelOrder\nTxType.L2CancelAllOrders\nTxType.L2ModifyOrder\nTxType.L2MintShares\nTxType.L2BurnShares\nTxType.L2UpdateLeverage\nTxType.L2CreateGroupedOrders\nTxType.L2UpdateMargin\n\n// Internal Transaction Types\nTxType.InternalClaimOrder\nTxType.InternalCancelOrder\nTxType.InternalDeleverage\nTxType.InternalExitPosition\nTxType.InternalCancelAllOrders\nTxType.InternalLiquidatePosition\nTxType.InternalCreateOrder\n```\n\n### Order Types\n\n```typescript\nimport { OrderType } from 'lighter-sdk-client';\n\nOrderType.Limit           // Standard limit order\nOrderType.Market          // Market order\nOrderType.StopLoss        // Stop loss order\nOrderType.StopLossLimit   // Stop loss limit order\nOrderType.TakeProfit      // Take profit order\nOrderType.TakeProfitLimit // Take profit limit order\nOrderType.TWAP            // Time-weighted average price order\nOrderType.TWAPSub         // TWAP sub-order (internal)\nOrderType.Liquidation     // Liquidation order (internal)\n```\n\n### Order Time-In-Force\n\n```typescript\nimport { OrderTimeInForce } from 'lighter-sdk-client';\n\nOrderTimeInForce.ImmediateOrCancel // Execute immediately or cancel\nOrderTimeInForce.GoodTillTime      // Active until specified time\nOrderTimeInForce.PostOnly          // Only add to order book (maker only)\n```\n\n### Grouping Types\n\n```typescript\nimport { GroupingType } from 'lighter-sdk-client';\n\nGroupingType.Default                        // No grouping\nGroupingType.OneTriggersTheOther           // OCO: One triggers the other\nGroupingType.OneCancelsTheOther            // OCO: One cancels the other\nGroupingType.OneTriggersAOneCancelsTheOther // OTOCO: Combined behavior\n```\n\n### Margin Modes\n\n```typescript\nimport { \n  PositionMarginMode, \n  AssetMarginMode,\n  MarginUpdateDirection \n} from 'lighter-sdk-client';\n\n// Position Margin Mode\nPositionMarginMode.Cross    // Cross margin\nPositionMarginMode.Isolated // Isolated margin\n\n// Asset Margin Mode\nAssetMarginMode.Disabled\nAssetMarginMode.Enabled\n\n// Margin Update Direction\nMarginUpdateDirection.RemoveFromIsolated\nMarginUpdateDirection.AddToIsolated\n```\n\n### Asset Route Types\n\n```typescript\nimport { AssetRouteType } from 'lighter-sdk-client';\n\nAssetRouteType.Perps // Perpetual futures\nAssetRouteType.Spot  // Spot trading\n```\n\n### Numeric Constants\n\nThe SDK includes various numeric constants for limits and validations:\n\n```typescript\nimport { \n  OneUSDC,\n  MinOrderPrice,\n  MaxOrderPrice,\n  MinOrderBaseAmount,\n  MaxOrderBaseAmount,\n  MinAccountIndex,\n  MaxAccountIndex,\n  NativeAssetIndex,\n  USDCAssetIndex,\n  // ... and many more\n} from 'lighter-sdk-client';\n\n// Example usage\nconst minAmount = MinOrderBaseAmount; // 1\nconst maxAmount = MaxOrderBaseAmount; // 281474976710655\nconst usdcDecimals = OneUSDC;         // 1000000\n```\n\nAvailable numeric constants include:\n- **Account Indices**: `MinAccountIndex`, `MaxAccountIndex`, `MaxMasterAccountIndex`, `MinSubAccountIndex`\n- **Market Indices**: `MinMarketIndex`, `MaxPerpsMarketIndex`, `MinSpotMarketIndex`, `MaxSpotMarketIndex`\n- **Asset Indices**: `NativeAssetIndex`, `USDCAssetIndex`, `MinAssetIndex`, `MaxAssetIndex`\n- **Order Limits**: `MinOrderPrice`, `MaxOrderPrice`, `MinOrderBaseAmount`, `MaxOrderBaseAmount`\n- **Order Timing**: `MinOrderExpiryPeriod`, `MaxOrderExpiryPeriod`, `MinOrderCancelAllPeriod`, `MaxOrderCancelAllPeriod`\n- **Pool Limits**: `MaxInvestedPublicPoolCount`, `MinInitialTotalShares`, `MaxInitialTotalShares`\n- **Exchange Limits**: `MaxExchangeUSDC`, `MinTransferAmount`, `MaxTransferAmount`, `MinWithdrawalAmount`, `MaxWithdrawalAmount`\n\n## Configuration\n\n### Base URLs\n\n- **Mainnet**: `https://mainnet.zklighter.elliot.ai`\n- **WebSocket**: `wss://mainnet.zklighter.elliot.ai/stream`\n\n### WASM Signing Setup\n\nFor transaction signing, you need to include the WASM files (please copy them from the `lighter-sdk-client` package to your `./public` directory):\n\n```typescript\nimport { WasmSigner } from 'lighter-sdk-client';\n\nconst wasmSigning = new WasmSigner({\n  wasmPath: './public/wasm/lighter-signer.wasm',\n  wasmExecPath: './public/wasm/lighter-wasm-exec.js'\n});\n```\n\nThe WASM files should be placed in your public directory and served statically.\n\n## Dependencies\n\n- `axios` - HTTP client for API requests\n- `viem` - Ethereum library for L1 bridge operations\n- `wagmi` - React hooks for Ethereum (peer dependency)\n- `@tanstack/react-query` - Data fetching library (peer dependency)\n\n## Development\n\n### Build\n\n```bash\npnpm build\n```\n\n### Project Structure\n\n```\nsrc/\n├── api/              # API endpoint implementations\n│   ├── exchange/     # Exchange/transaction endpoints\n│   ├── info/         # Public info endpoints\n│   └── info-private/ # Private/authenticated endpoints\n├── client/           # Client classes\n│   ├── exchange-client.ts\n│   ├── info-client.ts\n│   ├── info-private-client.ts\n│   ├── l1-bridge-client.ts\n│   └── ws-client.ts\n├── signing/          # Transaction signing utilities\n│   └── wasm-signer.ts\n└── types/            # TypeScript type definitions\n    ├── bridge.ts\n    ├── constant.ts   # Protocol constants and enums\n    ├── ws.ts\n    └── index.ts\n```\n\n## License\n\nISC\n\n## Disclaimer\n\nThis is an unofficial SDK client for the Lighter protocol. Use at your own risk. Always verify transactions before signing.\n\n## Links\n\n- [Lighter Protocol](https://lighter.xyz)\n- [Documentation](https://docs.lighter.xyz)\n\n## Support\n\nFor issues and questions:\n- Create an issue on GitHub\n- Join the Lighter community Discord\n- Check the official documentation\n","readmeFilename":"README.md"}