{"_id":"@arbify.fun/okx-dex-sdk","name":"@arbify.fun/okx-dex-sdk","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@arbify.fun/okx-dex-sdk","version":"1.0.0","main":"dist/index.js","types":"dist/index.d.ts","keywords":["okx","dex","sdk"],"author":{"name":"Julian Martinez"},"license":"MIT","description":"OKX DEX SDK","dependencies":{"@mysten/sui":"^1.20.0","@okxweb3/coin-ethereum":"^1.1.1","@okxweb3/coin-sui":"^1.1.1","@solana/web3.js":"^1.98.2","@types/bn.js":"^5.1.6","@types/bs58":"^5.0.0","axios":"^1.6.7","bn.js":"^5.2.2","bs58":"^6.0.0","crypto-js":"^4.2.0","dotenv":"^16.5.0","ethers":"^6.14.3","tweetnacl":"^1.0.3","typescript":"^5.8.3","valibot":"^1.1.0","web3":"^4.16.0"},"devDependencies":{"@types/crypto-js":"^4.2.2","@types/jest":"^29.5.14","@types/node":"^22.13.4","jest":"^29.7.0","ts-jest":"^29.2.5"},"repository":{"type":"git","url":"git+https://github.com/okx/okx-dex-sdk.git"},"publishConfig":{"registry":"https://registry.npmjs.org/"},"scripts":{"build":"tsc","test":"jest","test:coverage":"jest --coverage","clean":"rm -rf dist","example:evm-quote":"npx ts-node src/okx/examples/evm/evm-quote.ts","example:evm-swap":"npx ts-node src/okx/examples/evm/evm-swap.ts","example:evm-approve":"npx ts-node src/okx/examples/evm/evm-approve.ts","example:evm-broadcast":"npx ts-node src/okx/examples/evm/evm-broadcast-swap.ts","example:evm-gas-limit":"npx ts-node src/okx/examples/evm/evm-gas-limit.ts","example:evm-tx-sim":"npx ts-node src/okx/examples/evm/evm-tx-sim.ts","example:evm-order-tracking":"npx ts-node src/okx/examples/evm/evm-order-tracking.ts","example:solana-quote":"npx ts-node src/okx/examples/solana/solana-quote.ts","example:solana-swap":"npx ts-node src/okx/examples/solana/solana-swap.ts","example:solana-gas-limit":"npx ts-node src/okx/examples/solana/solana-gas-limit.ts","example:solana-swap-sim":"npx ts-node src/okx/examples/solana/solana-swap-sim.ts","example:sui-quote":"npx ts-node src/okx/examples/sui/sui-quote.ts","example:sui-swap":"npx ts-node src/okx/examples/sui/sui-swap.ts","example:sui-broadcast":"npx ts-node src/okx/examples/sui/sui-broadcast-swap.ts","example:ton-quote":"npx ts-node src/okx/examples/ton/ton-quote.ts","example:ton-swap":"npx ts-node src/okx/examples/ton/ton-swap.ts","example:tron-quote":"npx ts-node src/okx/examples/tron/tron-quote.ts","example:tron-swap":"npx ts-node src/okx/examples/tron/tron-swap.ts"},"bugs":{"url":"https://github.com/okx/okx-dex-sdk/issues"},"homepage":"https://github.com/okx/okx-dex-sdk#readme","_id":"@arbify.fun/okx-dex-sdk@1.0.0","_integrity":"sha512-MUW3j6TW3V4OC+khHzNK2tzGPL6wEpr+ES/dJcyB7kp2MuKM743HuDh8wAc2wSrIzSp14WmEOoJkCYSk3JduCQ==","_resolved":"/private/var/folders/41/f7sc0yh933bb8stpbk874lw40000gn/T/f2dfe96f9e82d9ff8edd582b3008f505/arbify.fun-okx-dex-sdk-1.0.0.tgz","_from":"file:arbify.fun-okx-dex-sdk-1.0.0.tgz","_nodeVersion":"18.19.0","_npmVersion":"10.2.3","dist":{"integrity":"sha512-MUW3j6TW3V4OC+khHzNK2tzGPL6wEpr+ES/dJcyB7kp2MuKM743HuDh8wAc2wSrIzSp14WmEOoJkCYSk3JduCQ==","shasum":"8094c79e0f361e3e9eeecb219784ba345da00b6d","tarball":"https://registry.npmjs.org/@arbify.fun/okx-dex-sdk/-/okx-dex-sdk-1.0.0.tgz","fileCount":115,"unpackedSize":182151,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQCbjZIAMieEYDtCpIniwDveE6s2UL6wh2GjuoT1nyzEJwIhAOt90NLbolgVC2vmaU62W4lVFBIsCYWc0YNCBz2JExVS"}]},"_npmUser":{"name":"arbify.fun","email":"geekarvin@gmail.com"},"directories":{},"maintainers":[{"name":"arbify.fun","email":"geekarvin@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/okx-dex-sdk_1.0.0_1754035597571_0.47035060245416926"},"_hasShrinkwrap":false}},"time":{"created":"2025-08-01T08:06:37.414Z","1.0.0":"2025-08-01T08:06:37.755Z","modified":"2025-08-01T08:06:38.067Z"},"maintainers":[{"name":"arbify.fun","email":"geekarvin@gmail.com"}],"description":"OKX DEX SDK","homepage":"https://github.com/okx/okx-dex-sdk#readme","keywords":["okx","dex","sdk"],"repository":{"type":"git","url":"git+https://github.com/okx/okx-dex-sdk.git"},"author":{"name":"Julian Martinez"},"bugs":{"url":"https://github.com/okx/okx-dex-sdk/issues"},"license":"MIT","readme":"# OKX DEX SDK\n\n[![npm version](https://img.shields.io/npm/v/@okx-dex/okx-dex-sdk.svg)](https://www.npmjs.com/package/@okx-dex/okx-dex-sdk)\n\nA comprehensive TypeScript SDK for interacting with OKX DEX across multiple blockchain networks including EVM-compatible chains, Solana, Sui, TON, and TRON.\n\n## Features\n\n### Core Trading Functionality\n- **Multi-chain token swaps** - Execute swaps across 6+ blockchain networks\n- **Real-time quotes** - Get accurate pricing and route information\n- **Token approvals** - Automated ERC-20 token approval handling\n- **Liquidity data** - Access DEX liquidity sources and routing information\n\n### Advanced Features\n- **Transaction broadcasting** - Direct transaction submission through OKX infrastructure with MEV protection\n- **Gas estimation** - Accurate gas limit calculation using onchain data\n- **Transaction simulation** - Pre-execution validation and risk assessment\n- **Order tracking** - Real-time transaction status monitoring\n- **Slippage protection** - Configurable slippage tolerance\n\n### Developer Experience\n- **Full TypeScript support** - Complete type safety and IntelliSense\n- **Built-in retry logic** - Automatic retries with exponential backoff\n- **Comprehensive error handling** - Detailed error messages and status codes\n- **Extensive examples** - Ready-to-use code samples for all chains\n\n## Installation\n\n```bash\nnpm install @okx-dex/okx-dex-sdk\n# or\nyarn add @okx-dex/okx-dex-sdk\n# or\npnpm add @okx-dex/okx-dex-sdk\n```\n\n## Supported Networks\n\n| Network | Chain ID | Status | Features |\n|---------|----------|--------|----------|\n| **Major EVM Chains** | | | |\n| Ethereum | `1` | ✅ | Swap, Quote, Approve, Broadcast |\n| Base | `8453` | ✅ | Swap, Quote, Approve, Broadcast |\n| Polygon | `137` | ✅ | Swap, Quote, Approve, Broadcast |\n| Avalanche | `43114` | ✅ | Swap, Quote, Approve, Broadcast |\n| BSC | `56` | ✅ | Swap, Quote, Approve, Broadcast |\n| Arbitrum | `42161` | ✅ | Swap, Quote, Approve, Broadcast |\n| Optimism | `10` | ✅ | Swap, Quote, Approve, Broadcast |\n| **Layer 2 & Scaling** | | | |\n| Polygon zkEVM | `1101` | ✅ | Swap, Quote, Approve, Broadcast |\n| zkSync Era | `324` | ✅ | Swap, Quote, Approve, Broadcast |\n| Linea | `59144` | ✅ | Swap, Quote, Approve, Broadcast |\n| Scroll | `534352` | ✅ | Swap, Quote, Approve, Broadcast |\n| Mantle | `5000` | ✅ | Swap, Quote, Approve, Broadcast |\n| Blast | `81457` | ✅ | Swap, Quote, Approve, Broadcast |\n| **Other EVM Chains** | | | |\n| Fantom | `250` | ✅ | Swap, Quote, Approve, Broadcast |\n| Gnosis | `100` | ✅ | Swap, Quote, Approve, Broadcast |\n| X Layer | `196` | ✅ | Swap, Quote, Approve, Broadcast |\n| Manta Pacific | `169` | ✅ | Swap, Quote, Approve, Broadcast |\n| Metis | `1088` | ✅ | Swap, Quote, Approve, Broadcast |\n| Cronos | `25` | ✅ | Swap, Quote, Approve, Broadcast |\n| Conflux | `1030` | ✅ | Swap, Quote, Approve, Broadcast |\n| Zeta Chain | `7000` | ✅ | Swap, Quote, Approve, Broadcast |\n| OKT Chain | `66` | ✅ | Swap, Quote, Approve, Broadcast |\n| **Non-EVM Chains** | | | |\n| Solana | `501` | ✅ | Swap, Quote, Broadcast |\n| Sui | `784` | ✅ | Swap, Quote, Broadcast |\n| TON | `607` | ✅ | Swap, Quote |\n| TRON | `195` | ✅ | Swap, Quote |\n\n## Configuration\n\nSet up your environment variables in a `.env` file:\n\n```bash\n# OKX API Credentials (Required)\nOKX_API_KEY=your_api_key\nOKX_SECRET_KEY=your_secret_key\nOKX_API_PASSPHRASE=your_passphrase\nOKX_PROJECT_ID=your_project_id\n\n# EVM Configuration (for Ethereum, Base, Polygon, etc.)\nEVM_RPC_URL=https://mainnet.base.org\nEVM_WALLET_ADDRESS=0x...\nEVM_PRIVATE_KEY=0x...\n\n# Solana Configuration\nSOLANA_RPC_URL=https://api.mainnet-beta.solana.com\nSOLANA_WALLET_ADDRESS=...\nSOLANA_PRIVATE_KEY=...\n\n# Sui Configuration\nSUI_RPC_URL=https://sui-mainnet.blockvision.org\nSUI_WALLET_ADDRESS=0x...\nSUI_PRIVATE_KEY=...\n```\n\n## Quick Start\n\n### Initialize the Client\n\n```typescript\nimport { OKXDexClient } from '@okx-dex/okx-dex-sdk';\nimport { createWallet } from '@okx-dex/okx-dex-sdk/core/solana-wallet';\nimport { createEVMWallet } from '@okx-dex/okx-dex-sdk/core/evm-wallet';\nimport { ethers } from 'ethers';\nimport 'dotenv/config';\n\n// Create wallet instances\nconst provider = new ethers.JsonRpcProvider(process.env.EVM_RPC_URL!);\nconst evmWallet = createEVMWallet(process.env.EVM_PRIVATE_KEY!, provider);\n\n// For Solana - create wallet instance (implementation may vary)\nconst connection = new Connection(process.env.SOLANA_RPC_URL!);\nconst solanaWallet = createWallet(process.env.SOLANA_PRIVATE_KEY!, connection);\n\n\n// Multi-chain client initialization\nconst client = new OKXDexClient({\n    apiKey: process.env.OKX_API_KEY!,\n    secretKey: process.env.OKX_SECRET_KEY!,\n    apiPassphrase: process.env.OKX_API_PASSPHRASE!,\n    projectId: process.env.OKX_PROJECT_ID!,\n    \n    // EVM configuration (Ethereum, Base, Polygon, etc.)\n    evm: {\n        wallet: evmWallet\n    },\n    \n    // Solana configuration\n    solana: {\n        wallet: solanaWallet\n    }\n    sui: {\n        privateKey: process.env.SUI_PRIVATE_KEY!,\n        walletAddress: process.env.SUI_WALLET_ADDRESS!,\n        connection: {\n            rpcUrl: suiRpcUrl\n        }\n        \n});\n```\n\n### Basic Usage Examples\n\n<details>\n<summary><b>EVM Chains (Ethereum, Base, Polygon, etc.)</b></summary>\n\n#### Token Addresses (Base Chain)\n```typescript\nconst BASE_TOKENS = {\n    ETH: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // Native ETH\n    USDC: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n    WETH: '0x4200000000000000000000000000000000000006'\n};\n```\n\n#### Get Quote\n```typescript\nconst quote = await client.dex.getQuote({\n    chainId: '8453',  // Base Chain\n    fromTokenAddress: BASE_TOKENS.ETH,\n    toTokenAddress: BASE_TOKENS.USDC,\n    amount: '1000000000000000000',  // 1 ETH in wei\n    slippage: '0.005'     // 0.5%\n});\n\nconsole.log(`Quote: ${quote.data[0].fromToken.tokenSymbol} → ${quote.data[0].toToken.tokenSymbol}`);\nconsole.log(`Rate: ${quote.data[0].toTokenAmount} USDC for 1 ETH`);\nconsole.log(`Price Impact: ${quote.data[0].priceImpactPercentage}%`);\n```\n\n#### Token Approval (ERC-20 tokens only)\n```typescript\n// Not needed for native ETH, only for ERC-20 tokens\nconst approval = await client.dex.executeApproval({\n    chainId: '8453',\n    tokenContractAddress: BASE_TOKENS.USDC,\n    approveAmount: '1000000' // 1 USDC (6 decimals)\n});\nconsole.log(`Approval tx: ${approval.transactionHash}`);\n```\n\n#### Execute Swap\n```typescript\nconst swap = await client.dex.executeSwap({\n    chainId: '8453',        // Base Chain\n    fromTokenAddress: BASE_TOKENS.ETH,\n    toTokenAddress: BASE_TOKENS.USDC,\n    amount: '100000000000000000', // 0.1 ETH in wei\n    slippage: '0.005',        // 0.5%\n    userWalletAddress: evmWallet.address\n});\n\nconsole.log(`Swap completed: ${swap.transactionId}`);\nconsole.log(`Explorer: ${swap.explorerUrl}`);\n```\n</details>\n\n<details>\n<summary><b>Solana</b></summary>\n\n#### Token Addresses\n```typescript\nconst SOLANA_TOKENS = {\n    SOL: 'So11111111111111111111111111111111111111112', // Native SOL\n    USDC: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n    USDT: 'Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB'\n};\n```\n\n#### Get Quote\n```typescript\nconst quote = await client.dex.getQuote({\n    chainId: '501',         // Solana mainnet\n    fromTokenAddress: SOLANA_TOKENS.SOL,\n    toTokenAddress: SOLANA_TOKENS.USDC,\n    amount: '1000000000',   // 1 SOL (9 decimals)\n    slippage: '0.005'         // 0.5%\n});\n\nconsole.log(`Quote: 1 SOL → ${quote.data[0].toTokenAmount} USDC`);\nconsole.log(`Price Impact: ${quote.data[0].priceImpactPercentage}%`);\n```\n\n#### Execute Swap\n```typescript\nconst swap = await client.dex.executeSwap({\n    chainId: '501',\n    fromTokenAddress: SOLANA_TOKENS.SOL,\n    toTokenAddress: SOLANA_TOKENS.USDC,\n    amount: '500000000',    // 0.5 SOL\n    slippage: '0.005',\n    userWalletAddress: solanaWallet.address\n});\n\nconsole.log(`Swap completed: ${swap.transactionId}`);\nconsole.log(`Explorer: ${swap.explorerUrl}`);\n```\n</details>\n\n<details>\n<summary><b>Sui</b></summary>\n\n#### Token Addresses\n```typescript\nconst SUI_TOKENS = {\n    SUI: '0x2::sui::SUI', // Native SUI\n    USDC: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'\n};\n```\n\n#### Get Quote\n```typescript\nconst quote = await client.dex.getQuote({\n    chainId: '784',         // Sui mainnet\n    fromTokenAddress: SUI_TOKENS.SUI,\n    toTokenAddress: SUI_TOKENS.USDC,\n    amount: '1000000000',   // 1 SUI (9 decimals)\n    slippage: '0.005'         // 0.5%\n});\n```\n\n#### Execute Swap\n```typescript\nconst swap = await client.dex.executeSwap({\n    chainId: '784',\n    fromTokenAddress: SUI_TOKENS.SUI,\n    toTokenAddress: SUI_TOKENS.USDC,\n    amount: '500000000',    // 0.5 SUI\n    slippage: '0.005',\n    userWalletAddress: suiWallet.address\n});\n\nconsole.log(`Swap completed: ${swap.transactionId}`);\nconsole.log(`Explorer: ${swap.explorerUrl}`);\n```\n</details>\n\n## Advanced Features\n\n### Onchain Gateway APIs\n\nThe SDK provides access to advanced trading infrastructure for developers with API access:\n\n#### Transaction Broadcasting with MEV Protection\n```typescript\n// Requires API registration and whitelist approval\nconst broadcastResult = await client.dex.broadcastTransaction({\n    signedTx: signedTransaction.rawTransaction,\n    chainIndex: '8453',     // Base Chain\n    address: walletAddress,\n    enableMevProtection: true  // MEV protection\n});\n\nconsole.log(`Order ID: ${broadcastResult.data[0].orderId}`);\nconsole.log(`Transaction Hash: ${broadcastResult.data[0].txHash}`);\n```\n\n#### Gas Limit Estimation\n```typescript\nconst gasLimit = await client.dex.getGasLimit({\n    chainId: '8453',\n    fromAddress: walletAddress,\n    toAddress: contractAddress,\n    txAmount: '0',\n    inputData: transactionData\n});\n```\n\n#### Transaction Simulation\n```typescript\n// Requires API registration and whitelist approval\nconst simulation = await client.dex.simulateTransaction({\n    chainId: '8453',\n    fromAddress: walletAddress,\n    toAddress: contractAddress,\n    txAmount: transactionValue,\n    inputData: transactionData\n});\n\nconsole.log(`Gas used: ${simulation.gasUsed}`);\nconsole.log(`Success: ${simulation.success}`);\n```\n\n#### Order Tracking\n```typescript\nconst orders = await client.dex.getTransactionOrders({\n    orderId: 'your_order_id',\n    chainIndex: '8453',\n    address: walletAddress\n});\n\nconsole.log(`Status: ${orders.data[0].orders[0].txStatus}`);\nconsole.log(`Transaction Hash: ${orders.data[0].orders[0].txHash}`);\n```\n\n> **Note**: Transaction broadcasting and simulation features require API registration and whitelist approval for access. These methods provide enhanced reliability and monitoring capabilities for high-volume trading operations. Please reach out to [dexapi@okx.com](mailto:dexapi@okx.com) to request access.\n\n### Other Common Operations\n\n#### Get Available Tokens\n```typescript\n// Get all supported tokens for a chain\nconst tokens = await client.dex.getTokens('8453'); // Base Chain\nconsole.log(`Supported tokens: ${tokens.data.length}`);\n```\n\n#### Check Liquidity Sources\n```typescript\n// Get available DEX liquidity sources\nconst liquidity = await client.dex.getLiquidity('8453');\nconsole.log('Available DEXs:', liquidity.data.map(dex => dex.name));\n```\n\n#### Get Chain Information\n```typescript\n// Get chain configuration and router addresses\nconst chainInfo = await client.dex.getChainData('8453');\nconsole.log(`Router address: ${chainInfo.data[0].dexTokenApproveAddress}`);\n```\n\n#### Raw Swap Data (for custom implementations)\n```typescript\n// Get raw swap transaction data without execution\nconst swapData = await client.dex.getSwapData({\n    chainId: '8453',\n    fromTokenAddress: BASE_TOKENS.ETH,\n    toTokenAddress: BASE_TOKENS.USDC,\n    amount: '1000000000000000000',\n    slippage: '0.005',\n    userWalletAddress: walletAddress\n});\n\n// Use swapData.data[0].tx for custom transaction handling\n```\n\n## Error Handling\n\nThe SDK includes comprehensive error handling with detailed error codes:\n\n```typescript\ntry {\n    const swap = await client.dex.executeSwap({\n        chainId: '8453',\n        fromTokenAddress: BASE_TOKENS.ETH,\n        toTokenAddress: BASE_TOKENS.USDC,\n        amount: '1000000000000000000',\n        slippage: '0.005',\n        userWalletAddress: walletAddress\n    });\n} catch (error: any) {\n    // Handle specific error cases\n    if (error?.status === 429) {\n        console.log('Rate limited, please try again later');\n    } else if (error.message?.includes('Insufficient liquidity')) {\n        console.log('Not enough liquidity for this trade');\n    } else if (error.message?.includes('Insufficient balance')) {\n        console.log('Wallet balance too low');\n    } else if (error.message?.includes('Slippage too high')) {\n        console.log('Price impact exceeds slippage tolerance');\n    } else {\n        console.error('Swap failed:', error.message);\n        \n        // Log additional error details for debugging\n        if (error.details) {\n            console.error('Error details:', error.details);\n        }\n    }\n}\n```\n\n### Common Error Scenarios\n\n| Error Type | Description | Solution |\n|------------|-------------|----------|\n| `Insufficient liquidity` | Not enough liquidity for the requested trade size | Reduce trade amount or try different route |\n| `Insufficient balance` | Wallet doesn't have enough tokens | Check wallet balance and fund if needed |\n| `Slippage too high` | Price moved beyond acceptable range | Increase slippage tolerance or reduce trade size |\n| `Rate limited (429)` | Too many API requests | Implement exponential backoff retry logic |\n| `Invalid token address` | Token not supported on this chain | Verify token address for the specific chain |\n| `Network error` | RPC or network connectivity issues | Check network connection and RPC endpoint |\n\n## Examples and Testing\n\n### Running Examples\n\nThe SDK includes comprehensive examples for all supported chains:\n\n```bash\n# EVM examples (Base, Ethereum, Polygon, etc.)\nnpm run example:evm-quote          # Get price quotes\nnpm run example:evm-swap           # Execute swaps\nnpm run example:evm-approve        # Token approvals\nnpm run example:evm-broadcast      # Enterprise broadcasting\n\n# Solana examples\nnpm run example:solana-quote       # Get SOL quotes\nnpm run example:solana-swap        # Execute SOL swaps\n\n# Sui examples  \nnpm run example:sui-quote          # Get SUI quotes\nnpm run example:sui-swap           # Execute SUI swaps\nnpm run example:sui-broadcast      # Sui broadcasting\n\n# TON and TRON examples\nnpm run example:ton-quote          # TON quotes\nnpm run example:tron-quote         # TRON quotes\n```\n\n### Testing\n\n```bash\n# Run all tests\nnpm test\n\n# Run chain-specific tests\nnpm test -- --testPathPattern=evm\nnpm test -- --testPathPattern=solana\nnpm test -- --testPathPattern=sui\n\n# Run with coverage\nnpm run test:coverage\n```\n\n### Advanced API Features\n\nDevelopers with access to the Onchain Gateway API get additional capabilities:\n\n- **MEV Protection** - Front-running and sandwich attack protection\n- **Priority Transaction Broadcasting** - Faster transaction confirmation through OKX infrastructure\n- **Advanced Analytics** - Detailed transaction monitoring and reporting\n- **Enhanced Reliability** - Direct access to OKX's trading infrastructure\n\n> **Access Requirements**: These features require API registration and whitelist approval. Contact [dexapi@okx.com](mailto:dexapi@okx.com) to request access to the Onchain Gateway API.\n\n## License\n\nThis SDK is released under the [MIT License](LICENSE.md).\n\nBy using this SDK, you agree to the fact that: OKX and its affiliates shall not be liable for any direct, indirect, incidental, special, consequential or exemplary damages as outlined in the [Legal Disclaimer](DISCLAIMER.md).","readmeFilename":"README.md","_rev":"1-f04dbd2e3761917df3f2117e9f7bcea0"}