# Alpha Sec. Docs > Alpha Sec. is an orderbook DEX on Kaia. Covers architecture, API references, and SDKs for developers building on the fastest, deepest DEX on Kaia. This file contains all documentation content in a single document following the llmstxt.org standard. ## Fees & Rebates # Fees & Rebates Alpha Sec. offers a premier trading experience with industry-leading fee rates. ## Fee Rates: ### Maker Fee: 0.025% - A Maker Order adds liquidity by placing a limit order that does not execute immediately. ### Taker Fee: 0.035% - A Taker Order removes liquidity by executing a market or aggressive limit order that matches instantly. Register a referral code to receive a 10% fee rebate during the promotion. > **Note:** All current fees apply to spot markets on Alpha Sec. A separate fee schedule will apply to perpetuals in future releases. ## Fee Collection & Rebate Claims - **Fees**: Charged automatically on trade execution. No manual action is required. - **Rebates(Coming soon)**: Calculated daily and automatically credited to your wallet. Track your rewards in the Alpha Sec. “Referrals” menu. ## Built for Alpha Sec. All fee and rebate logic is handled within Alpha Sec.’s gasless execution layer. This ensures real-time responsiveness and seamless integration with Alpha Sec. without introducing user friction or off-chain dependencies. --- ## Market Making # Market Making ## Designated Market Maker (DMM) Program Alpha Sec.'s Designated Market Maker (DMM) Program is open to any participant, from individual traders to professional market-making firms, who are committed to contributing meaningful liquidity. This open-access approach ensures that anyone with the right strategy and infrastructure can participate and earn rewards, not just institutions. Participants receive tailored incentives in exchange for meeting predefined quoting and volume obligations. ## Program Benefits - **Volume-Based Maker Rebates**: Enhanced earnings for providing sustained liquidity - **Early Access**: Priority onboarding for new listings and protocol features - **Custom Fee Tiers**: Flexible structures based on market performance The DMM Program plays a critical role in strengthening organic liquidity within Alpha Sec., while promoting healthy market dynamics and fair price discovery. **Apply to Join:** ## Technical Integration Support Alpha Sec. offers robust integration support for market makers building on its high-throughput architecture. All trades are executed via a deterministic sequencer and settled on-chain, requiring efficient, latency-aware connectivity. Available resources include: - **REST & WebSocket APIs**: Real-time order submission and orderbook updates - **Engine & Sequencer Documentation**: Detailed guides on matching logic and sequencing - **Dedicated Engineering Support**: 1:1 assistance for onboarding and infrastructure tuning **Start building today:** **Questions? Reach out via our support channel:** --- ## Order Types # Order Types Alpha Sec. supports a comprehensive suite of order types tailored for both retail users and advanced traders. All orders are processed by Alpha Sec.'s deterministic sequencer and settled on-chain, ensuring full transparency, verifiable execution, and sub-second responsiveness. ## Basic Order Types - **Limit Order**: A limit order allows users to specify the maximum price at which they are willing to buy or the minimum price at which they are willing to sell. It is placed in the orderbook and only executes if the market reaches the specified price or better, making it well-suited for price-sensitive execution. - **Market Order**: A market order executes instantly at the best available price in the orderbook. It prioritizes execution speed over price precision and is commonly used for time-critical trades where immediate fill is preferred. ## Conditional & Time-Based Orders - **Stop-Limit**: This order type converts into a limit order once the market reaches a predefined stop price. It offers traders control over both the trigger condition and the execution price. - **Stop-Market**: This order becomes a market order when the stop price is hit. While it guarantees execution after the trigger, the final execution price may vary with market conditions. - **TP/SL (Take Profit / Stop Loss)**: These are conditional orders designed to close a position automatically when a specific profit or loss threshold is reached. They are commonly used in risk management and automated strategy execution. - **GTC (Good-Til-Cancelled)**: By default, all orders on Alpha Sec. are set to GTC. These orders remain active in the orderbook until they are either fully filled or manually cancelled by the user. ## Advanced Order Types (Coming Soon) - **Trailing Stop**: A trailing stop order dynamically adjusts the stop price as the market moves in the trader's favor. If the price reverses by a set percentage, a market order is triggered to help capture profits while limiting downside risk. - **OCO (One-Cancels-the-Other)**: OCO orders pair a limit order with a stop order. When one of the two is executed or cancelled, the other is automatically cancelled. This mechanism is useful for conditional entry and exit strategies. - **TWAP (Time-Weighted Average Price)**: TWAP splits a large order into smaller slices and executes them at regular intervals over time. This method helps reduce market impact and slippage, making it a preferred option for institutional and algorithmic traders. - **ALO (Add Liquidity Only / Post-Only)**: This order type ensures that the order adds liquidity to the market. If the order would match immediately upon placement, it is rejected. It is commonly used by market makers to guarantee Maker status and avoid taker fees. - **IOC (Immediate or Cancel)**: An IOC order attempts to execute all or part of the order immediately. Any unfilled portion is cancelled without delay. This is suitable for time-sensitive trades where only immediate liquidity is desired. --- ## Orderbook # Orderbook ## What is an Orderbook? The orderbook is the foundational data structure that enables trading on Alpha Sec.. It maintains a real-time record of all open buy and sell orders for each supported trading pair (e.g., KAIA/USDT), fully on-chain. Each order includes: - **Price**: The target execution rate - **Amount**: The order size denominated in base asset - **Direction**: Bid (buy) or Ask (sell) Alpha Sec.'s orderbook replicates the familiarity and precision of centralized exchanges, while delivering full on-chain verifiability and transparency. ## Key Concepts **Bid & Ask** - **Bids**: Offers to buy at a specified price - **Asks**: Offers to sell at a specified price The orderbook is price-sorted, with the highest bids and lowest asks defining the market spread. **Price Levels** - Orders at the same price are aggregated into a single price level - Each level displays the total liquidity available at that price point **Live Updates** - The orderbook updates in real time as orders are placed, filled, or canceled - All changes are reflected in the Optimistic Rollup Layer 2 state and anchored to Kaia L1 for auditability ## On-Chain Transparency Unlike many DEXs that operate using off-chain matching or opaque orderflow, Alpha Sec.'s orderbook is: - **Fully on-chain** - **Publicly queryable** - **Cryptographically verifiable** Every order and update is processed through Alpha Sec.'s execution layer, providing deterministic behavior with zero MEV leakage or hidden flows. ## Designed for Spot Trading Alpha Sec. is designed exclusively for spot markets. There are no perpetuals, leverage, or synthetic instruments. This focus enables: - **A clean, latency-optimized market structure** - **Reliable execution** for high-frequency and algorithmic traders - **Efficient price discovery** within the Kaia ecosystem --- ## Perpetual Markets # Perpetual Markets Perpetual trading is scheduled for release in the first half of 2026. --- ## Points # Points AlphaSec recognizes and rewards traders who contribute to the ecosystem's liquidity, depth, and stability. Whether you are a casual participant or a professional trader, your contribution is quantified and recorded as Points. All the points have been distributed to traders since the launch of our Spot Market on December 4, 2025. You can check your pre-accumulated points immediately on the dashboard. ## Overview * **Duration**: December 4, 2025 ~ Until further notice * **Eligible Users**: Any user who connects a wallet and generates a daily trading volume of at least $100 on AlphaSec Spot Market. * **Eligible Markets**: All Spot trading pairs currently listed on AlphaSec. * **Distribution**: Points are updated and distributed once daily after 00:45 UTC. You can view your accumulated points on the Points Dashboard. > **Note:** Points accumulate based on your trading activity and will be redeemable for future benefits. ## Point Mechanism The specific calculation formula is proprietary to ensure fair play, but your Points are determined based on the following key factors: * **Trading Volume (Core)**: Points are primarily calculated based on your Filled Volume (executed Buy and Sell orders). * **Asset Balance (Boost)**: Higher asset balances held in your account may positively impact your point generation efficiency. * **Consistency (Boost)**: Consecutive active trading days are recognized as a contribution to ecosystem stability and may apply a positive weight to your score. > **Note:** A day counts as "active" only when your daily trading volume reaches the minimum threshold ($100). ## Tier System Your trading performance is reflected in a **Tier badge** displayed on the Points Dashboard. Tiers range from **Bronze** to **Grand Master** based on your cumulative trading volume. Higher tiers represent greater contribution to the AlphaSec ecosystem. ## Anti-Abuse & Fair Play AlphaSec enforces a strict anti-abuse policy to protect genuine users. * **Prohibited Activities**: Wash trading, Sybil attacks, self-dealing, bot-driven volume manipulation, and any other activity deemed abusive by our Risk Management System. * **Penalty**: Any account found engaging in abusive behavior will have all points forfeited and may be permanently banned from the service without prior notice. ## Disclaimer Points are a measure of contribution to the AlphaSec ecosystem and do not hold any monetary value. Points are not exchangeable for cash or other assets. Policies regarding the program may be adjusted and updated at the team’s discretion. --- ## Referrals # Referrals ## Incentivized Growth, Community-Driven Adoption Alpha Sec.’s referral system is designed to reward organic user acquisition while preserving integrity and economic sustainability. Both Referrers and Referees benefit through a transparent, performance-aligned fee-sharing model. ## For Referees Users who register using a referral link or manually enter a referral code are eligible for a 10% rebate on all trading fees they pay. Rebates are automatically calculated based on the total trading value(in USDT terms) at the time of each trade and are distributed once per day(00:10 UTC) through a batch process. **Key Details**: - Referral codes can be applied either automatically via a referral link or manually through the Referrals page in the Alpha Sec. interface. - The 10% rebate applies to all trading fees, including both maker and taker fees. - Rebates are paid in USDT, regardless of the original fee token. - The rebate amount is calculated based on the total trading value (in USDT terms) at the time of each trade. - Rebate distributions are processed once daily and automatically credited to the your account balance. - Once a referral code is applied to an account, it is permanent and cannot be changed. ## For Referrers Referrers earn a 20% commission on all trading fees (both maker and taker) paid by users who register through their referral link or enter their referral code. Rewards are automatically calculated and distributed once per day(00:10 UTC) in USDT. **Key Details**: - To create a personal referral code, users must first reach a total trading volume of at least $1,000. - Once eligible, the referral code can be created and used without maintaining the volume threshold thereafter. - The daily maximum reward per Referee is $300. - Commissions are automatically calculated based on the total trading fee value at the time of each trade and distributed through a daily batch process. - This requirement helps prevent the creation of dummy or sybil accounts and ensures that rewards are directed toward genuine, active traders. > **Note:** Referral program terms, reward rates, and eligibility criteria are subject to change based on protocol growth, economic conditions, and abuse prevention measures. Any changes will be announced in advance through official channels. ## Referrals Page Guide The Referrals page in the Alpha Sec. interface allows users to manage referral codes, monitor referral performance, and track daily rewards. **Available Actions:** - **Create Referral Code**: - Available once total trading volume reaches $1,000. - Generates both a Referral Code and Referral Link. - Supports direct sharing to X (Twitter), Telegram, and Discord. - **Enter Referral Code**: - You can manually input a friend’s code (requires Session Wallet). - Referral links automatically pre-fill the code. - Self-referrals are not allowed. You cannot apply your own referral code. - **Check Eligibility Progress**: - Real-time updates on trading volume toward the referral code creation threshold. - **View Reward Summary**: - Displays total earned Commission and Rebate (in USDT). - Shows daily change compared to the previous batch. **Viewable Information:** - **Commission Program**: Referral volume, total commission earned, and current commission rate. - **Rebate Program**: Personal trading volume, total rebate earned, and current rebate rate. - **Reward History**: Daily distribution records with type (Commission / Rebate), eligible volume, reward amount, and timestamp. - **Referees List**: Wallet addresses of referred users, join date, total volume, paid fees, and rewards generated. --- ## Spot Markets # Spot Markets ## What is Spot Trading? Spot trading is the most straightforward and transparent way to trade crypto. It involves the direct exchange of one asset for another at the current market price, with full ownership transferred upon execution. Unlike derivatives such as perpetuals, spot trades do not involve: - Leverage - Margin requirements - Expiry dates - Funding fees **Alpha Sec. supports spot trading only, as of the current release**, delivering a clean, high-performance trading experience. ## How Spot Markets Work on Alpha Sec. Alpha Sec.'s spot markets follow the **BASE-QUOTE format** — for example, KAIA/USDT: - **Buying KAIA** means spending USDT - **Selling KAIA** means receiving USDT To place buy orders, users must hold enough of the quote asset (e.g., USDT). All spot trades are powered by Alpha Sec.’s ultra-fast execution layer, which guarantees: - **Low-latency trading** with responsiveness approaching centralized exchange standards - **Price-time priority** enforced through deterministic on-chain matching - **Fully verifiable execution** with transparent, auditable trade settlement ## Supported Markets Alpha Sec. initially launches with a curated set of high-quality assets, including Kaia-native tokens, LINE Mini-Dapp tokens, and established blue-chip assets. All pairs use native USDT on Kaia as the quote asset, enabling fast, gasless settlement and deep liquidity provisioning. | Name | Symbol | Token Contract | Trading Pair | |------------|--------|--------------|--------------| |Kaia|KAIA|Native Asset|KAIA/USDT| |Tether USD|USDT|0xd077a400968890eacc75cdc901f0356c943e4fdb|All pairs as quote| |WETH (Portal from Ethereum)|WETH|0x98a8345bb9d3dda9d808ca1c9142a28f6b0430e1|WETH/USDT| |BORA|BORA|0x02cbe46fb8a1f579254a9b485788f2d86cad51aa|BORA/USDT| |IDRX|IDRX|0x18bc5bcc660cf2b9ce3cd51a404afe1a0cbd3c22|IDRX/USDT| |BTCB Token|BTCB|0x15d9f3ab1982b0e5a415451259994ff40369f584|BTC/USDT| > **Notes:** Support for additional tokens will continue to expand in line with ecosystem growth on the Kaia network. --- ## Vibe Trading # Vibe Trading ## AI-Powered Strategy Simulation and Execution Vibe Trading is AlphaSec's AI-powered trading tool that lets anyone create, backtest, and execute trading strategies using natural language. No coding, no complex interfaces. Just describe what you want, and AI handles the rest. > **Note:** Vibe Trading currently supports spot markets only. All features, from backtesting to auto trading and marketplace, are designed for spot trading pairs. ## Why Vibe Trading? Millions of potential traders sit on the sidelines. They have the capital and the ideas, but are blocked by tools built for institutions. Traditional trading demands: - Programming skills for backtesting - Quantitative expertise for strategy design - Constant attention for execution and risk management This Complexity Barrier keeps retail capital locked out of the market entirely. Vibe Trading operates on a single principle: **Your Own Trading Agent**. You provide the intent, and AI handles the rest. No professional knowledge needed. Trade from anywhere, using natural language. Start building your edge today, as every update brings Vibe Trading closer to a fully autonomous agent that executes your strategies around the clock. ## AI Strategy Simulation Describe a trading idea in your own words, and Vibe Trading's AI generates a complete strategy and simulates it against real historical market data. Programming skills or trading knowledge are no longer required. The AI interprets your intent, selects the right parameters, and delivers a full backtest result you can evaluate instantly. ### Set Up Your Workspace Before writing your strategy prompt, select the **trading pair** and **resolution** (candle timeframe) in the Vibe Trading workspace. These are configured through the workspace UI, so your prompt focuses purely on strategy logic. **Available resolutions:** 1m, 5m, 1h, 4h, 1D The resolution you choose also affects the backtest coverage period. A shorter resolution (e.g., 1m) covers a shorter historical window, while a longer resolution (e.g., 1D) covers a broader range of market history. ### Describe Your Strategy Enter your trading idea as a plain-text prompt. You can be as simple or as specific as you'd like. Vibe Trading is designed to understand your intent, even if you don't use precise trading terminology. **Example prompts:** - `"Buy when the price drops a lot, sell when it recovers."` - `"Buy when the market looks oversold and take profit at 2%."` - `"Accumulate slowly over the next 30 days."` - `"Buy when RSI **Note:** Your entire available USDT balance is allocated as the investment amount. Ensure your balance reflects the amount you intend to trade before activation. ### Execution - Each bot operates through a dedicated **Session Key**, signed via EIP-712. Your Master Wallet private key is never exposed to the bot. - The bot evaluates your strategy at each candle close based on the resolution used during backtesting, and executes **market orders** when conditions are met. - Only **one bot can run per wallet** at a time. ### Bot Dashboard While your bot is running, the Bot Dashboard provides real-time visibility: - **Status Bar**: Running/Stopped status, trading pair, expiration date, and stop reason (if stopped) - **Performance Metrics**: PnL (USDT and %), live elapsed time, Win Rate, Trade Count, Max Drawdown, Sharpe Ratio - **Current Position**: Total balance with per-asset breakdown (price, 24h change, holdings) - **Trade History**: Complete log of executed trades with timestamps, side, price, and quantity ### Auto-Stop Conditions The bot automatically stops under the following conditions: | Condition | Description | |-----------|-------------| | Max Loss reached | Portfolio value drops below the configured loss threshold | | Duration expired | The configured operating period and session key expire together | | Consecutive failures | 5 consecutive execution errors occur | You can also stop your bot manually at any time. All open orders are automatically canceled on stop. Any base token held at the time of stopping remains in your wallet and is not automatically sold. ## Marketplace Vibe Trading Marketplace allows you to explore strategies created by other users and run them with your own capital. ### List Your Strategy You can publish your own strategies to the Marketplace for others to discover and clone. Listing is self-service with no admin approval required, but your strategy must meet the following criteria: | Criteria | Requirement | |----------|-------------| | Minimum trades | At least 5 individual trade executions (buys and sells counted separately) | | Minimum backtest period | At least 7 days | | Minimum return | Positive return (above 0.1%) | You can delist your strategy at any time. Existing users who have already cloned your strategy will continue to operate their bots independently. ### Browse Discover top-performing strategies from the community, sorted by PnL or recency. Each strategy card displays: - Strategy name (AI-generated) and trading pair - Total return (%) - AI-generated summary describing the strategy's intent - Number of clones and active bots Clicking a strategy card opens its detail page, where you can review the full backtest result including performance metrics, candlestick chart with trade markers, and complete trade history. The original prompt and generated code are never exposed. The AI-generated summary describes what the strategy does without revealing specific indicators, parameters, or entry/exit conditions, protecting the creator's intellectual property. ### Clone Clone any Marketplace strategy to run it as an automated trading bot on your own account. 1. Browse the Marketplace and select a strategy 2. Review the backtest results and performance metrics on the detail page 3. Click "Start Auto Trading" to clone the strategy and open the configuration modal 4. Configure Max Loss, Duration, and activate your bot Unlike traditional copy trading, which mirrors another trader's live positions in real time, Clone deploys the strategy logic directly to your wallet. The strategy runs independently with your own risk parameters. The original creator does not need to be online, and your execution is entirely isolated and secure. ### Provider Incentives (Coming Soon) Vibe Trading plans to introduce a revenue-sharing model that rewards strategy providers based on their contribution to the ecosystem. Top-performing providers will be able to earn from their strategies, creating a sustainable cycle where better strategies attract more followers and generate rewards for creators. > **Note:** Backtest results are simulated based on historical data and do not guarantee future performance. Auto trading with any strategy, whether your own or from the Marketplace, carries inherent risk. AlphaSec and strategy providers are not responsible for trading losses. ## What's Next ### Expansion and Optimization Building on the foundation of strategy creation, backtesting, auto trading, and marketplace, the next phase focuses on expanding the platform's reach and continuously improving quality across the product. - **Perpetual Futures Support**: Expanding strategy creation, simulation, and auto trading to cover perpetual futures markets, enabling leveraged long/short strategies with futures-specific risk controls through the same natural language interface - **External Integrations**: Expanding the trading interface beyond the web platform through messenger-based access, including MCPs, Telegram bots, and LINE dApps - **Personalized Automation Settings**: User-level risk management tools that operate alongside strategies, such as automatic take-profit/stop-loss configuration and time-based position exits - **Strategy Optimization**: AI-powered parameter tuning that analyzes historical data and patterns to automatically optimize strategy performance - **Continuous Fine-tuning**: Ongoing improvements to strategy generation, backtesting accuracy, and auto trading reliability ### Autonomous Agent The final phase introduces an always-on AI agent that monitors your positions and portfolio 24/7, proactively responding to market conditions based on your preferences and risk profile. - **Proactive Suggestions**: The agent identifies opportunities and risks before you ask, delivering timely recommendations - **Real-time Market Monitoring**: Continuous analysis of both on-platform activity and external market signals, including social media sentiment, with automated responses when conditions are met - **Human-in-the-Loop Control**: Critical decisions require your explicit approval via push notification before execution, keeping you in control while the agent handles the monitoring - **Full Transparency**: Every decision, action, and reasoning by the agent is recorded and accessible, providing a complete audit trail of all automated activity --- ## API # API This API enables developers and professional traders to integrate directly with Alpha Sec. It provides full access to market data, wallet management, order handling, transaction signing, and real-time WebSocket streams. All APIs are designed with performance, precision, and transparency in mind. ## SDKs - Python SDK: https://github.com/alphasec-dex/alphasec-python-sdk - Rust SDK: https://github.com/alphasec-dex/alphasec-rust-sdk ## API Base URLs - Mainnet: https://api.alphasec.trade - Testnet: https://api-testnet.alphasec.trade - WebSocket(Mainnet): wss://api.alphasec.trade/ws - WebSocket(Testnet): wss://api-testnet.alphasec.trade/ws --- ## Bridge # Bridge ## General Information The bridge enables asset transfers between Kaia L1 and L2. This document covers: - **Deposit**: Moving assets from Kaia L1 to L2 (direct transaction submission) - **Withdrawal**: Moving assets from L2 to Kaia L1 (via API endpoint) ### Key Bridge Addresses #### Fixed Addresses - **ArbSys Contract**: `0x0000000000000000000000000000000000000064` (for L2 native KAIA withdrawal) #### Deployment-Dependent Addresses **L1 Contracts:** - **Inbox Contract**: L1 bridge entry point (for KAIA deposits) - **L1 Gateway Router**: Manages L1 ERC20 token deposits - **L1 ERC20 Gateway**: ERC20 gateway **L2 Contracts:** - **L2 Gateway Router**: Manages L2 ERC20 token withdrawals - **L2 ERC20 Gateway**: L2 ERC20 gateway **Note**: Deployment-dependent addresses are determined at network deployment time, so always verify you are using the correct address values. ## Deposit (Kaia L1 → L2) Deposits are initiated by sending transactions directly to bridge contracts on Kaia L1. No API endpoints are provided; users must construct and submit transactions directly to the L1 network. ### 1. KAIA Deposit (Native Token) To deposit native KAIA from Kaia L1 to L2, call the `depositEth()` function on the Inbox contract. #### Transaction Structure ```javascript { from: "0x...", // User's L1 wallet address to: "0x...", // Inbox contract address (L1 bridge entry point) data: "0x439370b1", // depositEth() function selector value: "0x...", // Amount of KAIA to deposit (in wei) gasLimit: "0x30d40", // 200000 - sufficient gas gasPrice: "0x...", // Current L1 network gas price nonce: "...", // User account nonce chainId: "..." // L1 chain ID (Kaia Testnet: 1001, Kaia Mainnet: 8217) } ``` #### Field Descriptions - **from**: User's L1 network wallet address performing the deposit - **to**: Inbox contract address - official L1 bridge entry point deployed by bridge operators - **data**: `depositEth()` function selector - always `0x439370b1` - **value**: KAIA amount to deposit (in wei, 1 KAIA = 10^18 wei) - **gasLimit**: `0x30d40` (200000) - sufficient gas for deposit operation - **gasPrice**: Current L1 network gas price needs to be queried - **nonce**: User account's sequential transaction counter - **chainId**: - Kaia Testnet: `1001` - Kaia Mainnet: `8217` #### Creating and Signing Deposit Transaction ```javascript const { ethers } = require('ethers') // Initialize Provider and Signer const l1Provider = new ethers.providers.JsonRpcProvider(L1_RPC_URL) const l1Signer = new ethers.Wallet(PRIVATE_KEY, l1Provider) // Create Inbox contract interface const inbox = new ethers.Contract( INBOX_CONTRACT_ADDRESS, // L1 bridge entry point ['function depositEth() external payable returns (uint256)'], l1Signer ) // Method 1: Using contract interface (recommended) const depositTx = await inbox.depositEth({ value: ethers.BigNumber.from('1000000000000000000'), // 1 KAIA (in wei) gasLimit: 200000 // Sufficient gas }) // Method 2: Manual transaction construction const unsignedTx = { from: l1Signer.address, to: INBOX_CONTRACT_ADDRESS, // L1 bridge entry point data: '0x439370b1', // depositEth() selector value: '0xde0b6b3a7640000', // 1 KAIA (hex, 10^18 wei) gasLimit: '0x30d40', // 200000 (hex) - sufficient gas gasPrice: await l1Provider.getGasPrice(), nonce: await l1Provider.getTransactionCount(l1Signer.address), chainId: (await l1Provider.getNetwork()).chainId } // Sign transaction const signedTx = await l1Signer.signTransaction(unsignedTx) // Send transaction const txResponse = await l1Provider.sendTransaction(signedTx) console.log('Deposit transaction:', txResponse.hash) ``` #### Notes 1. **Inbox Contract**: The `to` address must be the official Inbox contract deployed on L1 2. **Gas Requirements**: L1 transactions require actual gas fees 3. **Value Field**: Deposit amount must be specified in the `value` field in wei 4. **Network Compatibility**: Use the correct chain ID and RPC endpoint for your target network ### 2. ERC20 Token Deposit This section describes the transaction structure and process for depositing ERC20 tokens from L1 to L2. #### Transaction Structure ##### Step 1: Token Approval Transaction ```javascript { from: "0x...", // User's L1 wallet address to: "0x...", // ERC20 token contract address data: "0x095ea7b3...", // approve(spender, amount) encoded data value: "0x0", // No KAIA needed for ERC20 approval gasLimit: "0xc350", // 50000 - sufficient gas gasPrice: "0x...", // Current L1 network gas price nonce: "...", // User account nonce chainId: "..." // L1 chain ID (Kaia Testnet: 1001, Kaia Mainnet: 8217) } ``` ##### Step 2: Deposit Transaction via L1GatewayRouter ```javascript { from: "0x...", // User's L1 wallet address to: "0x...", // L1GatewayRouter contract address data: "0x...", // outboundTransfer() encoded call data value: "0x...", // L2 execution cost (bridge fee) gasLimit: "0x7a120", // 500000 - sufficient gas gasPrice: "0x...", // Current L1 network gas price nonce: "...", // User account nonce chainId: "..." // L1 chain ID } ``` #### Field Descriptions ##### Token Approval Transaction - **from**: User's L1 wallet address performing the deposit - **to**: L1 ERC20 token contract address - **data**: `approve(address spender, uint256 amount)` function call encoding - spender: L1 ERC20 Gateway address (query from router) - amount: Token amount to approve (in smallest unit) - **value**: Always `0x0` (no KAIA needed for ERC20 approval) - **gasLimit**: `0xc350` (50000) - sufficient gas for approval operation ##### Deposit Transaction - **from**: User's L1 wallet address - **to**: L1GatewayRouter contract address - deployed bridge entry point - **data**: `outboundTransfer()` function call encoding - L1 token address - L2 recipient address (typically same as sender) - Token amount to deposit - Max gas for L2 execution - Gas price bid for L2 execution - Additional data - **value**: KAIA fee for L2 bridge processing - **gasLimit**: `0x7a120` (500000) - sufficient gas for deposit operation #### Complete Implementation Flow ```javascript const { ethers } = require('ethers') // ==================================================================== // Initial Setup // ==================================================================== const l1Provider = new ethers.providers.JsonRpcProvider(L1_RPC_URL) const l1Signer = new ethers.Wallet(PRIVATE_KEY, l1Provider) // Load contract addresses from network configuration const L1_GATEWAY_ROUTER = '0x...' // Get from network configuration const L1_TOKEN = '0x...' // ERC20 token to deposit // Create token contract interface const token = new ethers.Contract(L1_TOKEN, [ 'function approve(address spender, uint256 amount) returns (bool)', 'function allowance(address owner, address spender) view returns (uint256)', 'function decimals() view returns (uint8)', // For querying decimals ], l1Signer) // Create router contract interface const router = new ethers.Contract(L1_GATEWAY_ROUTER, [ 'function getGateway(address) view returns (address)', 'function outboundTransfer(address,address,uint256,uint256,uint256,bytes) payable returns (bytes)', ], l1Signer) // ==================================================================== // Step 0: Query Token Info and Gateway // ==================================================================== // Query token decimals const decimals = await token.decimals() const depositAmount = ethers.utils.parseUnits('100', decimals) // 100 tokens // Query gateway from router const gateway = await router.getGateway(L1_TOKEN) // Query gateway from router // ==================================================================== // Step 1: Token Approval Transaction // ==================================================================== const allowance = await token.allowance(l1Signer.address, gateway) if (allowance.lt(depositAmount)) { // Encode approve() function data const approveData = token.interface.encodeFunctionData('approve', [ gateway, // Address to approve (gateway) depositAmount // Token amount to approve ]) // Construct transaction object const approveTx = { from: l1Signer.address, to: L1_TOKEN, // ERC20 token contract data: approveData, // approve(gateway, amount) value: '0x0', // No KAIA needed for ERC20 approval gasLimit: '0xc350', // 50000 - sufficient gas gasPrice: await l1Provider.getGasPrice(), nonce: await l1Provider.getTransactionCount(l1Signer.address), chainId: (await l1Provider.getNetwork()).chainId } // Sign and send transaction const signedApprove = await l1Signer.signTransaction(approveTx) const approveReceipt = await l1Provider.sendTransaction(signedApprove) await approveReceipt.wait() console.log('Token approval complete:', approveReceipt.hash) } // ==================================================================== // Step 2: Deposit Transaction // ==================================================================== // Set bridge parameters const maxGas = ethers.BigNumber.from('1000000') const gasPriceBid = ethers.utils.parseUnits('1', 'gwei') const bridgeFee = ethers.utils.parseEther('0.01') // Fixed fee for L2 execution and submission costs // Encode additional data const extraData = ethers.utils.defaultAbiCoder.encode( ['uint256', 'bytes'], [bridgeFee, '0x'] ) // Encode outboundTransfer() function data const depositData = router.interface.encodeFunctionData('outboundTransfer', [ L1_TOKEN, // L1 token address l1Signer.address, // L2 recipient address depositAmount, // Token amount to deposit maxGas, // Max gas for L2 execution gasPriceBid, // Gas price bid for L2 execution extraData // Additional data ]) // Construct transaction object const depositTx = { from: l1Signer.address, to: L1_GATEWAY_ROUTER, // L1GatewayRouter contract data: depositData, // outboundTransfer() call value: bridgeFee.toHexString(), // Bridge fee (KAIA) gasLimit: '0x7a120', // 500000 - sufficient gas gasPrice: await l1Provider.getGasPrice(), nonce: await l1Provider.getTransactionCount(l1Signer.address), chainId: (await l1Provider.getNetwork()).chainId } // Sign and send transaction const signedDeposit = await l1Signer.signTransaction(depositTx) const depositReceipt = await l1Provider.sendTransaction(signedDeposit) await depositReceipt.wait() console.log('Deposit complete:', depositReceipt.hash) ``` #### Key Requirements 1. **Two-Step Process**: ERC20 deposits always require two transactions 2. **Balance Requirements**: Need both ERC20 token balance to deposit and KAIA for gas fees 3. **Network-Specific Settings**: Contract addresses vary by network deployment 4. **Allowance Optimization**: Check current allowance first to avoid unnecessary approval transactions ## Withdrawal (L2 → Kaia L1) Withdrawals are initiated on L2 via the DEX API endpoint. After creating and signing a withdrawal transaction on L2 and calling the `/api/v1/wallet/withdraw` API, the system automatically completes the withdrawal processing on Kaia L1. ### POST /api/v1/wallet/withdraw Submit a signed withdrawal transaction to move assets from L2 to Kaia L1. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}" } ``` **Request Fields:** | Field | Type | Required | Description | |-------|------|-----------|-------------| | tx | STRING | YES | Complete signed withdrawal transaction in hex format | **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ### 3. KAIA Withdrawal (Native Token) This section describes how to create a raw signed transaction for withdrawing native KAIA from L2 to L1. #### Key Points - **Gas Free**: L2 network is gas-free, so gasPrice can be set to 0 - **Nonce**: L2 supports both sequential nonces and time-based nonces (Unix timestamp in milliseconds) - **Chain ID**: Must use L2 chain ID - **Target Contract**: Fixed address `0x0000000000000000000000000000000000000064` (ArbSys precompile) #### Transaction Structure ```javascript { from: "0x...", // User's L2 wallet address to: "0x0000000000000000000000000000000000000064", // ArbSys precompile address data: "0x...", // Encoded withdrawEth(address) function call value: "0x...", // Amount of KAIA to withdraw (in wei) gasLimit: "0x7a120", // 500000 - sufficient gas gasPrice: "0x0", // 0 (gas-free network) nonce: nonce, // Sequential or time-based nonce chainId: L2_CHAIN_ID // L2 chain ID } ``` #### Field Descriptions - **from**: User's L2 wallet address performing the withdrawal - **to**: ArbSys precompile address - always `0x0000000000000000000000000000000000000064` - **data**: `withdrawEth(address destination)` function call encoding - Function selector: `0x25e16063` - destination: L1 recipient address (32 bytes with padding) - **value**: Amount of KAIA to withdraw (in wei, 1 KAIA = 10^18 wei) - **gasLimit**: `0x7a120` (500000) - sufficient gas for withdrawal operation - **gasPrice**: `0x0` - can be set to 0 as L2 is gas-free - **nonce**: Sequential nonce or time-based nonce (Date.now()) - **chainId**: L2 network chain ID #### Creating and Signing Transaction ```javascript const { ethers } = require('ethers') // Initialize L2 RPC Provider and Signer const l2Provider = new ethers.providers.JsonRpcProvider(L2_RPC_URL) const l2Signer = new ethers.Wallet(PRIVATE_KEY) // No provider connection for manual signing // Get L2 network info const l2Network = await l2Provider.getNetwork() const l2ChainId = l2Network.chainId // L2 chain ID // Prepare ArbSys interface const arbSysInterface = new ethers.utils.Interface([ 'function withdrawEth(address destination) external payable returns (uint256)' ]) // Encode function data const withdrawData = arbSysInterface.encodeFunctionData('withdrawEth', [ L1_RECIPIENT_ADDRESS // L1 recipient address ]) // Use time-based nonce const nonce = Date.now() // Time-based nonce (milliseconds) // Construct unsigned transaction const unsignedTx = { from: l2Signer.address, to: '0x0000000000000000000000000000000000000064', // ArbSys precompile data: withdrawData, value: ethers.utils.parseEther('1.0').toHexString(), // 1 KAIA gasLimit: ethers.BigNumber.from(500000).toHexString(), // Sufficient gas gasPrice: '0x0', // Gas-free so can set to 0 nonce: nonce, chainId: l2ChainId // L2 chain ID } // Sign transaction const signedTx = await l2Signer.signTransaction(unsignedTx) console.log('Signed transaction:', signedTx) // Submit via API (see POST /api/v1/wallet/withdraw above) ``` ### 4. ERC20 Token Withdrawal This section describes how to create and sign transactions for withdrawing ERC20 tokens from L2 to L1. #### Key Features - **Gas-Free Network**: L2 has no gas fees, so gasPrice can be set to 0 - **Nonce**: Both sequential and time-based nonces are supported - **Chain ID**: Use L2 chain ID - **Raw Signed Transaction**: Create pre-signed transaction for API submission #### Transaction Structure ```javascript { from: "0x...", // User's L2 wallet address to: "0x...", // L2 Gateway Router contract address data: "0x7b3a3c8b...", // outboundTransfer function call data value: "0x00", // Always 0 for ERC20 transfers gasLimit: "0x0f4240", // 1000000 - sufficient gas gasPrice: "0x00", // 0 (gas-free network) nonce: nonce, // Sequential or time-based nonce chainId: L2_CHAIN_ID // L2 chain ID } ``` #### Field Descriptions - **from**: L2 wallet address initiating the withdrawal - **to**: L2 Gateway Router contract address - manages token bridging operations - **data**: `outboundTransfer(address,address,uint256,bytes)` function call encoding - L1 token address: L1 token contract address to receive - L1 recipient address: L1 address to receive tokens - Withdrawal amount: Token quantity in wei - Additional data: Typically "0x" (empty data) - **value**: Always `0x00` for ERC20 token transfers - **gasLimit**: `0x0f4240` (1000000) - sufficient gas for withdrawal operation - **gasPrice**: `0x00` - can be set to 0 as L2 is gas-free - **nonce**: Sequential nonce or time-based nonce (Date.now()) - **chainId**: L2 network chain ID #### Transaction Creation and Signing Process ```javascript const { ethers } = require('ethers') // Configuration const L2_RPC = 'https://l2-sequencer-testnet.alphasec.trade' // Testnet L2 RPC Endpoint const PRIVATE_KEY = '0x...' const L2_GATEWAY_ROUTER = '0x097209B15FB6cEefba90EA10e4c1c5439E6bC1Ea' // Testnet L2 Gateway Router // Initialize L2 Provider and Signer const l2Provider = new ethers.providers.JsonRpcProvider(L2_RPC) const l2Signer = new ethers.Wallet(PRIVATE_KEY) // Get L2 chain ID const network = await l2Provider.getNetwork() const l2ChainId = network.chainId // Create router interface and encode function const routerInterface = new ethers.utils.Interface([ 'function outboundTransfer(address,address,uint256,bytes) returns (bytes)' ]) // Encode outboundTransfer function data const transferData = routerInterface.encodeFunctionData('outboundTransfer', [ '0xac76d4a9985aba068dbae07bf5cc10be06a19f12', // L1 Testnet token address recipient, // L1 recipient address ethers.BigNumber.from('1000000000000000000'), // 1 token (18 decimals) '0x' // Additional data (empty) ]) // Use time-based nonce const nonce = Date.now() // Time-based nonce (milliseconds) // Create transaction object const unsignedTx = { from: l2Signer.address, to: L2_GATEWAY_ROUTER, data: transferData, value: ethers.BigNumber.from(0).toHexString(), // 0x00 gasLimit: ethers.BigNumber.from(1000000).toHexString(), // Sufficient gas gasPrice: ethers.BigNumber.from(0).toHexString(), // 0x00 (gas-free) nonce: nonce, chainId: l2ChainId // L2 chain ID } // Sign transaction const rawSignedTx = await l2Signer.signTransaction(unsignedTx) console.log('Signed transaction:', rawSignedTx) // Submit via API (see POST /api/v1/wallet/withdraw above) ``` #### Notes 1. **Chain ID**: Must use L2 chain ID 2. **Gas Settings**: L2 is a gas-free network, so `gasPrice` can be set to `0` 3. **Nonce Options**: Choose between sequential nonce or time-based nonce (Date.now()) 4. **Transaction Flow**: Create and sign on L2 → Submit via API → Automatic processing ## Transaction Configuration Guidelines ### Kaia L1 Transactions (Deposits) - Use standard Kaia gas pricing - KAIA required for gas fees - Include submission cost for L2 execution - Wait for L1 confirmation before expecting funds on L2 ### L2 Transactions (Withdrawals) - Gas price can be set to 0 (gas-free) - Set gas limit to a sufficient value - Use either sequential or time-based nonces - Transactions must target specific precompile/router addresses ## Withdrawal Process 1. **Transaction Creation**: Create and sign withdrawal transaction on L2 2. **API Submission**: Call `/api/v1/wallet/withdraw` API 3. **Automatic Processing**: System automatically handles L2 confirmation, batch submission, and Kaia L1 withdrawal --- ## Contract Addresses # Contract Addresses ## Mainnet ### Chain Information | Item | Value | |------|-------| | L1 Chain ID | `8217` | | L2 Chain ID | `48217` | | L2 RPC Endpoint | https://l2-sequencer.alphasec.trade | ### L1 Contracts | Contract | Address | |----------|---------| | Inbox | `0xe4CD7C744C8016a8E42336c91366fB78a192F426` | | L1 Gateway Router | `0x35Be945fb1da550a76f1FAD6D3759437d71bA739` | | Sequencer Inbox | `0xe011c8DeaB65F2e299D5fbaa3808E953Ca93ee42` | | Bridge | `0xF31CE581A8440f0f4850eDEb343a28372572a088` | | Outbox | `0x2cBcf920bbC9241C7F0de33585b903eA57B3c215` | ### L2 Contracts | Contract | Address | |----------|---------| | MatchEngine | `0x00000000000000000000000000000000000000cc` | | ArbSys | `0x0000000000000000000000000000000000000064` | | L2 Gateway Router | `0x9e0648ec6Cd742ccb5EE9f9b3120eaEF014A684d` | | NodeInterface | `0x00000000000000000000000000000000000000C8` | | SequencerSystem | `0x00000000000000000000000000000000000a4b05` | --- ## Testnet ### Chain Information | Item | Value | |------|-------| | L1 Chain ID | `1001` | | L2 Chain ID | `41001` | | L2 RPC Endpoint | https://l2-sequencer-testnet.alphasec.trade | ### L1 Contracts | Contract | Address | |----------|---------| | Inbox | `0xF6B3519a72989BC5d6591b25F47656585a8deF60` | | L1 Gateway Router | `0x74F972A16a9B902f4B3A2b9546f5a77d98DA1070` | | Sequencer Inbox | `0xF26710e309529Ad5d14171f3a5902Cd36C7F6e11` | | Bridge | `0xF723f6AD011d2996255991e3E442311d22DD6D42` | | Outbox | `0xE7acB970E90E626CE37DBcDeDc9606A278832D2D` | ### L2 Contracts | Contract | Address | |----------|---------| | MatchEngine | `0x00000000000000000000000000000000000000cc` | | ArbSys | `0x0000000000000000000000000000000000000064` | | L2 Gateway Router | `0x097209B15FB6cEefba90EA10e4c1c5439E6bC1Ea` | | NodeInterface | `0x00000000000000000000000000000000000000C8` | | SequencerSystem | `0x00000000000000000000000000000000000a4b05` | --- ## Error Codes # Error Codes All API errors follow a consistent JSON structure. Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary based on the specific context. ## Error Response Format ```json { "code": -1100, "errMsg": "Invalid parameter" } ``` ## Error Code Categories ### 10xx - System and Server Issues #### -1000 INTERNAL_ERROR **Message:** `Internal server error` **Description:** An internal server error occurred while processing the request. The server encountered an unexpected condition that prevented it from fulfilling the request. --- #### -1001 NOT_FOUND **Message:** `Resource not found` **Description:** The requested resource was not found. The endpoint or resource you are trying to access does not exist. --- ### 11xx - Request Validation Issues #### -1100 INVALID_PARAMETER **Message:** `Invalid parameter` **Description:** Invalid data sent for a parameter. The parameter value does not meet the expected format or constraints. --- #### -1101 MISSING_PARAMETER **Message:** `Missing required parameter` **Description:** A mandatory parameter was not sent, was empty, or was null. Required parameters must be included in the request. --- #### -1102 INVALID_ADDRESS **Message:** `Invalid address format` **Description:** Invalid blockchain address format. The address provided does not conform to the expected address format. --- #### -1103 INVALID_TX **Messages:** - `Invalid transaction` - General transaction validation error - `Not a value transfer transaction` - Transaction is not of the expected type **Description:** Invalid transaction data or format. The transaction could not be processed due to validation failures. --- #### -1104 METHOD_NOT_ALLOWED **Message:** `Method not allowed` **Description:** The HTTP method is not supported for this endpoint. Use the correct HTTP method (GET, POST, PUT, DELETE) as specified in the API documentation. --- ### 12xx - Order, Cancel, and Modify Operations #### -1200 ORDER_REJECTED **Message:** `Order rejected` **Description:** The order was rejected and could not be processed. The order did not meet the requirements for placement. --- #### -1201 CANCEL_REJECTED **Message:** `Cancel rejected` **Description:** The cancel request was rejected and could not be processed. The order could not be cancelled. --- #### -1202 MODIFY_REJECTED **Message:** `Modify rejected` **Description:** The modify request was rejected and could not be processed. The order could not be modified. --- #### -1203 ORDER_LIMIT_EXCEEDED **Message:** `Maximum open orders limit exceeded` **Description:** The maximum number of open orders has been exceeded. Users are limited in the number of concurrent open orders they can have. --- #### -1204 SUBMIT_TX_RATE_LIMIT_EXCEEDED **Message:** `Transaction rate limit exceeded` **Description:** The transaction submission rate limit has been exceeded. Slow down the frequency of transaction submissions. --- ### 13xx - Market Related #### -1300 MARKET_NOT_AVAILABLE **Message:** `Market is not available for trading` **Description:** The requested market is not currently available for trading. The market may be temporarily halted, under maintenance, or in a non-trading state. --- #### -1301 MARKET_NOT_FOUND **Message:** `Market not found` **Description:** The requested market does not exist. Verify the market ID is correct. --- ### 20xx - Authentication and Authorization Issues #### -2000 UNAUTHORIZED **Message:** `Unauthorized` **Description:** Authentication is required to access this endpoint. The request lacks valid authentication credentials. --- #### -2001 NOT_AUTHORIZED **Message:** `Not authorized` **Description:** You do not have permission to access this resource. Valid authentication provided, but insufficient privileges. --- ### 30xx - Business Logic #### -3000 BUSINESS_RULE **Message:** `Business rule error` **Description:** A valid request that failed due to business logic rules. The request is technically correct but violates one or more business constraints. --- ## Markets # Markets ## General Information - All endpoints return data in JSON format - All timestamps are in milliseconds (Unix epoch time) - No authentication required for market data endpoints - All price and quantity values are returned as strings to preserve precision ## Get Server Time ### GET /time Get the current server time in milliseconds. **Parameters:** None **Response:** ```json { "code": 200, "errMsg": "OK", "result": { "serverTime": 1758005316000 } } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | serverTime | LONG | Current server time in milliseconds (Unix epoch time) | **Use Cases:** - Synchronize client time with server time - Calculate time differences for request timestamps - Verify network latency ## Get All Markets ### GET /api/v1/market Get information about all available trading markets. **Parameters:** None **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "marketId": "1_2", "description": "Kaia / Tether", "baseTokenId": "1", "quoteTokenId": "2", "exchange": "Alphasec Testnet", "ticker": "KAIA/USDT", "type": "spot", "minmov": 1, "pricescale": 100000, "session": "24x7", "hasIntraday": true, "hasEmptyBars": true, "takerFee": "0.0003", "makerFee": "0.0001", "listed": true, "logoUrls": "", "isDefaultMakerFee": false, "isDefaultTakerFee": false, "createdAt": "2025-09-17T01:26:59Z", "updatedAt": "2025-09-17T01:26:59Z" } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | marketId | STRING | Market identifier (format: `{baseTokenId}_{quoteTokenId}`) | | description | STRING | Market description | | baseTokenId | STRING | ID of the base token | | quoteTokenId | STRING | ID of the quote token | | exchange | STRING | Exchange name | | ticker | STRING | Market ticker (e.g., "KAIA/USDT") | | type | STRING | Market type (e.g., "spot") | | minmov | INTEGER | Minimum price movement in tradingview graph | | pricescale | INTEGER | Price scale for display in tradingview graph | | session | STRING | Trading session (e.g., "24x7") | | hasIntraday | BOOLEAN | Whether market has intraday data in tradingview graph | | hasEmptyBars | BOOLEAN | Whether market has empty bars in tradingview graph | | takerFee | STRING | Fee rate for taker orders (market orders) | | makerFee | STRING | Fee rate for maker orders (limit orders) | | listed | BOOLEAN | Whether the market is currently active | | logoUrls | STRING | Comma-separated logo URLs | | isDefaultMakerFee | BOOLEAN | Whether using default maker fee | | isDefaultTakerFee | BOOLEAN | Whether using default taker fee | | createdAt | STRING | Creation timestamp (ISO format) | | updatedAt | STRING | Last update timestamp (ISO format) | ## Get 24hr Ticker Price Change Statistics ### GET /api/v1/market/ticker Get 24 hour rolling window price change statistics. Careful when accessing without marketId. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | marketId | STRING | NO | Market identifier in format `{baseTokenId}_{quoteTokenId}` (e.g., "1_2"). If not provided, returns tickers for all markets | **Response (Single Market):** ```json { "code": 200, "errMsg": "OK", "result": [ { "marketId": "1_2", "baseTokenId": "1", "quoteTokenId": "2", "price": "2.3", "open24h": "2.1", "high24h": "2.5", "low24h": "2.0", "volume24h": "150000.5", "quoteVolume24h": "345001.15" } ] } ``` **Response (All Markets):** ```json { "code": 200, "errMsg": "OK", "result": [ { "marketId": "1_2", "baseTokenId": "1", "quoteTokenId": "2", "price": "2.3", "open24h": "2.1", "high24h": "2.5", "low24h": "2.0", "volume24h": "150000.5", "quoteVolume24h": "345001.15" }, { "marketId": "3_2", "baseTokenId": "3", "quoteTokenId": "2", "price": "3500.0", "open24h": "3400.0", "high24h": "3600.0", "low24h": "3350.0", "volume24h": "1200.5", "quoteVolume24h": "4200000.0" } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | marketId | STRING | Market identifier | | baseTokenId | STRING | Base token identifier | | quoteTokenId | STRING | Quote token identifier | | price | STRING | Current/last traded price | | open24h | STRING | Opening price 24 hours ago | | high24h | STRING | Highest price in last 24 hours | | low24h | STRING | Lowest price in last 24 hours | | volume24h | STRING | Base token volume traded in last 24 hours | | quoteVolume24h | STRING | Quote token volume traded in last 24 hours | ## Get All Listed Tokens ### GET /api/v1/market/tokens Get information about all tokens available for trading. **Parameters:** None **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "tokenId": "1", "l1Address": "0x0000000000000000000000000000000000000000", "l1Symbol": "KAIA", "l1Name": "Kaia Token", "l1Decimal": 18, "l2Symbol": "KAIA", "l2Name": "Kaia Token", "image": "https://storage.googleapis.com/dex-images-dev/tokens/1/image_1758080220.svg" }, { "tokenId": "2", "l1Address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "l1Symbol": "USDT", "l1Name": "Tether USD", "l1Decimal": 6, "l2Symbol": "USDT", "l2Name": "Tether USD", "image": "https://storage.googleapis.com/dex-images-dev/tokens/2/image_1758080221.svg" } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | tokenId | STRING | Unique identifier for the token | | l1Address | STRING | Token contract address on Layer 1 (Ethereum) | | l1Symbol | STRING | Token symbol on Layer 1 | | l1Name | STRING | Full token name on Layer 1 | | l1Decimal | INT | Number of decimals for the token on Layer 1 | | l2Symbol | STRING | Token symbol on Layer 2 (Kaia) | | l2Name | STRING | Full token name on Layer 2 | | image | STRING | URL to the token's logo image | ## Get Recent Trades ### GET /api/v1/market/trades Get recent trades for a specific market. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | marketId | STRING | YES | Market identifier in format `{baseTokenId}_{quoteTokenId}` (e.g., "1_2") | | limit | INT | NO | Number of trades to return. Default: 20, Max: 1000 | **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "tradeId": "405100010000", "marketId": "1_2", "price": "2.3", "quantity": "0.7", "buyOrderId": "0xdb9d5d086b4755fb5e49819fef783f80fb98f893", "sellOrderId": "0x766be3ed6e3296708885405c7766c6cc880cfafa", "createdAt": 1758005316000, "isBuyerMaker": false }, { "tradeId": "405100010001", "marketId": "1_2", "price": "2.31", "quantity": "1.5", "buyOrderId": "0xab9d5d086b4755fb5e49819fef783f80fb98f894", "sellOrderId": "0x866be3ed6e3296708885405c7766c6cc880cfafb", "createdAt": 1758005320000, "isBuyerMaker": true } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | tradeId | STRING | Unique trade identifier | | marketId | STRING | Market identifier (format: `{baseTokenId}_{quoteTokenId}`) | | price | STRING | Execution price in quote token | | quantity | STRING | Trade quantity in base token | | buyOrderId | STRING | Buy order transaction hash | | sellOrderId | STRING | Sell order transaction hash | | createdAt | LONG | Trade execution timestamp in milliseconds (Unix epoch) | | isBuyerMaker | BOOLEAN | True if buyer was the maker, false if taker | ## Get Order Book ### GET /api/v1/market/depth Get the order book depth for a specific market. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | marketId | STRING | YES | Market identifier in format `{baseTokenId}_{quoteTokenId}` (e.g., "1_2") | | limit | INT | NO | Depth limit per side. Default: 1000, Max: 5000 | **Response:** ```json { "code": 200, "errMsg": "OK", "result": { "bids": [ { "price": "2.3", "quantity": "10.5" }, { "price": "2.29", "quantity": "25.0" }, { "price": "2.28", "quantity": "50.0" } ], "asks": [ { "price": "2.31", "quantity": "15.0" }, { "price": "2.32", "quantity": "30.0" }, { "price": "2.33", "quantity": "45.5" } ], "updatedAt": 1758096768006, "lastUpdatedId": 42921 } } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | bids | ARRAY | Buy orders sorted by price (highest first) | | asks | ARRAY | Sell orders sorted by price (lowest first) | | price | STRING | Price level in quote token | | quantity | STRING | Total quantity available at this price level | | updatedAt | LONG | Last update timestamp in milliseconds (Unix epoch) | | lastUpdatedId | LONG | Sequential update ID for tracking orderbook changes | ## Get Candlestick Data ### GET /market/candles Get OHLCV (Open, High, Low, Close, Volume) candlestick data for a specific market. Used for charting and technical analysis. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | marketId | STRING | YES | Market identifier in format `{baseTokenId}_{quoteTokenId}` (e.g., "1_2") | | resolution | STRING | YES | Candle interval/timeframe (see Resolution Values below) | | from | LONG | NO | Start timestamp in Unix seconds. Default: 0 | | to | LONG | NO | End timestamp in Unix seconds. Default: current time | **Resolution Values:** | Value | Description | |-------|-------------| | 1 | 1 minute | | 5 | 5 minutes | | 15 | 15 minutes | | 30 | 30 minutes | | 60 | 1 hour | | 120 | 2 hours | | 240 | 4 hours | | 480 | 8 hours | | 720 | 12 hours | | 1D | 1 day | | 3D | 3 days | | 1W | 1 week | | 1M | 1 month (30 days) | **Limits:** - Maximum 1000 data points per request - If the time range exceeds 1000 candles, an error will be returned **Response:** ```json { "success": true, "result": [ { "marketId": "1_2", "resolution": "60", "timestamp": 1704067200, "open": 2.25, "high": 2.35, "low": 2.20, "close": 2.30, "volume": 15000.5, "quoteVolume": 34125.15, "tradeCount": 125 }, { "marketId": "1_2", "resolution": "60", "timestamp": 1704070800, "open": 2.30, "high": 2.40, "low": 2.28, "close": 2.38, "volume": 18500.0, "quoteVolume": 43660.00, "tradeCount": 156 } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | marketId | STRING | Market identifier | | resolution | STRING | Candle resolution/interval | | timestamp | LONG | Candle open timestamp in Unix seconds | | open | FLOAT | Opening price | | high | FLOAT | Highest price during the interval | | low | FLOAT | Lowest price during the interval | | close | FLOAT | Closing price | | volume | FLOAT | Base token volume traded during the interval | | quoteVolume | FLOAT | Quote token volume traded during the interval | | tradeCount | LONG | Number of trades during the interval | **Error Response:** ```json { "success": false, "errorCode": "INVALID_PARAM", "message": "time range exceeds maximum of 1000 data points" } ``` **Example Request:** ``` GET /market/candles?marketId=1_2&resolution=60&from=1704067200&to=1704153600 ``` ## Rate Limits - TBD ## Notes - Market IDs follow the format `{baseTokenId}_{quoteTokenId}` (e.g., "1_2" where token 1 is the base and token 2 is the quote) - All prices and quantities are returned as strings to preserve decimal precision - Timestamps are always in milliseconds (Unix epoch time) - The ticker endpoint returns a 24-hour rolling window of statistics - Order book depth is aggregated at each price level - Recent trades are returned in descending order (newest first) --- ## Orders # Orders ## General Information - All endpoints return data in JSON format - All timestamps are in milliseconds (Unix epoch time) - Order endpoints use address-based authentication (no JWT required) - Order placement, modification, and cancellation require signed transactions ## Enum Values ### Order Side | Value | Description | |-------|-------------| | BUY | Buy order (bid) | | SELL | Sell order (ask) | ### Order Type | Value | Description | |-------|-------------| | LIMIT | Limit order at specified price | | MARKET | Market order at best available price | | TAKE_PROFIT_LIMIT | Take profit limit order - executes as limit order when price reaches profit target | | TAKE_PROFIT_MARKET | Take profit market order - executes as market order when price reaches profit target | | STOP_LOSS_LIMIT | Stop loss limit order - executes as limit order when price hits loss threshold | | STOP_LOSS_MARKET | Stop loss market order - executes as market order when price hits loss threshold | ### Order Status | Value | Description | |-------|-------------| | NEW | Order is active and waiting to be filled | | PARTIALLY_FILLED | Order has been partially executed | | FILLED | Order has been completely filled | | CANCELED | Order has been canceled by user | | REJECTED | Order was rejected by the system | | EXPIRED | Order has expired | | PENDING_NEW | Order is pending placement | | PENDING_CANCEL | Order cancellation is pending | ### Contingency Type | Value | Description | |-------|-------------| | NONE | No contingency (regular order) | | OCO | One Cancels Other - when one order fills, the other is automatically canceled | | OTO | One Triggers Other - when primary order fills, secondary order is automatically placed | ### OTO Leg Type | Value | Description | |-------|-------------| | NONE | Not part of an OTO order | | WORKING_LEG | The primary order that must fill first | | TP_LEG | Take Profit leg - triggered when price reaches profit target | | SL_LEG | Stop Loss leg - triggered when price hits loss limit | | OCO_LEG | Part of an OCO (One Cancels Other) pair | ### Order Mode | Value | Description | Filled Field | |-------|-------------|--------------| | 0 | Base token quantity mode - order quantity specified in base token | origQty | | 1 | Quote token quantity mode - order quantity specified in quote token (market orders only) | origQuoteOrderQty | **Note**: When `orderMode=0`, the order quantity is specified in the base token (e.g., BTC in BTC/USDT), and the `origQty` field will be filled while `origQuoteOrderQty` will be "0". When `orderMode=1`, the order quantity is specified in the quote token (e.g., USDT in BTC/USDT), and the `origQuoteOrderQty` field will be filled while `origQty` will be "0". **Important**: Quote mode (`orderMode=1`) can only be used for market orders that execute at the best available price. It cannot be used for limit orders. This is particularly useful for market buy orders where you want to specify the amount in quote token (e.g., "buy with 1000 USDT"). ## Query Open Orders ### GET /api/v1/order/open Get all open orders (NEW or PARTIALLY_FILLED status) for a wallet address. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | address | STRING | YES | Wallet address (0x...) | | marketId | STRING | NO | Market identifier (e.g., "1_2"). If not provided, returns open orders for all markets | | from | LONG | NO | Start timestamp in milliseconds. Default: 0 | | to | LONG | NO | End timestamp in milliseconds. Default: current time | | limit | INT | NO | Maximum number of results. Default: 100, Min: 1 | **Time Range Constraints:** - Maximum time range: 90 days - Default time range: 30 days (when both from and to are 0 or not provided) - Historical data limit: Up to 730 days (2 years) in the past - Future timestamps are not allowed **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "id": 1011335, "orderId": "0x57edb3d6e2eff8e6cdf45ee171609975a5ad0318a8c8d896dcd93eef18584b52", "accountAddress": "0x1234567890123456789012345678901234567890", "marketId": "1_2", "side": "BUY", "orderType": "LIMIT", "orderMode": 0, "price": "2.3", "origQty": "10.5", "origQuoteOrderQty": "0", "isTrigger": false, "isTriggered": false, "triggerPrice": "0", "status": "PARTIALLY_FILLED", "contingencyType": "NONE", "otoLegType": "NONE", "txHash": "0x57edb3d6e2eff8e6cdf45ee171609975a5ad0318a8c8d896dcd93eef18584b52", "createdAt": 1758005316000, "updatedAt": 1758005416000, "executedQty": "5.2", "executedQuoteQty": "11.96" } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | id | INTEGER | Order database ID | | orderId | STRING | Unique order identifier (transaction hash format) | | accountAddress | STRING | Wallet address of order creator | | marketId | STRING | Market identifier (baseTokenId_quoteTokenId) | | side | ENUM | Order side - see [Order Side](#order-side) enum values | | orderType | ENUM | Order type - see [Order Type](#order-type) enum values | | orderMode | INTEGER | Order mode: 0 = base token quantity mode (uses origQty), 1 = quote token quantity mode (uses origQuoteOrderQty, market orders only) | | price | STRING | Limit price in quote token (0 for market orders) | | origQty | STRING | Original order quantity in base token (filled when orderMode=0) | | origQuoteOrderQty | STRING | Original order quantity in quote token (filled when orderMode=1) | | isTrigger | BOOLEAN | Whether this is a trigger order (stop-loss or take-profit) | | isTriggered | BOOLEAN | Whether a trigger order has been activated | | triggerPrice | STRING | Price at which trigger order activates (0 for non-trigger orders) | | status | ENUM | Current order status - see [Order Status](#order-status) enum values | | contingencyType | ENUM | Order contingency - see [Contingency Type](#contingency-type) enum values | | otoLegType | ENUM | OTO order leg type - see [OTO Leg Type](#oto-leg-type) enum values | | txHash | STRING | Transaction hash on blockchain | | createdAt | LONG | Order creation timestamp in milliseconds (Unix epoch) | | updatedAt | LONG | Last update timestamp in milliseconds (Unix epoch) | | executedQty | STRING | Total executed quantity in base token | | executedQuoteQty | STRING | Total executed value in quote token | ## Query Completed Order History ### GET /api/v1/order Get historical orders (filled, canceled, rejected) for a wallet address. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | address | STRING | YES | Wallet address (0x...) | | marketId | STRING | NO | Filter by market ID | | from | LONG | NO | Start timestamp in milliseconds. Default: 0 | | to | LONG | NO | End timestamp in milliseconds. Default: current time | | limit | INT | NO | Maximum number of results. Default: 100, Min: 1, Max: 500 | **Time Range Constraints:** - Maximum time range: 90 days - Default time range: 30 days (when both from and to are 0 or not provided) - Historical data limit: Up to 730 days (2 years) in the past - Future timestamps are not allowed **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "orderId": "0x4bed76ae0c75b1d1d0b291873ad7fb58b0986955ae0d49ca642a0f8c48efbae5", "accountAddress": "0x1234567890123456789012345678901234567890", "marketId": "1_2", "side": "SELL", "orderType": "LIMIT", "price": "2.5", "origQty": "8.0", "origQuoteOrderQty": "20.0", "status": "FILLED", "txHash": "0x4bed76ae0c75b1d1d0b291873ad7fb58b0986955ae0d49ca642a0f8c48efbae5", "createdAt": 1758004316000, "updatedAt": 1758005316000, "executedQty": "8.0", "executedQuoteQty": "20.0" } ] } ``` ## Query Order by ID ### GET /api/v1/order/\{orderId\} Get details of a specific order by order ID. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | orderId | STRING | YES | Order ID (in path) | **Response:** ```json { "code": 200, "errMsg": "OK", "result": { "orderId": "0x4bed76ae0c75b1d1d0b291873ad7fb58b0986955ae0d49ca642a0f8c48efbae3", "accountAddress": "0x1234567890123456789012345678901234567890", "marketId": "1_2", "side": "BUY", "orderType": "LIMIT", "price": "2.3", "origQty": "10.5", "origQuoteOrderQty": "24.15", "status": "NEW", "txHash": "0x4bed76ae0c75b1d1d0b291873ad7fb58b0986955ae0d49ca642a0f8c48efbae3", "createdAt": 1758005316000, "updatedAt": 1758005316000, "executedQty": "0", "executedQuoteQty": "0" } } ``` **Response Fields:** Same as [Query Open Orders](#query-open-orders) response fields, but returns a single order object instead of an array. ## POST Endpoints for Orders All order POST operations (place, cancel, modify) require signed transactions sent to the fixed contract address. For detailed transaction structure and examples, see [Transaction Structure Documentation](./sign.md): - Place Order: [Section 2](./sign.md#2-place-order-dexcommandorder---0x21) - Place TPSL Order: [Section 2-1](./sign.md#2-1-place-tpsl-order-dexcommandorder---0x21) - Cancel Order: [Section 3](./sign.md#3-cancel-order-dexcommandcancel---0x22) - Cancel All Orders: [Section 4](./sign.md#4-cancel-all-orders-dexcommandcancelall---0x23) - Modify Order: [Section 5](./sign.md#5-modify-order-dexcommandmodify---0x24) - Stop Order: [Section 6](./sign.md#6-stop-order-dexcommandstoporder---0x25) ## Query Trade History ### GET /api/v1/order/trade Get executed trades for a wallet address. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | address | STRING | YES | Wallet address (0x...) | | marketId | STRING | NO | Filter by market ID | | from | LONG | NO | Start timestamp in milliseconds. Default: 0 | | to | LONG | NO | End timestamp in milliseconds. Default: current time | | limit | INT | NO | Maximum number of results. Default: 100, Min: 1, Max: 500 | **Time Range Constraints:** - Maximum time range: 90 days - Default time range: 30 days (when both from and to are 0 or not provided) - Historical data limit: Up to 730 days (2 years) in the past - Future timestamps are not allowed **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "id": 971249, "orderId": "0x20c859e2a894d76d1e022e24b608b59c567e74c89baa3c71abe2c05e65f3b0aa", "accountAddress": "0x1234567890123456789012345678901234567890", "marketId": "3_2", "side": "BUY", "orderType": "LIMIT", "origPrice": "7", "origQty": "2", "price": "7", "quantity": "1", "feeTokenId": "3", "fee": "0.0001", "isMaker": true, "tradeId": "23040400030001", "createdAt": 1758684608000 } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | id | INTEGER | Trade database ID | | tradeId | STRING | Unique trade identifier | | orderId | STRING | Order that generated this trade | | accountAddress | STRING | Wallet address of the trader | | marketId | STRING | Market identifier (baseTokenId_quoteTokenId) | | side | STRING | Trade side ("BUY" or "SELL") | | orderType | STRING | Order type (e.g., "LIMIT", "MARKET") | | origPrice | STRING | Original order price | | origQty | STRING | Original order quantity | | price | STRING | Execution price in quote token | | quantity | STRING | Executed quantity in base token | | fee | STRING | Trading fee paid for this execution | | feeTokenId | STRING | Token ID in which fee was paid | | isMaker | BOOLEAN | True if this was a maker trade (provided liquidity), false if taker | | createdAt | LONG | Trade execution timestamp in milliseconds (Unix epoch) | ## Notes - Order IDs are unique across the system - Market orders cannot have a limit price - Trigger orders activate when market price crosses the trigger price - OCO (One Cancels Other) orders automatically cancel the paired order when one fills - OTO (One Triggers Other) orders automatically place a secondary order when the primary fills - All prices and quantities are strings to preserve precision - Results are sorted by ID in descending order (newest first) --- ## Sign # Sign ## Overview All DEX operations use standard Ethereum transactions with a specific structure: 1. **Standard Ethereum transaction** sent to a fixed contract address 2. **To Address (FIXED)**: `0x00000000000000000000000000000000000000cc` 3. **Input Data Format**: `[Command Byte] + [JSON Data]` **Important Notes**: 1. **Strict Schema**: Only predefined fields are allowed in JSON data. Unknown fields will be rejected. 2. **Order ID**: The order ID is the transaction hash (txHash) of the create order transaction 3. **Price and Quantity**: All values in JSON contexts are already decimal-applied: - Price "2.3" means 2.3 USDT - Quantity "10.5" means 10.5 tokens - No conversion to smallest units (wei) is needed **Transaction Structure:** ```javascript { from: "0x...", // Your wallet address to: "0x00000000000000000000000000000000000000cc", // FIXED contract address data: "[CommandByte][JSON(Context)]", // Command byte + JSON payload value: "0x0", // Always 0 for DEX operations gasLimit: "0x30000", // Arbitrary large value (gas-free on L2) gasPrice: "0x0", // Set to 0 (gas-free on L2) nonce: "...", // Your account nonce (supports timeNonce: Unix timestamp in ms) chainId: "..." // Kaia chain ID } ``` ## Command Bytes | Command | Byte Value | Description | |---------|------------|-------------| | DexCommandSession | 0x01 | Session wallet operations | | DexCommandTransfer | 0x02 | Kaia transfers | | DexCommandTokenTransfer | 0x11 | Token-specific transfers | | DexCommandOrder | 0x21 | Place new order | | DexCommandCancel | 0x22 | Cancel specific order | | DexCommandCancelAll | 0x23 | Cancel all orders | | DexCommandModify | 0x24 | Modify existing order | | DexCommandStopOrder | 0x25 | Place stop order | ## Enums for Order Context ### Side | Value | Description | |-------|-------------| | 0 | Buy order | | 1 | Sell order | ### Order Type | Value | Description | |-------|-------------| | 0 | Limit order | | 1 | Market order | ### Order Mode | Value | Description | |-------|-------------| | 0 | Base mode (default) - quantity in base token | | 1 | Quote mode - quantity in quote token (market orders only) | **Note**: Quote mode (`orderMode=1`) can only be used for market orders that execute at the best available price. It cannot be used for limit orders. This is particularly useful for market buy orders where you want to specify the amount in quote token (e.g., "buy with 1000 USDT"). ## Tick and Lot Size Alpha Sec. enforces standardized price precision and minimum order sizes across all markets to ensure consistent execution, protect against dust orders, and maintain engine-level efficiency. ### Price Precision Prices support up to **5 significant digits** and up to **8 decimal places**. Depending on the price range, the allowed decimal places and the minimum order size change dynamically. ### Decimal Rules by Price Range The following table defines the allowed decimal precision and the minimum order size for each price tier. Lower priced assets allow deeper decimal precision but enforce larger minimum sizes to prevent excessively small orders. | Price Range | Allowed Decimals | Minimum Size | |-------------|------------------|--------------| | 10,000 or higher | 0 | 0.00001 | | 1,000 or higher | 1 | 0.0001 | | 100 or higher | 2 | 0.001 | | 10 or higher | 3 | 0.01 | | 1 or higher | 4 | 0.1 | | 0.1 or higher | 5 | 1 | | 0.01 or higher | 6 | 1 | | 0.001 or higher | 7 | 1 | | 0.0001 or higher | 8 | 1 | | 0.00001 or higher | 8 | 1 | | 0.000001 or higher | 8 | 1 | | 0.0000001 or higher | 8 | 1 | | 0.00000001 or higher | 8 | 1 | ### Valid Price and Size Conditions An order is valid only if it satisfies the following conditions: **Price Rules:** 1. The price must be within 5 significant digits - Valid: `12345`, `0.0012345` - Invalid: `12345.6`, `0.00123456` 2. The price cannot exceed the allowed decimal places for its price tier - Example: If the price is `120`, allowed decimals = 2 - Valid: `120.34` - Invalid: `120.345` **Size Rules:** - The size must be equal to or greater than the minimum size defined for the current price tier - Example: At `50` dollars, minimum size is `0.01` - Valid: `0.01` - Invalid: `0.009` **Note**: Orders that do not meet these requirements will be rejected by the matching engine. ## 1. Session Wallet Operations (DexCommandSession - 0x01) ### POST /api/v1/wallet/session Manage session wallets for delegated trading. Session wallets allow trading without exposing the main wallet's private key. **Transaction Data Structure:** ```javascript data = [0x01][JSON(SessionContext)] ``` **SessionContext Structure:** ```json { "type": 1, // 1: create, 2: update, 3: delete "publickey": "0xSessionWalletAddress", "expiresAt": 1758005316, // Unix timestamp in seconds when session expires "nonce": 0, // Session nonce for replay protection "l1owner": "0x1234567890123456789012345678901234567890", "l1signature": "0x..." // EIP-712 signature } ``` **SessionContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | type | INT | YES | Session command: 1 (create), 2 (update), 3 (delete) | | publickey | STRING | YES | Session wallet address | | expiresAt | LONG | YES | Unix timestamp in seconds when session expires | | nonce | LONG | YES | Nonce for replay protection | | l1owner | STRING | YES | Owner wallet address (master wallet address) | | l1signature | STRING | YES | EIP-712 signature from owner wallet | **Session Command Types:** | Type | Value | Description | |------|-------|-------------| | SessionCreate | 1 | Create new session wallet | | SessionUpdate | 2 | Update existing session | | SessionDelete | 3 | Delete session wallet | ### EIP-712 Signature Structure Session operations require an EIP-712 typed data signature: ```javascript const typedData = { types: { EIP712Domain: [ { name: "name", type: "string" }, { name: "version", type: "string" }, { name: "chainId", type: "uint256" }, { name: "verifyingContract", type: "address" } ], RegisterSessionWallet: [ { name: "sessionWallet", type: "address" }, { name: "expiry", type: "uint64" }, { name: "nonce", type: "uint64" } ] }, primaryType: "RegisterSessionWallet", domain: { name: "DEXSignTransaction", version: "1", chainId: 8217, // 8217 for Mainnet L1 Chain ID verifyingContract: "0x0000000000000000000000000000000000000000" }, message: { sessionWallet: "0xSessionWalletAddress", expiry: "1758005316", // Unix timestamp in seconds as string nonce: "0" // Nonce as string } }; // Sign the typed data with the L1 owner's private key const signature = await signer._signTypedData( typedData.domain, { RegisterSessionWallet: typedData.types.RegisterSessionWallet }, typedData.message ); // IMPORTANT: When building the transaction, use the same nonce const nonce = "0"; // Or Date.now().toString() for timeNonce const tx = { from: l1owner, to: "0x00000000000000000000000000000000000000cc", data: commandByte + JSON.stringify({ type: 1, // SessionCreate publickey: sessionWallet, expiresAt: 1758005316, nonce: parseInt(nonce), // MUST match the nonce in EIP-712 message l1owner: l1owner, l1signature: signature }), nonce: nonce, // Transaction nonce MUST match the nonce in SessionContext gasPrice: '0x0', gasLimit: '0x30000' }; ``` **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` **Notes:** - Session wallets expire at the specified Unix timestamp (in milliseconds) - The nonce prevents replay attacks - **Important**: The nonce value in the EIP-712 message MUST match the nonce value in the actual transaction - **Important**: The `chainId` in the EIP-712 domain must be the **L1 chain ID** (e.g., 8217 for Kaia Mainnet), not the L2 chain ID - L1 signature must be an EIP-712 signature from the owner wallet - All session operations target the same fixed contract address: `0x00000000000000000000000000000000000000cc` ## 2. Place Order (DexCommandOrder - 0x21) ### POST /api/v1/order **Transaction Data Structure:** ```javascript data = [0x21][JSON(OrderContext)] ``` **OrderContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "baseToken": "1", "quoteToken": "2", "side": 0, // 0: buy, 1: sell "price": "2.3", // Price "quantity": "10.5", // Quantity "orderType": 0, // 0: limit, 1: market "orderMode": 0 // 0: base mode, 1: quote mode } ``` **OrderContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address placing the order (master wallet address) | | baseToken | STRING | YES | Base token ID (e.g., "1" for KAIA) | | quoteToken | STRING | YES | Quote token ID (e.g., "2" for USDT) | | side | INT | YES | 0 for buy, 1 for sell | | price | STRING | YES | Limit price (set to "0" for market orders) | | quantity | STRING | YES | Order quantity | | orderType | INT | YES | 0 for limit, 1 for market | | orderMode | INT | YES | 0 for base mode, 1 for quote mode (quote mode only available for market orders) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## 2-1. Place TPSL Order (DexCommandOrder - 0x21) ### POST /api/v1/order (with Take Profit/Stop Loss) **Transaction Data Structure:** ```javascript data = [0x21][JSON(OrderContextWithTPSL)] ``` **OrderContextWithTPSL Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "baseToken": "1", "quoteToken": "2", "side": 0, // 0: buy, 1: sell "price": "2.3", // Main order price "quantity": "10.5", // Quantity "orderType": 0, // 0: limit, 1: market "orderMode": 0, // 0: base mode, 1: quote mode "tpsl": { // Take Profit/Stop Loss configuration "tpLimit": "2.5", // Take profit limit price "slTrigger": "2.1", // Stop loss trigger price "slLimit": "2.09" // Optional: Stop loss limit price (if not set, SL is market) } } ``` **OrderContextWithTPSL Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address placing the order (master wallet address) | | baseToken | STRING | YES | Base token ID | | quoteToken | STRING | YES | Quote token ID | | side | INT | YES | 0 for buy, 1 for sell | | price | STRING | YES | Main order limit price | | quantity | STRING | YES | Order quantity | | orderType | INT | YES | 0 for limit, 1 for market | | orderMode | INT | YES | 0 for base mode, 1 for quote mode (quote mode only available for market orders) | | tpsl | OBJECT | YES | Take profit and stop loss configuration | | tpsl.tpLimit | STRING | YES | Take profit limit price | | tpsl.slTrigger | STRING | YES | Stop loss trigger price | | tpsl.slLimit | STRING | NO | Stop loss limit price (omit for market SL) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` **TPSL Order ID Generation**: When placing a TPSL order, both TP and SL must be set together. The order IDs are systematically generated from the original order's transaction hash: ``` // Generated based on original order ID (txHash) TPIncrement = 1 // TP order: txHash[31] + 1 SLIncrement = 2 // SL order: txHash[31] + 2 // Note: Only the last byte is rotated // Example: // Original: 0x011...00ff → TP ID: 0x011...0000, SL ID: 0x011...0001 ``` - Stop orders use the original txHash as-is (no increment) - Both TP and SL orders must be configured when using the `tpsl` field ## 3. Cancel Order (DexCommandCancel - 0x22) ### POST /api/v1/order/cancel **Transaction Data Structure:** ```javascript data = [0x22][JSON(CancelContext)] ``` **CancelContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "orderId": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` **CancelContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address that owns the order (master wallet address) | | orderId | STRING | YES | Order ID to cancel (transaction hash) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## 4. Cancel All Orders (DexCommandCancelAll - 0x23) ### POST /api/v1/order/cancel/all **Transaction Data Structure:** ```javascript data = [0x23][JSON(CancelAllContext)] ``` **CancelAllContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890" } ``` **CancelAllContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address whose orders to cancel (master wallet address) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## 5. Modify Order (DexCommandModify - 0x24) ### POST /api/v1/order/modify **Important**: Modify operates as a "cancel and replace" mechanism. The original order is canceled and a new order is created with the modified parameters. The new order ID will be the transaction hash of the modify transaction. **Transaction Data Structure:** ```javascript data = [0x24][JSON(ModifyContext)] ``` **ModifyContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "orderId": "0x4bed76ae0c75b1d1d0b291873ad7fb58b0986955ae0d49ca642a0f8c48efbae5", "newPrice": "2.35", // New price (null to keep current) "newQty": "20.0" // New quantity (null to keep current) } ``` **ModifyContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address that owns the order (master wallet address) | | orderId | STRING | YES | Order ID to modify (original transaction hash) | | newPrice | STRING | NO | New limit price (null to keep current) | | newQty | STRING | NO | New quantity (null to keep current) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## 6. Stop Order (DexCommandStopOrder - 0x25) ### POST /api/v1/order/trigger **Transaction Data Structure:** ```javascript data = [0x25][JSON(StopOrderContext)] ``` **StopOrderContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "baseToken": "1", "quoteToken": "2", "stopPrice": "2.1", // Trigger price "price": "2.09", // Limit price (0 for market order) "quantity": "10.0", // Quantity "side": 0, // 0: buy, 1: sell "orderType": 0, // 0: limit, 1: market "orderMode": 0 // 0: base mode, 1: quote mode } ``` **StopOrderContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address placing the order (master wallet address) | | baseToken | STRING | YES | Base token ID | | quoteToken | STRING | YES | Quote token ID | | stopPrice | STRING | YES | Price at which the stop order triggers | | price | STRING | YES | Limit price after trigger ("0" for market) | | quantity | STRING | YES | Order quantity | | side | INT | YES | 0 for buy, 1 for sell | | orderType | INT | YES | 0 for limit, 1 for market | | orderMode | INT | YES | 0 for base mode, 1 for quote mode (quote mode only available for market orders) | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## 7. Transfer Assets (DexCommandTokenTransfer - 0x11) ### POST /api/v1/wallet/transfer **Transaction Data Structure:** ```javascript data = [0x11][JSON(TransferContext)] ``` **TransferContext Structure:** ```json { "l1owner": "0x1234567890123456789012345678901234567890", "to": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "token": "2", "value": "1000.0", // Amount } ``` **TransferContext Fields:** | Field | Type | Mandatory | Description | |-------|------|-----------|-------------| | l1owner | STRING | YES | Wallet address initiating the transfer (master wallet address) | | to | STRING | YES | Destination wallet address | | token | STRING | YES | Token ID to transfer | | value | STRING | YES | Amount to transfer | **Request Body:** ```json { "tx": "0x02f8730183...{full signed transaction hex}" } ``` **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` ## Building and Signing Transactions ### Fixed Contract Address **ALL transactions MUST be sent to:** ``` 0x00000000000000000000000000000000000000cc ``` ### Input Data Construction The transaction's `data` field consists of: 1. **Command Byte** (1 byte): Identifies the operation type 2. **JSON Data** (remaining bytes): UTF-8 encoded JSON string with operation parameters ### L2 Gas-Free Transactions **Important**: The Kaia L2 DEX supports gas-free transactions, meaning: - **Gas Price**: Set to `0` (zero) for all transactions - **Gas Limit**: Use a sufficiently large arbitrary value (e.g., `0x30000` or `196608`) - **Value**: Always `0x0` for DEX operations - Users don't need to hold native tokens for gas fees ### Example: Building Order Transaction ```javascript // 1. Create OrderContext const orderContext = { l1owner: walletAddress, baseToken: "1", quoteToken: "2", side: 0, // buy price: "2.3", quantity: "10.0", orderType: 0, // limit orderMode: 0 // base mode }; // 2. Build transaction data const commandByte = 0x21; // DexCommandOrder const jsonData = JSON.stringify(orderContext); const data = Buffer.concat([ Buffer.from([commandByte]), Buffer.from(jsonData) ]); // 3. Sign transaction (with gas-free parameters) const tx = { from: walletAddress, to: MATCH_ENGINE_ADDRESS, data: '0x' + data.toString('hex'), value: '0x0', // Always 0 for DEX operations gasLimit: '0x30000', // Arbitrary large value gasPrice: '0x0', // Gas-free: set to 0 nonce: Date.now() // Can use timeNonce (Unix timestamp in ms) or sequential nonce }; const signedTx = await web3.eth.accounts.signTransaction(tx, privateKey); // 4. Send to API const response = await fetch('/api/v1/order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ tx: signedTx.rawTransaction }) }); ``` ## Important Notes 1. **Transaction Target**: All order transactions must be sent to the Match Engine contract address 2. **Order Mode**: - Base mode (0): Quantity specified in base token - Quote mode (1): Quantity specified in quote token (only available for market orders, useful for market buy orders where you want to specify the amount in quote token) 3. **Gas Estimation**: Recommended gas limit is 0x30000 (196,608) for most operations 4. **Nonce Management**: - Standard sequential nonces are supported - **TimeNonce Support**: You can use Unix timestamp in milliseconds as the nonce value - TimeNonce allows parallel transaction submission without nonce conflicts - Example: Use `Date.now()` (returns milliseconds) as the nonce value 5. **TPSL Orders**: Take Profit and Stop Loss can be attached to any limit order via the optional `tpsl` field 6. **Null Values**: In modify operations, set fields to null to keep current values unchanged --- ## Wallet # Wallet ## General Information - All endpoints return data in JSON format - All timestamps are in milliseconds (Unix epoch time) except where noted - Session wallet timestamps (expiry, createdAt) are in seconds - Wallet endpoints use address-based authentication (no JWT required) - Transfer operations require signed transactions ## Query Account Balance ### GET /api/v1/wallet/balance Get token balances for a wallet address. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | address | STRING | YES | Wallet address (0x...) | **Response:** ```json { "code": 200, "errMsg": "OK", "result": { "balances": [ { "tokenId": "1", "locked": "0", "unlocked": "1.039709" }, { "tokenId": "2", "locked": "100.5", "unlocked": "500.25" } ], "blockNumber": 12345678 } } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | balances | ARRAY | Array of token balance objects | | blockNumber | LONG | L2 block number at which the balances were queried | | tokenId | STRING | Unique identifier for the token | | locked | STRING | Amount locked in open orders (cannot be withdrawn) | | unlocked | STRING | Available balance for trading or withdrawal (see [Bridge](./bridge) for deposit/withdrawal details) | ## Withdraw Assets ### POST /api/v1/wallet/withdraw Submit a signed withdrawal transaction to move assets from L2 to Kaia L1. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}" } ``` **Request Fields:** | Field | Type | Required | Description | |-------|------|-----------|-------------| | tx | STRING | YES | Complete signed withdrawal transaction in hex format | **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | result | STRING | Transaction hash for the withdrawal operation | **Notes:** - For detailed withdrawal transaction creation and examples, see [Bridge Documentation](./bridge#withdrawal-l2--kaia-l1) - Withdrawals are processed automatically after submission - Both KAIA and ERC20 token withdrawals are supported ## Retry Failed Withdrawal ### POST /api/v1/wallet/withdraw/retry Retry a failed L2→L1 withdrawal using the latest confirmed Merkle root. **Request Body:** ```json { "txHash": "0x123abc...def" } ``` **Request Fields:** | Field | Type | Required | Description | |-------|------|----------|-------------| | txHash | STRING | YES | L2 withdrawal transaction hash to retry | **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x456def...789" } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | result | STRING | L1 execution transaction hash. Returns "0x0" if the withdrawal was already executed on L1 by an external transaction | **Notes:** - This endpoint retries withdrawals that failed during the L1 execution phase - A result of "0x0" indicates the withdrawal was already successfully completed on L1 (not by this request) ## Get Session Wallets ### GET /api/v1/wallet/session Get all session wallets associated with an owner address. **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | address | STRING | YES | Owner wallet address (0x...) | **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "name": "Trading Session 1", "expiry": 1758105316, "createdAt": 1757932516, "ownerAddress": "0x1234567890123456789012345678901234567890", "sessionAddress": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "applied": true }, { "name": "Trading Session 2", "expiry": 1758191716, "createdAt": 1758018916, "ownerAddress": "0x1234567890123456789012345678901234567890", "sessionAddress": "0xd02aaa39b223fe8d0a0e5c4f27ead9083c756cc3", "applied": false } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | name | STRING | User-friendly name for the session wallet | | expiry | LONG | Session expiry timestamp in seconds (Unix epoch) | | createdAt | LONG | Session creation timestamp in seconds (Unix epoch) | | ownerAddress | STRING | Main wallet address that owns this session wallet | | sessionAddress | STRING | Temporary session wallet address for trading | | applied | BOOLEAN | Whether the session wallet is currently active on-chain | ## Create Session Wallet ### POST /api/v1/wallet/session Create a new session wallet for delegated trading. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}", "name": "Trading Session 1" } ``` **Request Fields:** | Field | Type | Mandatory | Description | |------|------|-----------|-------------| | tx | STRING | YES | Complete signed session wallet creation transaction in hex format | | name | STRING | NO | Optional name for the session wallet | **Response:** ```json { "code": 200, "errMsg": "OK" } ``` **Notes:** - The transaction must be a valid session wallet creation transaction (see [Transaction Structure](./sign.md#1-session-wallet-operations-dexcommandsession---0x01)) - Owner address, session address, and expiry are extracted from the signed transaction - The name field is optional and stored for display purposes only ## Update Session Wallet ### POST /api/v1/wallet/session/update Update an existing session wallet's expiry time. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}" } ``` **Request Fields:** | Field | Type | Mandatory | Description | |------|------|-----------|-------------| | tx | STRING | YES | Complete signed session wallet update transaction in hex format | **Response:** ```json { "code": 200, "errMsg": "OK" } ``` **Notes:** - The transaction must be a valid session wallet update transaction (see [Transaction Structure](./sign.md#1-session-wallet-operations-dexcommandsession---0x01)) - This endpoint only updates the expiry time; the name cannot be changed - Owner address, session address, and new expiry are extracted from the signed transaction ## Delete Session Wallet ### POST /api/v1/wallet/session/delete Delete a session wallet. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}" } ``` **Request Fields:** | Field | Type | Mandatory | Description | |------|------|-----------|-------------| | tx | STRING | YES | Complete signed session wallet deletion transaction in hex format | **Response:** ```json { "code": 200, "errMsg": "OK" } ``` **Notes:** - The transaction must be a valid session wallet deletion transaction (see [Transaction Structure](./sign.md#1-session-wallet-operations-dexcommandsession---0x01)) - Owner address and session address are extracted from the signed transaction ## Transfer Assets ### POST /api/v1/wallet/transfer Submit a signed transfer transaction to move assets between L2 addresses. **Request Body:** ```json { "tx": "0x02f8730183...{complete signed transaction hex}" } ``` **Request Fields:** | Field | Type | Required | Description | |-------|------|----------|-------------| | tx | STRING | YES | Complete signed transfer transaction in hex format | **Response:** ```json { "code": 200, "errMsg": "OK", "result": "0x4c9980c4fd003e9aae2e7a8a87812382c84a695614225e423aaf1676089dbbfe" } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | result | STRING | Transaction hash for the transfer operation | **Notes:** - For detailed transfer transaction creation and examples, see [Transaction Structure](./sign.md#7-transfer-assets-dexcommandtokentransfer---0x11) - Both KAIA and ERC20 token transfers are supported - The transaction is processed immediately by the sequencer ### GET /api/v1/wallet/transfer Query transfer history for a specific address. **Query Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | address | STRING | YES | Wallet address to query transfer history for | | token_id | INT64 | NO | Filter by specific token ID | | from | INT64 | NO | Start timestamp in milliseconds (default: 0) | | to | INT64 | NO | End timestamp in milliseconds (default: current time) | | limit | INT | NO | Number of records to return (default: 100, max: 500) | **Response:** ```json { "code": 200, "errMsg": "OK", "result": [ { "id": 12345, "fromAddress": "0x1234567890123456789012345678901234567890", "toAddress": "0x0987654321098765432109876543210987654321", "txType": "Token Transfer", "tokenId": "1", "amount": "100.5", "status": "CONFIRMED", "timestamp": 1704067200000, "hash": "0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890" } ] } ``` **Response Fields:** | Field | Type | Description | |-------|------|-------------| | id | INT64 | Transfer record ID | | fromAddress | STRING | Source address | | toAddress | STRING | Destination address | | txType | STRING | Transfer type (e.g., "Token Transfer") | | tokenId | STRING | Token ID | | amount | STRING | Transfer amount | | status | STRING | Transfer status (e.g., "Success") | | timestamp | INT64 | Transfer timestamp in milliseconds | | hash | STRING | Transaction hash | **Notes:** - Results are returned in reverse chronological order (newest first) - The `from` and `to` timestamps are in milliseconds (Unix epoch time) - If `token_id` is not specified, transfers for all tokens are returned ## POST Endpoints for Wallet Operations All wallet POST operations (session wallet, transfers) require signed transactions sent to the fixed contract address. For detailed transaction structure and examples, see [Transaction Structure Documentation](./sign.md): - Session Wallet Operations: [Section 1](./sign.md#1-session-wallet-operations-dexcommandsession---0x01) - Kaia Transfers: [Section 7](./sign.md#7-transfer-assets-dexcommandtokentransfer---0x11) - Token-specific Transfers: Command byte 0x11 (DexCommandTokenTransfer) ## Notes - All wallet addresses must be valid Ethereum addresses (0x...) - All numeric values (amounts, balances) are returned as strings to preserve precision - Most timestamps are in milliseconds (Unix epoch time); session wallet timestamps are in seconds - Session wallets provide delegated trading capabilities with configurable expiry times - Session wallet operations (create, update, delete) require signed transactions - The `locked` balance represents funds tied up in open orders and cannot be withdrawn - The `unlocked` balance is available for trading and withdrawal - Transfer operations require properly signed transactions following the L2 transaction format - For deposit and withdrawal operations between L1 and L2, see [Bridge Documentation](./bridge) --- ## WebSocket # WebSocket ## General Information - All data is returned in JSON format - All timestamps are in milliseconds (Unix epoch time) - A single connection can subscribe to multiple streams - The WebSocket server sends a ping frame every 30 seconds - If a pong frame is not received within 60 seconds, the connection will be closed - Maximum connection lifetime is 24 hours ## Message Format ### Request Format All requests to the WebSocket server follow this format: ```json { "method": "subscribe", "params": { "channels": ["trade@1_2", "depth@1_2"] }, "id": 1 } ``` **Request Fields:** | Field | Type | Description | |-------|------|-------------| | method | STRING | Action to perform: "subscribe" or "unsubscribe" | | params | OBJECT | Parameters for the method | | channels | ARRAY | Array of channel names to subscribe/unsubscribe | | id | INT | Request ID for correlation with responses | ### Response Format Server responses for subscription requests: ```json { "result": "ok", "id": 1 } ``` ### Stream Data Format Stream updates are sent in this format: ```json { "method": "subscription", "params": { "channel": "trade@1_2", "result": { // Stream-specific data } } } ``` ## Available Streams ### Trade Streams Real-time trade executions for a specific market. **Channel Name:** `trade@{marketId}` **Example:** `trade@1_2` **Subscribe:** ```json { "method": "subscribe", "params": { "channels": ["trade@1_2"] }, "id": 1 } ``` **Stream Data:** ```json { "method": "subscription", "params": { "channel": "trade@1_2", "result": { "tradeId": "405100010000", "marketId": "1_2", "price": "2.3", "quantity": "0.7", "buyOrderId": "0xdb9d5d086b4755fb5e49819fef783f80fb98f893", "sellOrderId": "0x766be3ed6e3296708885405c7766c6cc880cfafa", "createdAt": 1758005316000, "isBuyerMaker": false } } } ``` ### Diff. Depth Stream Order book price and quantity depth updates used to locally manage an order book. **Stream Name:** `depth@{marketId}` **Update Speed:** Real-time **Subscribe:** ```json { "method": "subscribe", "params": { "channels": ["depth@1_2"] }, "id": 1 } ``` **Payload:** ```json { "method": "subscription", "params": { "channel": "depth@1_2", "result": { "marketId": "1_2", // Market ID "bids": [ // Bids to be updated [ "2.30", // Price level to be updated "10.5" // Quantity ] ], "asks": [ // Asks to be updated [ "2.31", // Price level to be updated "15.0" // Quantity ] ], "firstId": 42920, // First update ID in event "finalId": 42921, // Final update ID in event "time": 1758096768006 // Event time } } } ``` **How to manage a local order book correctly:** 1. Open a stream to `depth@{marketId}`. 2. Buffer the events you receive from the stream. 3. Get a depth snapshot from `GET /api/v1/market/depth?marketId={marketId}`. 4. Drop any event where `finalId = lastUpdatedId + 1`. 6. While listening to the stream, each new event's `firstId` should equal the previous event's `finalId + 1`. If not, re-sync from step 3. 7. For each event, apply the price level updates: - The price level quantity is the **absolute quantity** at that price (not a delta). - If the quantity is `0`, **remove** the price level. 8. Bids are sorted by price in **descending** order (best bid first). 9. Asks are sorted by price in **ascending** order (best ask first). :::note Receiving an event that removes a price level that is not in your local order book can happen and is normal. ::: ### Partial Book Depth Streams Top **100** bids and asks, pushed every **500ms** or on order book change. **Stream Name:** `depthSnapshot@{marketId}` **Update Speed:** 500ms or Real-time **Subscribe:** ```json { "method": "subscribe", "params": { "channels": ["depthSnapshot@1_2"] }, "id": 1 } ``` **Payload:** ```json { "method": "subscription", "params": { "channel": "depthSnapshot@1_2", "result": { "marketId": "1_2", // Market ID "lastUpdateId": 42921, // Last update ID "bids": [ // Bids [ "2.30", // Price level "100.5" // Quantity ] ], "asks": [ // Asks [ "2.31", // Price level "150.0" // Quantity ] ], "time": 1758096768006 // Event time } } } ``` ### Ticker Streams 24hr rolling window ticker statistics for all markets. **Channel Name:** `ticker` (all markets only) **Subscribe:** ```json { "method": "subscribe", "params": { "channels": ["ticker"] }, "id": 1 } ``` **Stream Data:** ```json { "method": "subscription", "params": { "channel": "ticker", "result": [ { "marketId": "1_2", "baseTokenId": "1", "quoteTokenId": "2", "price": "2.3", "open24h": "2.1", "high24h": "2.5", "low24h": "2.0", "volume24h": "150000.5", "quoteVolume24h": "345001.15" }, { "marketId": "3_2", "baseTokenId": "3", "quoteTokenId": "2", "price": "3500.0", "open24h": "3400.0", "high24h": "3600.0", "low24h": "3350.0", "volume24h": "1200.5", "quoteVolume24h": "4200000.0" } ] } } ``` **Ticker Stream Response Fields:** | Field | Type | Description | |-------|------|-------------| | result | ARRAY | Array of ticker data for all markets | | marketId | STRING | Market identifier | | baseTokenId | STRING | Base token identifier | | quoteTokenId | STRING | Quote token identifier | | price | STRING | Current/last traded price | | open24h | STRING | Opening price 24 hours ago | | high24h | STRING | Highest price in last 24 hours | | low24h | STRING | Lowest price in last 24 hours | | volume24h | STRING | Base token volume in last 24 hours | | quoteVolume24h | STRING | Quote token volume in last 24 hours | ### User Event Streams Real-time updates for user's orders and trades. **Channel Name:** `userEvent@{address}` **Important**: The address in the channel name is automatically converted to EIP-55 checksum format. For example, if you subscribe with a lowercase address, the stream will return with the checksummed version. **Example:** - Input (lowercase): `userEvent@0x000000000000000000000000000000000000abcd` - Stream returns (checksummed): `userEvent@0x000000000000000000000000000000000000ABcD` **Subscribe:** ```json { "method": "subscribe", "params": { "channels": ["userEvent@0x000000000000000000000000000000000000ABcD"] }, "id": 1 } ``` **User Event Response Fields:** **Common Fields (All Events):** | Field | Type | Description | |-------|------|-------------| | topic | STRING | Event topic: "ORDER" or "ACCOUNT" | | eventType | STRING | Event type (see Event Types table below) | | eventTime | LONG | Event timestamp in milliseconds | | blockNumber | LONG | Blockchain block number | | accountAddress | STRING | Account address | | txHash | STRING | Transaction hash | **ORDER Topic Fields (topic="ORDER"):** | Field | Type | Event Types | Description | |-------|------|-------------|-------------| | orderId | STRING | ALL | Order identifier (transaction hash) | | marketId | STRING | ALL | Market identifier | | side | STRING | ALL | "BUY" or "SELL" | | orderType | STRING | ALL | Order type (LIMIT, MARKET, etc.) | | orderMode | INTEGER | ALL | Order mode: 0 = base token quantity, 1 = quote token quantity | | origPrice | STRING | ALL | Original order price | | origQty | STRING | ALL | Original order quantity | | origQuoteOrderQty | STRING | ALL | Original quote order quantity | | status | STRING | ALL | Order status: "NEW", "PARTIALLY_FILLED", "FILLED", "CANCELED", "REJECTED" | | createdAt | LONG | ALL | Order creation timestamp in milliseconds | | executedQty | STRING | ALL | Total cumulative executed quantity including this event | | executedQuoteQty | STRING | ALL | Total cumulative executed quote amount including this event | | lastPrice | STRING | ALL | Price from this event (0 for non-execution events) | | lastQty | STRING | ALL | Quantity from this event (0 for non-execution events) | | fee | STRING | ALL | Fee from this event | | feeTokenId | STRING | ALL | Fee token ID | | tradeId | STRING | ALL | Trade ID (empty for non-trade events) | | isMaker | BOOLEAN | ALL | True if maker order | **ACCOUNT Topic Fields (topic="ACCOUNT"):** | Field | Type | Event Types | Description | |-------|------|-------------|-------------| | tokenId | STRING | ALL | Token identifier | | amount | STRING | ALL | Asset amount | | fromAddress | STRING | TRANSFER | Source address (sender) | | toAddress | STRING | TRANSFER | Destination address (receiver) | **User Event Types:** **ORDER Topic Events:** | Event Type | Description | |------------|-------------| | NEW | New order placed | | TRADE | Order execution/trade | | CANCEL | Order canceled | | TRIGGER | Trigger order activated | | REJECTED | Order was rejected by the system | **ACCOUNT Topic Events:** | Event Type | Description | |------------|-------------| | DEPOSIT | Asset deposit to the DEX | | WITHDRAW | Asset withdrawal from the DEX | | TRANSFER | Asset transfer between accounts | ### ORDER Topic Events ```json { "method": "subscription", "params": { "channel": "userEvent@0x000000000000000000000000000000000000ABcD", "result": { "topic": "ORDER", "eventType": "TRADE", // Event types: "NEW", "TRADE", "CANCEL", "TRIGGER", "REJECTED" "eventTime": 1758182405000, "blockNumber": 12345678, "accountAddress": "0x000000000000000000000000000000000000ABcD", "orderId": "0x99eaddbe1a31751b4aca11269d6e45bd9c18894190140fbd80c08053933a7949", "txHash": "0x99eaddbe1a31751b4aca11269d6e45bd9c18894190140fbd80c08053933a7949", "marketId": "5_2", "side": "SELL", // "BUY" or "SELL" "orderType": "LIMIT", // "LIMIT", "MARKET", "STOP_LOSS_LIMIT", "TAKE_PROFIT_LIMIT" "orderMode": 0, "origPrice": "0.2", "origQty": "10", "origQuoteOrderQty": "0", "status": "FILLED", // NEW: "NEW" | TRADE: "PARTIALLY_FILLED" or "FILLED" | CANCEL: "CANCELED" | TRIGGER: "NEW" | REJECTED: "REJECTED" "createdAt": 1758182405000, "executedQty": "10", // Cumulative filled amount. NEW/TRIGGER/REJECTED: "0" | TRADE: cumulative | CANCEL: amount filled before cancellation "executedQuoteQty": "2", // Cumulative filled quote value. Same rules as executedQty "lastPrice": "0.2", // Price from this specific trade. NEW/CANCEL/TRIGGER/REJECTED: "0" | TRADE: actual trade price "lastQty": "10", // Quantity from this specific trade. NEW/CANCEL/TRIGGER/REJECTED: "0" | TRADE: actual trade quantity "fee": "0.0006", // Fee amount for this event. NEW/CANCEL/TRIGGER/REJECTED: "0" | TRADE: actual fee "feeTokenId": "2", // Fee token ID. null if no fee "tradeId": "4340900010000", // Trade ID. Empty string for non-TRADE events "isMaker": false // Whether this was a maker order. Only relevant for TRADE events } } } ``` **Field Notes by Event Type:** - **NEW**: Order placed. `status="NEW"`, all execution fields (`executedQty`, `executedQuoteQty`, `lastPrice`, `lastQty`, `fee`) are "0", `tradeId` is empty. - **TRADE**: Order executed. `status` is "PARTIALLY_FILLED" or "FILLED". `executedQty`/`executedQuoteQty` show cumulative totals. `lastPrice`/`lastQty` show this specific trade's execution. - **CANCEL**: Order canceled. `status="CANCELED"`. `executedQty`/`executedQuoteQty` show amounts filled before cancellation. `lastPrice`/`lastQty` are "0". - **TRIGGER**: Stop-loss/take-profit order activated. `status="NEW"` (order now active in orderbook). All execution fields are "0" as triggering is not an execution. - **REJECTED**: Order rejected by system. `status="REJECTED"`, all execution fields are "0". ### ACCOUNT Topic Events ```json { "method": "subscription", "params": { "channel": "userEvent@0x000000000000000000000000000000000000ABcD", "result": { "topic": "ACCOUNT", "eventType": "TRANSFER", // Event types: "DEPOSIT", "WITHDRAW", "TRANSFER" "eventTime": 1758182700000, "blockNumber": 12345710, "accountAddress": "0x000000000000000000000000000000000000ABcD", // DEPOSIT: recipient | WITHDRAW: sender | TRANSFER: sender or receiver "txHash": "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", "tokenId": "2", "amount": "25.5", "fromAddress": "0x000000000000000000000000000000000000ABcD", // Only for TRANSFER events. The sender address "toAddress": "0x1111111111111111111111111111111111111111" // Only for TRANSFER events. The receiver address } } } ``` **Field Notes by Event Type:** - **DEPOSIT**: Asset deposited into the DEX. `accountAddress` is the recipient (matches ToAddress). `fromAddress` and `toAddress` are not included. - **WITHDRAW**: Asset withdrawn from the DEX. `accountAddress` is the initiator (matches FromAddress). `fromAddress` and `toAddress` are not included. - **TRANSFER**: Asset transferred between accounts. Two separate events are generated (one for sender, one for receiver). `accountAddress` matches the party receiving the event. `fromAddress` and `toAddress` fields indicate the transfer direction. ## Subscription Management ### Subscribe to Multiple Streams You can subscribe to multiple streams in a single request: ```json { "method": "subscribe", "params": { "channels": [ "trade@1_2", "depth@1_2", "ticker", "userEvent@0x000000000000000000000000000000000000ABcD" ] }, "id": 1 } ``` ### Unsubscribe from Streams To unsubscribe from specific streams: ```json { "method": "unsubscribe", "params": { "channels": ["trade@1_2", "depth@1_2"] }, "id": 2 } ``` ## Connection Maintenance ### Ping/Pong The server sends ping frames every 30 seconds to maintain the connection. Your WebSocket client should automatically respond with pong frames. If you're implementing a custom client: ```javascript ws.on('ping', function() { ws.pong(); // Respond to ping with pong }); ``` --- ## What is Alpha Sec.? # What is Alpha Sec.? #### "Born from Origin. Built on Orderbook. Becoming the Ordinary." CEX-like performance. DeFi-first values. Alpha Sec. is where they finally meet. Alpha Sec. is a high-performance orderbook DEX that brings centralized-level execution into a fully decentralized environment, without compromise. Built on the ultra-fast Optimistic Rollup network, Alpha Sec. offers: - Seamless trading with CEX-level usability - Institutional-grade performance with robust API support - Self-custody by default, removing centralized risk - 100% on-chain transparency, ensuring full verifiability Alpha Sec. isn’t catching up. It’s leading the way toward what decentralized trading should be. --- ## Audit # Audit Optimistic Rollup Layer2 audited by CertiK: - **[251220 AlphaSec - CertiK Audit Report](../../static/audit/251220_AlphaSec_CertiK_Audit_Report.pdf)** --- ## Privacy Policy # Privacy Policy This Privacy Policy (this "Policy") for Kairos Studio Ltd., located in the BRITISH VIRGIN ISLANDS (the "Company", "we", "our", or "us") sets forth the basis on which we may process personal data we may collect from users of the Company's website, app.alphasec.trade, including any of its subdomains (the "Website"), in accordance with applicable law. For purposes of applicable data protection laws, the Company is the controller. For the purposes of this Policy, "you" and "your" refers to you as the user of the Website. Read this Policy carefully so that you understand your rights in relation to your personal data and how we might collect, use, and process it. By accessing and using the Website, you expressly represent and acknowledge that you have read, understood, and agreed to be bound by this Policy. If you do not agree to this Policy, do not use, access, connect to or interact with the Website, or otherwise provide your information to us. ### PERSONAL DATA WE COLLECT ABOUT YOU, WHY WE PROCESS IT, AND THE LEGAL BASIS FOR PROCESSING When you access, use, connect to, or interact with the Website, you agree that we may collect certain categories of information about you (the "Data"), including personal data, from a variety of sources. Information you provide to us: By accessing our services by connecting your digital wallet to the Website, you provide us with the following Data: (i) any digital-asset, smart-contract, or protocol address ("Wallet") information; and (ii) geolocation data. Further to the foregoing, when you access and use the Website, we collect transaction data or history such as your public blockchain transaction history and other information associated with a linked address or Wallet and token holdings. In the event you contact us, you will be required to provide your email address, which we will collect along with the content of our communications and any personal data contained therein. Data we collect automatically: While the following Data may not constitute personal information, when you visit certain pages on our Website, our servers save each access in a log file, and the following Data may be collected: (i) the date and time of access; (ii) the country from which the website is accessed; (iii) any API endpoints being accessed; (iv) user agent details; (v) the operating system of your computer and the browser you are using (provider, version, and language); and (vi) the transmission protocol used (e.g., HTTP/1.1). Usage Data Collection: We may use web beacons/clear gifs, geolocation and tracking technologies, and other applications when you visit the Website, including technologies collecting certain information about your access to, use of, connection to, or interaction with the Website ("Usage Data") that may be integrated with third-party service providers. For your reference, a web beacon, also known as a clear gif, is a small, often invisible image embedded in a web page or online content to monitor user interactions on a website and track user behavior for analytical reporting purposes. In our legitimate interests to provide effective services to you, we may also use this Usage Data to create aggregated, anonymized, or de-identified data. Further to the foregoing, when you access, use, connect to, or interact with the Website, the Company and any of its third-party service providers may receive and record personal data that you may have provided and your digital signature. By providing your digital signature in the course of your interaction with the Website, you explicitly agree to and approve the collection of your digital signature data, and you authorize the Company to store and process such data and use it to facilitate your access to and use of the Website. You further acknowledge and consent that such digital signature data may be disclosed and transferred to third-party service providers that you access through the Website. Third-Party Wallet Connections and Disclaimer: Certain features of the Website may require you to connect a compatible third-party digital Wallet. By using such Wallet, you agree that your access to, use of, connection to, and/or interactions with such third-party Wallets are governed by the policy for the applicable Wallet, and you agree that you are using the Wallet in accordance with the terms and conditions of the applicable third-party provider of such Wallet. Wallets are not maintained or supported by, or associated or affiliated with, the Company. We expressly disclaim any and all liability for actions arising from your use of third-party Wallets, including but without limitation, actions relating to the use and/or disclosure of personal information by such third-party Wallets. Legal Basis and Purposes for Processing Data: We generally process the information we collect when we need to do so to perform our contract with you. For example, the processing of this Data is carried out for the purpose of enabling your access to, use of, connection to, and interaction with the Website, including: (i) to facilitate your connection to the Website; and (ii) to identify if you are likely to be a Restricted Person, as defined in our general Terms of Use, available at https://alphasec.trade/terms. Each case with respect to any of (i) or (ii) is in order for us to perform our contract with you and in our legitimate interests to provide access to the Website to you. For the avoidance of doubt, the Company is not responsible or liable for verifying whether you are a restricted person; this remains your responsibility under the Terms. Nonetheless, any information collected may assist the Company in verifying your eligibility if necessary. Further, we may use any Data collected, including Usage Data, to tailor features and content to you and to ensure content is presented in the most effective manner for you and your device. We may also use and run analytics to better understand your user experience with respect to the Website. We may also process this Data in our legitimate interests to assist system security and stability for provision of the Website, to conduct troubleshooting, data analytics, testing, and research, and to enable optimization and internal statistical analysis with respect to the Website, as well as to maintain the safety and security of our users, the Website, and to improve and develop the Website. In addition to the foregoing, we may use any of your information to comply with any applicable legal obligations, to enforce any applicable terms of use, and to protect or defend the Website, our rights, and the rights of our users or others. Cookie Policy: Cookies are small data files stored on your device that help the Website remember your preferences, improve functionality, and understand general usage patterns. We use cookies to enhance your experience when accessing and using the Website. The cookies we use are strictly necessary cookies, which help ensure compliance with our Terms of Use, and are otherwise integral to our ability to provide the best user experience and to help us understand general usage patterns. These cookies are not used for marketing purposes. By continuing to use the Website, you consent to the placement of these cookies. If we introduce optional cookies (e.g., analytics or marketing cookies) in the future, you will be able to block or delete them using the following methods: How to Block Cookies Desktop Browsers - Chrome: Click the "⋮" icon at the top right > Settings >Privacy and security > Cookies and other site data > Block third-party cookies - Edge: Click the "…" icon at the top right > Settings > Cookies and site permissions > Manage and delete cookies and site data > Block cookies - Safari (Mac): Safari > Preferences > Privacy > Block all cookies Mobile Browsers - Chrome (Mobile): Tap the "⋮" icon at the top right > Settings >Site settings > Cookies > Block cookies - Safari (iOS): Device Settings > Safari > Block All Cookies - Samsung Internet: Tap the "≡" icon at the bottom > Settings >Sites and downloads > Block cookies How to Delete Cookies Desktop Browsers - Chrome: Click the "⋮" icon at the top right > Settings >Privacy and security > Clear browsing data > Select "Cookies and other site data" > Delete - Edge: Click the "…" icon at the top right > Settings > Privacy, search, and services > Clear browsing data > Select "Cookies and other site data" > Delete - Safari (Mac): Safari > Preferences > Privacy > Manage Website Data > Select items > Remove Mobile Browsers - Chrome (Mobile): Tap the "⋮" icon at the top right > Settings >Privacy > Clear browsing data > Select "Cookies and site data"> Delete - Safari (iOS): Device Settings > Safari > Advanced > Website Data > Remove All Website Data - Samsung Internet: Tap the "≡" icon at the bottom > Settings >Privacy and security > Delete browsing data > Select "Cookies and site data" > Delete ### YOUR RIGHTS Under applicable data protection laws, you may have certain rights in relation to your personal data. These rights may include the following: - Access to your personal data that we hold, information on how we use it, and who we share it with; - Request the correction of inaccurate or incomplete personal data we hold about you, which we may verify as necessary before making changes; - Deletion or removal of your personal data, in certain circumstances; - Objection to the processing of your personal data, in certain circumstances; - Restriction of the processing of your personal data, to stop us from processing the personal data we hold about you other than for storage purposes, in certain circumstances; - Portability of your personal data; we will endeavor to provide you, or a third party, with a copy of the personal data that we hold about you and transfer it to a third party in a structured, commonly used, machine-readable format; - Withdrawal of consent, where we rely on consent to process personal data; this will not affect the processing of personal data carried out before consent is withdrawn or on legal bases other than consent. You may submit a written request concerning the processing of your personal data to support@alphasec.trade. Please note that, prior to any response to such request, we will require you to verify your identity. In addition, we may have valid legal reasons to refuse your request and will inform you if that is the case. Note that these rights apply only in certain circumstances and all of these rights may be limited by law. Such limitations may apply, for example, where fulfilling your request would adversely affect other individuals or our trade secrets or intellectual property, where there are overriding public interests, or where we are required by law to retain your personal data. To the extent required under applicable data protection laws, we will be responsive to your request without undue delay and where required under applicable data protection laws, at least within one month (though this may be extended by a further two months in certain circumstances). ### SHARING OF PERSONAL DATA In certain circumstances, we may share your information with third parties with your consent, as necessary, or as otherwise required or permitted by law, including, but not limited to: - service providers and vendors ("Data Processor"): we may share your personal data with third parties to process on our behalf. Such Data Processor could include blockchain analysis service providers, screening service providers, developers, content delivery service providers, and data analytics service providers. Such service providers may assist us with many different functions and tasks, including geo-blocking based on IP address and collecting anonymized device information for analytics purposes. - professional advisors, in our legitimate interests or as required by law. - for legal and security reasons and to protect our Website, in our legitimate interests or as required by law. We use Google Analytics, a web analytics service provided by Google LLC ("Google"), to help us analyze how users interact with our services. In this regard, certain personal data (such as IP address, device information, and usage data) may be collected by Google and processed on our behalf. Google may also combine such data with other information it has collected about you through its own services. By using our services, you acknowledge and agree that your personal data may be transferred to and processed by Google for the purposes of providing analytics and improving our services. In particular, we use Google Analytics, a web analytics service provided by Google LLC ("Google"), to better understand how users interact with the Website. In this context, certain data such as device information, and usage data, may be collected by Google and processed on our behalf. By continuing to use the Website, you acknowledge and agree that your Data, including personal data, may be transferred to and processed by Google for the purposes of analytics and service improvement. Your personal information may be transferred to and stored or processed in countries outside the jurisdiction in which you live and reside, including outside the European Economic Area ("EEA") and United Kingdom ("UK"), and including to the United States of America, in order to provide the Website, in which case we will disclose the relevant provision in the Privacy Policy or obtain separate consent from you for the transfer. Your personal information may also be processed by staff operating outside the UK/EEA who work for us or for third-party service providers or partners. We will take steps reasonably necessary to ensure that your personal information is treated securely and in accordance with this Policy. Should we transfer your personal information to third parties located outside the EEA/UK, we will seek to put in place appropriate safeguards to ensure that this transfer occurs in accordance with applicable laws. These measures include seeking entry into the standard contractual clauses ("SCCs") approved by the European Commission (for transfers outside the EEA) and/or an international data transfer agreement/addendum to the SCCs approved by the UK Information Commissioner's Office ("ICO") (for transfers outside the UK), unless the data transfer is to a country that has been determined by the European Commission or the relevant UK authorities, as applicable, to provide an adequate level of protection for individuals' rights and freedoms for their personal data. ### RETENTION We will retain your Data only for so long as necessary to fulfill the purposes for which it was collected, but in any case no longer than [5] years, unless we are required to retain the Data to satisfy any legal, accounting or reporting requirements, or as otherwise required by law. The length of time we retain your Data will depend on the nature of the Data and the purpose for which it was processed. Upon expiration of the retention period, we will delete your Data; however, if complete deletion is impractical, we will take reasonable measures, considering time, cost, and technology, to anonymize the personal data so that it can no longer be used to identify you. ### CHILDRENS' PRIVACY AND DATA PROTECTION If we become aware that we have unknowingly collected information about any person under eighteen (18) years of age, we will make commercially reasonable efforts to delete such personal data and other information from our records. ### SECURITY MEASURES TAKEN TO PROTECT PERSONAL DATA The Company implements reasonable measures to protect your personal data. However, be aware that despite our efforts to protect your personal data and other information, we cannot guarantee perfect security of your information transmitted through the Website. In addition, note that any information you send to us electronically, may not be secure while in transit. Any transmission is at your own risk. ### SOCIAL MEDIA AND OTHER THIRD-PARTY WEBSITES AND LINKS We may provide links on the Website to other websites or online platforms operated by third parties, including social media or content platforms operated by third parties, such as X (formerly Twitter) or Medium (such platforms, generally, "Social Media Platforms"). We may also provide links to websites or online platforms operated by third-party contributors to the NitroX blockchain and ecosystem ("Contributors"). We do not own, operate, or control such third-party websites. If you follow links to sites not owned or operated by us, you should review their available privacy and security policies and other terms and conditions. We do not guarantee and are not responsible for the privacy, security, or content of these sites, including the accuracy, completeness, or reliability of information and services found on these sites. Note that third parties and Contributors may provide services, information, dashboards, websites, tools, functionalities, and applications, and these may be linked from time to time through the Website or through Social Media Platforms. Such third parties and Contributors are independent and as such, we do not own, operate, or control their services, information, dashboards, websites, tools, functionalities, and applications and cannot guarantee, and are not responsible for, the privacy, security, or content of these sites or the accuracy, completeness, or reliability of services, information, dashboards, websites, tools, functionalities, and applications found on these sites. Our inclusion of links, including through Social Media Platforms, does not, by itself, imply any endorsement of such services, information, dashboards, websites, tools, functionalities, and applications, or of their owners, operators, or publishers, except as disclosed on the Website. When you open a link to any Social Media Platform from the Website, a direct connection may be established between your browser and the server of the Social Media Platform. This provides the Social Media Platform with information that you visited the Website and accessed the link. If you access a link to a Social Media Platform while logged-in to your account on the Social Media Platform concerned, the content of the Website may be linked to your profile on the platform (i.e., the Social Media Platform may link your visit to the Website directly to your user account). If you want to prevent this, you should log out before clicking on the relevant links. In any case, an association takes place when you log-in to the relevant Social Media Platform after clicking on the link. You understand and agree that it is your sole responsibility to connect to third-party Social Media Platforms through our Website. You further agree to indemnify, defend, and hold the Company harmless from any loss, damages, liabilities, or expenses incurred in connection with your use of any third-party services accessed via the Website. ### GOVERNING LAW AND DISPUTE RESOLUTION This Policy takes into account the requirements of British Virgin Islands' privacy policy and general privacy principles, and shall be governed by and construed in accordance with the laws of the British Virgin Islands. Individuals located in the European Union ("EU") and the United Kingdom ("UK") may have rights under the EU General Data Protection Regulation 2016/679 and the UK General Data Protection Regulation, respectively (collectively, the "GDPR"). You and the Company agree to waive the right to have any and all disputes or claims arising from this Policy ("Disputes") resolved in a court. Instead, all Disputes will be resolved through binding arbitration. All arbitration proceedings will be conducted solely on an individual basis. No Dispute may be brought as a class action or representative action, whether in arbitration or any other forum. You agree to notify us, in writing, of any Dispute within thirty (30) days of when it arises so that the parties can attempt, in good faith, to resolve the Dispute informally. Notice to the Company shall be provided by sending an email to support@alphasec.trade. Your notice must include: (1) your name, postal address, and email address; (2) a description of the nature or basis of the Dispute; and (3) the specific resolution or action that you are seeking. If the Dispute cannot be resolved informally within thirty (30) days of receipt, either party may commence arbitration. Any Dispute that remains unresolved after the informal resolution process will be finally resolved by arbitration under the rules of the London Court of International Arbitration (LCIA), as amended from time to time, which are incorporated by reference into this clause. Arbitration will be conducted in English, in London, United Kingdom, by a single arbitrator appointed under the LCIA Rules. Each party shall bear its own costs, unless otherwise determined by the arbitrator. For the avoidance of doubt, neither you nor the Company may bring a Dispute in any court located in the United States of America. ### PERIODIC REVIEWS AND UPDATES TO POLICY We may review and update this Policy from time to time. While the Company shall not be liable for any such modifications, suspensions, or discontinuance, the Company will use reasonable efforts to provide prior notice of changes. In principle, notice of at least seven (7) days will be given before any changes to this Policy take effect, and in the case of material changes, notice of at least thirty (30) days will be given. If advance notice is not reasonably practicable, notice will be provided promptly by posting the revised Policy on the Website. For the avoidance of doubt, posting the revised Policy on the Website shall be deemed to constitute valid and sufficient notice of such changes. Updates to this Policy will apply only to information collected after the date of the change. If we make changes, we will update the "Last updated" date at the top of this Policy. If you continue to participate in the Interface in any way after a change to these Terms, you will be deemed to have read, understood, and unconditionally consented and agreed to such changes. You should review this Policy and applicable policies and guidelines frequently to understand the terms and conditions that apply to your provision of Data. If you do not agree to the revised Policy, you must immediately cease using the Website and contact us if you wish to have your personal data deleted before the end of the prescribed retention period. ### CONTACT Should you have any questions or complaints about our privacy or data-protection practices, your personal data, or this Policy, you can email us at support@alphasec.trade. --- ## Terms of Use # Terms of Use These Terms of Use (these "Terms") set forth the terms and conditions by which you may access and use this website-hosted user interface, Alpha Sec. (the "Interface"), available at app.alphasec.trade. The Interface is made available by Kairos Studio Ltd. (the "Company", "we", "us" or "our"). You must read these Terms carefully as they govern your use of the Interface. By accessing and using the Interface, you expressly represent and acknowledge that you have read, understood, and agreed to be bound by these Terms. If you do not agree, you are not authorized to access or use the Interface. ### 1. THE INTERFACE 1.1 The Interface facilitates your interaction with NitroX, a decentralized, permissionless, and community-driven blockchain ("NitroX"). The Company does not own, control, or operate NitroX, nor can it modify or interfere with its functionality, security, or availability. The Interface is not the exclusive means of accessing NitroX. 1.2 All transactions conducted on NitroX are executed by a decentralized set of validators. The Company is solely a provider of the Interface, has no involvement in the execution of transactions, and expressly disclaims any liability for losses or damages arising from or related to any interaction with, or actions taken on, NitroX through the Interface. 1.3 To use the Interface, you must use a non-custodial wallet, which allows you to access public blockchains and interact with them. You should consult the terms of service provided by your wallet provider to understand your rights and responsibilities as they relate to your self-custodial wallet. The Company has no custody or control over the contents of your wallet and has no ability to retrieve or transfer its contents. When you connect your wallet to the Interface, you agree to be bound by these Terms. 1.4 The Interface solely serves to facilitate your interaction with NitroX, and any and all transactions on NitroX are conducted through individual wallets or separate services, rather than through any wallet or service of the Company. For the avoidance of doubt, the Company does not have control over any private keys or involvement in the operation of your wallet and, therefore, does not engage in or assume any responsibility for the transfer, custody, or exchange of assets. 1.5 By using the Interface, you acknowledge and agree that all use of the Interface, and any interaction with NitroX through the Interface, is entirely at your own risk. 1.6 The Interface is not available to "Restricted Persons." For the purposes of these Terms, Restricted Persons include: (a) persons or entities who reside in, are located in, are incorporated in, or have a registered office in the United States of America or Ontario, Canada; (b) persons or entities who reside in, are located in, are incorporated in, or have a registered office in jurisdictions subject to applicable economic and trade sanctions or export control laws and regulations by the United Nations, the United States, the European Union, the United Kingdom, or any other relevant governmental authority (collectively, "Restricted Territories"); and (c) citizens of Restricted Territories, regardless of their location. Restricted Persons are strictly prohibited from accessing or using the Interface described herein. Any attempt to circumvent these restrictions, whether through the use of virtual private networks (VPNs), proxy servers, or other technological means, shall be deemed a violation of these Terms and may result in immediate suspension or termination of access, without prejudice to any other remedies available to the Company under applicable laws. 1.7 You are solely responsible for determining whether your access to and use of the Interface complies with applicable laws and regulations in your jurisdiction, including, but not limited to, laws governing leveraged or derivative trading. By using the Interface, you expressly represent and warrant that your activities are lawful under such applicable laws. ### 2. NO WARRANTIES 2.1 The Interface is provided on an "as is" and "as available" basis without warranties of any kind, either express, implied, statutory, or otherwise, including, but not limited to, warranties of merchantability, title, fitness for a particular purpose, non-infringement, accuracy, completeness, reliability, security, or timeliness. To the fullest extent permitted by law, the Company makes no representations or warranties that access to the Interface will be continuous, uninterrupted, or error-free, that any defects will be corrected, or that the Interface or any interaction through the Interface with NitroX will meet your expectations or requirements. 2.2 You expressly understand and agree that you are solely responsible for evaluating and accepting the risks involved in using the Interface, as well as the risks associated with digital assets and decentralized systems generally, including, but not limited to: (a) the inherent volatility of digital assets, which may result in sudden and substantial losses in value; (b) the risks of using digital assets due to both features of such assets and the potential unauthorized acts of third-parties, including hacking, phishing, fraud, or cyberattacks; (c) the possibility of limited access to your assets or delays, disruptions, or errors when using the Interface; and (d) the potential loss of tokens or other assets due to network failures, errors in any code or algorithm, or factors beyond the Company's control. 2.3 You agree that you will have no recourse against the Company or the Indemnified Parties (defined below) for any losses due to your use of the Interface. Such losses may include, but are not limited to, those arising from or relating to: (a) incorrect information, including any displayed token values or transaction details; (b) failures of blockchain networks, including forks, congestion, or malicious attacks; (c) corrupted cryptocurrency wallet files or wallet incompatibilities; (d) unauthorized access to wallets or accounts, including losses caused by compromised private keys; (e) errors or inaccuracies in the Interface or its underlying software; (f) failures of, or actions by, third-party systems, services, or applications you rely on to use the Interface or interact with NitroX; (g) slippage or market inefficiencies when executing trades; (h) any malfunction or failure of NitroX or its decentralized set of validators; and (i) regulatory actions or legal uncertainties affecting the availability or use of NitroX or related assets. 2.4 By using the Interface, you acknowledge and accept full responsibility for all of the risks involved in accessing and using the Interface or interacting with NitroX through the Interface, including, without limitation: (a) failures or inaccuracies in cross-chain bridges, oracles, or liquidity pools; (b) code vulnerabilities, including potential hacks or exploits; (c) significant slippage or other market risks arising from perpetual futures trading; (d) the risks of trading with leverage, which may lead to immediate and significant losses, including the liquidation of your positions; and (e) potential regulatory or legal issues affecting blockchain transactions or their enforceability. These Terms are not intended to, and do not, create or impose any fiduciary duties on the Company. To the fullest extent permitted by law, you acknowledge and agree that the Company owes no fiduciary duties or liabilities to you or any other party based on your use of the Interface. To the extent that any such duties or liabilities may exist at law or in equity, you hereby irrevocably disclaim, waive, and eliminate such duties and liabilities. 2.5 By using the Interface, you represent and warrant that all digital assets you use are legally obtained and under your sole control. You are solely responsible for securing your private keys, wallet credentials, and other sensitive information related to your interaction with the Interface or, through it, NitroX. The Company shall have no liability for any loss, damage, or unauthorized access resulting from your failure to secure such credentials. You agree that the only duties and obligations the Company owes you are those set out expressly in these Terms. ### 3. PROHIBITED ACTIVITY 3.1 You agree not to engage in, or attempt to engage in, any of the following categories of prohibited activity in relation to your access and use of the Interface: 3.1.1 Intellectual Property Infringement. Activity that infringes or violates any copyright, trademark, service mark, patent, right of publicity, right of privacy, or other proprietary or intellectual property rights under applicable law. 3.1.2 Cyberattack. Activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including, but not limited to, the deployment of viruses and denial of service attacks, phishing schemes or malicious code. 3.1.3 Fraud and Misrepresentation. Activity that seeks to defraud us or any other person or entity, including, but not limited to, providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of another, or impersonating any person, entity, or system. 3.1.4 Market Manipulation. Activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including, but not limited to, manipulating trading volumes or prices through coordinated actions, such as wash trading, spoofing, or any other practice intended to deceive market participants. 3.1.5 Circumvention of Restrictions. Activity that attempts to bypass, evade, or circumvent any restrictions imposed by the Interface or the Company. This includes but is not limited to: (a) using technologies such as VPNs, proxies, or other methods to conceal your location; (b) making false statements or misrepresentations about your residency, citizenship, or compliance with applicable laws; or (c) engaging in any other activity designed to evade the restrictions set forth in these Terms or applicable laws. By accessing or using the Interface, you represent and warrant that you are not a Restricted Person as defined in these Terms. 3.1.6 Money Laundering and Sanctions Violations. Activity that involves or facilitates money laundering, terrorism financing, proliferation financing, or any other illegal financial activity, including the use of the Interface to engage in or support transactions prohibited by applicable sanctions laws or regulations. 3.1.7 Exploitation of Vulnerabilities. Activity that exploits any errors, bugs, vulnerabilities, or unintended features of the Interface, NitroX, or any associated code, including attempts to gain any unauthorized access or manipulate transactions. 3.1.8 Automated or High-Frequency Abuses. Activity that employs bots, scripts, or other automated methods to interact with the Interface in ways that exceed reasonable usage, bypass rate limits, cause denial-of-service conditions, or disrupt the normal functioning of NitroX or related systems. 3.1.9 Manipulation of Leverage and Liquidation Processes. Activities designed to exploit vulnerabilities in the leverage or liquidation mechanisms of NitroX, including, but not limited to, coordinated efforts to distort market pricing, manipulate protocol weaknesses, or create artificial disruptions. 3.1.10 Any Other Unlawful Conduct. Activity that violates, attempts to violate, or facilitates the violation of any applicable law, regulation, rule, or governmental order, including, but not limited to, those relating to financial crimes, data protection, intellectual property, or consumer protection. 3.2 By engaging in any prohibited activity, whether intentional or inadvertent, you agree to indemnify and hold harmless the Indemnified Parties (as defined in Section 9 (Indemnity)) from and against any and all claims, damages, losses, liabilities, costs, and expenses, including reasonable legal fees, arising out of or related to such activity, as further described in Section 9 (Indemnity). ### 4. NO PROFESSIONAL ADVICE 4.1 Any information provided by the Interface is for informational purposes only and should not be construed as professional, technical, operational, investment, or other advice. The Company does not evaluate or monitor the suitability of trading activities for users or provide any advice on the consequences of interacting with decentralized financial systems, including perpetual futures trading. You should not take, or refrain from taking, any action based on any information contained on the Interface, or any other information that we may make available at any time. 4.2 Any content, information, or data made available through the Interface may be incomplete, outdated, or subject to other inaccuracies. You are solely responsible for verifying the accuracy and relevance of such information before making any decisions or taking any action. Before you make any financial, legal, technical, operational, or other decisions involving the Interface, you should seek independent professional advice from an individual who is licensed and qualified in the area for which such advice would be appropriate. 4.3 Nothing in these Terms, or provided by the Interface, establishes a fiduciary, advisory, or client relationship between the Company and any user. The Company explicitly disclaims any duty to provide advice, updates, or corrections to information accessed through the Interface. 4.4 You acknowledge and agree that you are solely responsible for determining, reporting, and paying any taxes applicable to your use of the Interface. The Company makes no representations regarding your tax obligations and strongly recommends consulting with a qualified tax advisor to ensure compliance with all applicable laws. ### 5. PROGRAMS 5.1 The Company may, from time to time, in its sole discretion, make certain programs, special offers, challenges, bonuses or other promotions available to participants (each a "Program", and collectively, "Programs"). The terms and conditions applicable to any such Program will be determined by the Company in its sole discretion and may be communicated to participants in conjunction with any such Program. 5.2 Because any terms and conditions associated with such Programs may differ from or supplement these Terms, you should read any such additional terms and conditions carefully before participating in any Program. In the event of a conflict between any Program terms and these Terms, such Program terms shall prevail. For the avoidance of doubt, any provisions of these Terms that do not conflict with the Program terms shall remain applicable. 5.3 The Company reserves the right to modify, suspend, or discontinue any Program at any time without notice or liability to participants in such Program. Participation in any Program is entirely voluntary, and the Company makes no guarantee as to the availability, rewards, or functionality of any Program. 5.4 You acknowledge and agree that any benefits earned under a Program: (a) have no cash value unless explicitly stated otherwise; (b) may be subject to additional conditions for redemption; (c) are not guaranteed and may be canceled or forfeited at the Company's sole discretion; and (d) are subject to applicable laws and regulations, which may restrict or prohibit participation in certain jurisdictions. The Company reserves the right to modify or cancel any benefits if compliance with applicable laws requires such actions, and, at its sole discretion, to evaluate compliance retroactively and take such remedial actions as it deems necessary. ### 6. LIMITATIONS, RESTRICTIONS, AND OTHER TERMS 6.1 The Company's determinations regarding the eligibility of any user to access or participate in features of the Interface, as well as any questions or disputes arising from a user's use of the Interface or any applicable rules or restrictions, shall be final and binding and not subject to challenge or appeal. 6.2 Without notice to you, the Company reserves the right to suspend or terminate your participation in any feature on the Interface in its sole discretion, including, but not limited to, cases where the Company determines or suspects that your use of the Interface is unauthorized, deceptive, fraudulent or unlawful; intentionally subverts the purposes of the Interface; or would require suspension or termination to comply with applicable laws, regulations or legal orders. 6.3 The Interface does not impose any fees; however, fees may be incurred on NitroX when you interact with it through the Interface. You acknowledge and agree that you are solely responsible for paying all such fees, and that you understand and accept that the cost and speed of transacting with blockchain-based systems is variable and may increase at any time. For the avoidance of doubt, unless otherwise agreed by the parties in writing, the Company shall not be responsible or liable for any fees incurred in your use or access of the Interface or NitroX through the Interface, or any other third-party application. 6.4 Transactions processed by NitroX are irreversible. The Company assumes no liability for errors or omissions made during transaction confirmations on NitroX, including accidental transmissions or incorrect wallet interactions. By accessing and using the Interface, you represent that you are financially and technically sophisticated such that you understand the inherent risks associated with using cryptographic and blockchain-based systems. 6.5 The Company is not responsible for any problems or technical malfunction of any telephone, internet or blockchain network or lines, online systems, servers, providers, computer equipment, software, or messaging platform, or as a result of technical problems or traffic congestion on the internet, any website, or any application, or any combination thereof, including, without limitation, any resulting error in computing qualifying actions or any unavailability of Interface features, or any injury or damage to any participant's or any other person's computer or mobile device related to or resulting from participation in features available through the Interface. If, for any reason, the Interface is not capable of running as planned, including due to errors of any kind or nature, infection by computer viruses, bugs, tampering, unauthorized intervention, fraud, technical failures, or any other causes beyond the control of the Company which corrupt or affect the administration, security, fairness, integrity, or proper conduct of the Interface features, the Company reserves the right in its sole discretion to cancel, terminate, modify, or suspend the Interface features or otherwise respond to the circumstances as the Company deems appropriate. ### 7. MODIFICATIONS TO THE INTERFACE, PROGRAMS, AND TERMS OF USE 7.1 The Company reserves the right to modify, update, and/or discontinue, in whole or in part, either temporarily or permanently, any portion of the Interface, any Program made available through the Interface, and/or any related policy, FAQ, and/or guidelines, at any time in its sole discretion. The Company shall not be liable for modifications, suspensions, or discontinuance of the Interface or any features made available through the Interface. While the Company shall not be liable for any such modifications, suspensions, or discontinuance, the Company will use reasonable efforts to provide prior notice of changes. In principle, notice of at least seven (7) days will be given before any changes to these Terms take effect, and in the case of material changes, notice of at least thirty (30) days will be given. If advance notice is not reasonably practicable, notice will be provided promptly by posting the revised Terms on the Interface. 7.2 Unless otherwise specified, the Company will use reasonable efforts to provide advance notice of any changes or modifications to these Terms, at least seven (7) days prior to their effectiveness, and in the case of material changes, at least thirty (30) days, by posting the revised Terms on the Interface or by other reasonable means of communication. For the avoidance of doubt, posting the revised Terms on the Interface shall be deemed to constitute valid and sufficient notice of such changes. If we change or modify these Terms, we will revise the "last updated" date located at the top of these Terms, which you may refer to in order to confirm the current version. If you continue to participate in the Interface in any way after a change to these Terms, you will be deemed to have read, understood, and unconditionally consented and agreed to such changes. You should review these Terms and applicable policies and guidelines frequently to understand the terms and conditions that apply to your use of the Interface. If you do not agree to these Terms or revised Terms, you must cease using the Interface immediately. ### 8. RELEASE OF CLAIMS 8.1 You expressly agree that you assume all risks in connection with your access and use of the Interface and your interaction with NitroX through the Interface. These risks include, but are not limited to, risks associated with: (a) coding errors, failures, vulnerabilities or exploits; (b) network delays, disruptions, forks or unexpected outcomes resulting from decentralized governance or protocol upgrades; (c) volatility, illiquidity, or total loss of digital assets, especially when engaging in leveraged or perpetual futures trading; (d) market manipulation, slippage, or other inefficiencies; (e) liquidation risks due to the use of leverage or adverse market movements; (f) unauthorized access, fraud, phishing or other malicious acts by third-parties; and (g) any failure of NitroX or its supporting infrastructure, including cross-chain bridges. 8.2 The Company does not and cannot guarantee the security, performance, or reliability of NitroX, its code, or any associated blockchain networks, protocols or tools. You understand that the Company is not a party to, nor does it control or facilitate, any transactions or trading activity conducted on NitroX. 8.3 By using the Interface, you expressly waive and release the Company from any and all liability, claims, causes of action or damages arising from or in any way relating to: (a) your use of the Interface, including any errors, delays, or interruptions in its operation; (b) your interaction with NitroX through the Interface, including in respect of any trading losses, liquidation events, or other financial impact; (c) any reliance on market data, token values, or information displayed on the Interface, which may be inaccurate or delayed; (d) third-party integrations, tools, or services utilized in connection with the Interface or NitroX; and (e) any regulatory, tax, or legal consequences arising from your use of the Interface or participation in activities on NitroX through it. 8.4 By using the Interface to engage in trading or other activities on NitroX, you acknowledge the inherent risks associated with decentralized, leveraged financial instruments and waive any recourse against the Company for any losses or damages incurred. ### 9. INDEMNITY 9.1 You agree to hold harmless, release, defend, and indemnify us and our officers, directors, employees, contractors, agents, affiliates, and subsidiaries (collectively, "Indemnified Parties") from and against any and all claims, damages, obligations, losses, liabilities, costs, and expenses (including, but not limited to, reasonable attorney's fees and court costs) arising out of or related to: (a) your access to or use of the Interface; (b) your interaction with NitroX through the Interface, including, but not limited to, trading activities, leveraged positions or liquidation events; (c) your violation of any term or condition of these Terms, the right of any third-party, or any other applicable law, rule, or regulation; (d) your participation in any prohibited activities described in Section 3 (Prohibited Activities); (e) any other party's access to and use of the Interface or, through the Interface, NitroX, using any device or account that you own or control, whether or not caused by you; (f) any third-party services, tools, or platforms you use in connection with the Interface or NitroX through the Interface; and (g) any false, misleading, or fraudulent statements or omissions made by you in connection with your use of the Interface, or access to NitroX through the Interface. 9.2 If any claim or demand is brought against the Indemnified Parties arising out of your use of the Interface, or through the Interface, NitroX, you agree to provide prompt and full cooperation with the Company in defending such claims or demands, including making reasonable efforts to mitigate any potential damages. The Company will make reasonable efforts to provide notice to you of any such claim, suit, or proceeding, provided it has sufficient contact information to do so. 9.3 The Company reserves the right to assume exclusive control of the defense or settlement of any matter subject to indemnification at your expense. You agree not to settle any such matter without the prior written consent of the Company. ### 10. LIMITATION OF LIABILITY 10.1 Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, affiliates, or subsidiaries be liable to you for any direct, indirect, punitive, incidental, special, consequential, or exemplary damages, including, but not limited to, damages for loss of profits, goodwill, use, data, or other intangible property, arising out of or relating to any access or use of the Interface, or your interaction with NitroX through the Interface, or participation in any trading or financial activity conducted via such interaction with NitroX, nor will we be responsible for any damage, loss, or injury resulting from hacking, tampering, or other unauthorized access or use of the Interface or its supporting infrastructure. 10.2 We assume no liability or responsibility for any: (a) errors, bugs, or vulnerabilities in NitroX, including, but not limited to, issues in code, cross-chain bridges, oracles, or perpetual futures mechanisms; (b) errors, mistakes, or inaccuracies of content; (c) personal injury or property damage, of any nature whatsoever, resulting from any access or use of the Interface; (d) unauthorized access or use of any secure server, database or wallet in our control, or the use of any information or data stored therein; (e) interruption or cessation of function related to the Interface; (f) bugs, viruses, trojan horses, or the like that may be transmitted to or through the Interface; (g) errors or omissions in, or loss or damage incurred as a result of the use of, any content made available through the Interface; (h) third-party actions, including fraud, phishing, or market manipulation impacting users of NitroX or the Interface; (i) failures or disruptions caused by third-party services, platforms, or tools connected to the Interface or NitroX; or (j) unclaimed rewards, tokens, or other benefits associated with any Program. 10.3 Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, affiliates, or subsidiaries be liable to you for any claims, proceedings, liabilities, obligations, damages, losses, or costs in an amount exceeding $100.00. This limitation of liability applies regardless of whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, and even if we have been advised of the possibility of such liability. 10.4 Some jurisdictions do not allow the exclusion of certain warranties or the limitation or exclusion of certain liabilities and damages. Accordingly, some of the disclaimers and limitations set forth in these Terms may not apply to you. This limitation of liability shall apply to the fullest extent permitted by law. ### 11. ARBITRATION AND CLASS ACTION WAIVER 11.1 You and the Company agree to waive the right to have any and all disputes or claims arising from these Terms, your use of, or access to, the Interface, or any other disputes with the Company ("Disputes") resolved in a court. Instead, all Disputes will be resolved through binding arbitration. 11.2 All arbitration proceedings will be conducted solely on an individual basis. No Dispute may be brought as a class action or representative action, whether in arbitration or any other forum. 11.3 You agree to notify us, in writing, of any Dispute within thirty (30) days of when it arises so that the parties can attempt, in good faith, to resolve the Dispute informally. Notice to the Company shall be provided by sending an email to support@alphasec.trade. Your notice must include: (1) your name, postal address, and email address; (2) a description of the nature or basis of the Dispute; and (3) the specific resolution or action that you are seeking. If the Dispute cannot be resolved informally within thirty (30) days of receipt, either party may commence arbitration. 11.4 These Terms are governed by and will be construed under the laws of the British Virgin Islands, without regard to its conflict of law provisions. Any Dispute that remains unresolved after the informal resolution process will be finally resolved by arbitration under the rules of the London Court of International Arbitration (LCIA), as amended from time to time, which are incorporated by reference into this clause. Arbitration will be conducted in English, in London, United Kingdom, by a single arbitrator appointed under the LCIA Rules. Each party shall bear its own costs, unless otherwise determined by the arbitrator. Neither you nor the Company may bring a Dispute in any court located in the United States of America. 11.5 The arbitrator shall have the exclusive authority to resolve all procedural and substantive disputes related to these Terms and may grant any remedy that would otherwise be available in court. Arbitration will be conducted solely on an individual basis, and the arbitrator may not consolidate claims, preside over a representative proceeding, or adjudicate claims on behalf of any other party. ### 12. MISCELLANEOUS 12.1 Entire Agreement. These Terms constitute the entire agreement between you and us and supersede any and all prior or contemporaneous written or oral agreements, communications or other understandings (if any) relating to the subject matter of these Terms. 12.2 Privacy Policy. You agree to the collection, use, storage, and disclosure of your data in accordance with our privacy policy, which is incorporated herein by reference and is available athttps://alphasec.trade/privacypolicy. 12.3 Assignment. You may not assign or transfer any of your rights or obligations under these Terms, without our express prior written consent, including by operation of law or in connection with any change of control. We may assign or transfer any or all of our rights or obligations under these Terms, in whole or in part, with or without notice or obtaining your consent or approval. 12.4 Severability. If any provision of these Terms shall be determined to be invalid or unenforceable under any applicable rule, law, or regulation, such provision will be changed and interpreted to accomplish the objectives of the provision to the greatest extent possible under any applicable law and the validity or enforceability of any other provision of these Terms shall not be affected. 12.5 Notice. We may provide any notice to you under these Terms using commercially reasonable methods, including using public communications channels. Notices we provide using public communications channels will be effective as of the date of the posting. --- ## Trading Basics # Trading Basics ## What do you need to start trading on Alpha Sec.? To use Alpha Sec., you need either a MetaMask, Trust Wallet, Bitget Wallet, OKX Wallet, Coinbase Wallet, or Safepal. - On desktop: Install the Chrome extensions for supported wallets. Create or import your wallets via the extensions. - On mobile: Download the supported wallet apps. Set up your wallets within the apps. ## How do you sign up for Alpha Sec.? Alpha Sec. requires no traditional registration. Simply visit the Alpha Sec. and click “Connect Wallet.” Once your wallet is connected, your account is instantly activated. No email, password, or KYC is needed. ## How do you deposit into Alpha Sec.? To deposit assets into Alpha Sec., you can follow stages below: - Connect your wallet. - Click the Deposit button on the top navigation bar. - Choose a supported token listed on Alpha Sec.. - Enter the amount. - Confirm the transaction in your wallet. Your funds will be bridged from Kaia Layer 1 to Optimistic Rollup Layer 2 via the Alpha Sec. interface. > **Notes:** Ensure your wallet holds a sufficient token balance and KAIA for the deposit gas fee. Gas fees are only charged during deposit. All trades on Alpha Sec. are gas-free once assets are deposited. ## How do you withdraw from Alpha Sec.? To withdraw assets from Alpha Sec., you can follow stages below: - Go to the Portfolio page. - Click Withdraw button on the overview section. - Enter the amount and confirm the transaction. - The selected assets will be bridged from Optimistic Rollup Layer 2 back to Kaia Layer 1. - Once the withdrawal is confirmed, assets will appear in your Kaia Wallet on Layer 1. > **Notes:** You must have a sufficient Alpha Sec. balance for the selected token. 1 USDT is required in your wallet to cover the withdrawal fee. --- ## DEX Usage # DEX Usage ## How do I transfer tokens to and from Alpha Sec.? The Alpha Sec Transfer Gateway is the official mechanism for moving assets between Alpha Sec. and the Kaia network. - Connect your wallet to Alpha Sec. - Use the Deposit and Withdraw features of Alpha Sec. - Alpha Sec. abstracts all bridging logic, no separate interface is required Assets are transferred securely and verifiably between Kaia and Alpha Sec. through canonical gateway contracts. ## Can I send assets from Alpha Sec. to a CEX? Direct withdrawals from Alpha Sec. to CEXs are not currently supported. To send assets to a CEX: - First, withdraw the assets to Kaia mainnet using the Alpha Sec interface - Then transfer them from your wallet to a CEX that supports KAIA or the relevant token ## Do I need to pay gas fees when trading on Alpha Sec. DEX? No. All trading activity within Alpha Sec. is gasless. - No gas fees are charged for placing or canceling orders - No gas is required for trade matching, settlement, or transfers between users This is different from most Layer 1 DEXs, where every interaction (like submitting an order or canceling it) incurs a transaction fee. ## Is Alpha Sec. secure? Yes. Alpha Sec is built on a custom rollup-inspired architecture designed for both performance and security. - Transactions are executed on Alpha Sec’s dedicated Layer 2 engine - State roots are periodically submitted to Kaia network for verification and settlement - All execution is on-chain and audit-friendly, with no centralized operator dependencies ## How can I view my transaction history on Alpha Sec.? Transaction history can be accessed via the Alpha Sec. Explorer, which includes: - Transaction logs per wallet - Trade-level execution records - Order submission, fill, and cancellation events - Gasless transaction activity Explorer functionality is integrated directly into the Alpha Sec. interface. --- ## Key Advantages # Key Advantages - **Deep Orderbook Liquidity**: Enables efficient price discovery and scalable execution across market depths. - **Low Fees & Revenue Sharing**: Aligns incentives through competitive rates and user-partner revenue distribution. - **CEX-Level Performance**: Delivers low-latency, high-throughput trading with real-time reliability. - **Developer-Friendly Architecture**: Provides modular SDKs and intuitive APIs for seamless integration and iteration. - **Gasless Trading UX**: Offers a frictionless experience with zero direct gas costs to users. - **Self-Custody Arcchitecture**: Ensures full user control of assets without intermediaries or custodians. - **Fully On-Chain Execution**: Guarantees transparent, verifiable, and audit-ready operations at every layer. --- ## Our Mission # Our Mission **A one-of-a-kind orderbook DEX that unites unmatched performance, reliability, and decentralization.** Alpha Sec. is a next-generation orderbook DEX designed for serious traders. We bring the speed, clarity, and precision of centralized exchanges into a fully transparent, self-custodial, on-chain environment. Our goal is simple: help traders discover Alpha faster, execute with confidence, and manage risk without compromise. From zero transaction fees and click-to-trade UX to deep liquidity and powerful order types, every part of Alpha Sec. is built to empower execution. What makes this possible is our underlying performance layer: a custom-built Optimistic Rollup based on Arbitrum Nitro, deployed on the high-throughput Kaia mainnet. It enables ultra-low latency, over 100,000 TPS capacity, and sub-10ms execution times. Kaia was chosen not just for its speed, but for its commitment to decentralization and security. As a scalable, EVM-compatible Layer 1 with transparent data availability, Kaia provides the trust foundation that Alpha Sec. is built on. Alpha Sec. is not just another DEX. It’s a purpose-built trading engine where performance meets sovereignty. From day one, it’s fully on-chain, modular, and designed to evolve. And while we’re the first protocol on this execution layer, the infrastructure is open for others to build on too. --- ## Roadmap # Roadmap --- ## Transfer Gateway # Transfer Gateway The Alpha Sec. Transfer Gateway is a secure, high-throughput asset transfer system connecting Kaia Layer 1 and Alpha Sec.’s Optimistic Rollup Layer 2. It is purpose-built to support Alpha Sec.’s fully on-chain, orderbook-driven trading infrastructure. Built on a customized rollup framework, the Transfer Gateway ensures verifiable asset movement across layers while preserving decentralization, transparency, and security. ## Deposits (Kaia → Alpha Sec. L2) - **Verification & Finality**: When users deposit assets into Alpha Sec., the transaction is confirmed on Kaia Layer 1 and processed by the Transfer Gateway. Deposits are finalized once reflected in the rollup state and included in the sequencer’s canonical chain. - **Settlement Time**: Deposits are generally processed within a minute and reflected immediately in the user’s Alpha Sec. wallet. - **Supported Assets**: The Transfer Gateway currently supports all trading assets available on the Alpha Sec. DEX. ## Withdrawals (Alpha Sec. L2 → Kaia) - **Request & Processing**: Users can initiate withdrawals from Alpha Sec. to Kaia Layer 1. Withdrawal requests are submitted to the Transfer Gateway, confirmed within the rollup state, and relayed to Kaia. - **Fast Finality**: Unlike traditional optimistic rollups that enforce a 7-day challenge window, Alpha Sec. leverages Arbitrum’s AnyTrust framework and fast withdrawal mechanisms. This enables near-instant withdrawals while preserving cryptoeconomic security. ## Security & Governance - **Protocol-Verified Logic**: The Transfer Gateway operates through audited smart contracts and transparent rollup logic. All transactions are verifiable on-chain, and state transitions can be challenged if invalid. - **Emergency Controls**: In cases of abnormal activity or protocol-level alerts, transfer operations may be temporarily paused to ensure user safety. These controls are governed transparently and will evolve toward greater decentralization. - **Audits & Monitoring**: All gateway contracts are regularly audited. Transaction logs, proofs, and cross-layer messages are openly accessible to maintain trust and accountability. --- ## Matching Engine # Matching Engine Alpha Sec. is powered by a fully on-chain Matching Engine designed for high-performance, deterministic, and transparent trade execution. Unlike systems that rely on off-chain matchers or centralized sequencing, Alpha Sec. executes all order matching logic directly within the rollup’s verifiable on-chain environment. ## On-Chain Matching Process - **Order Submission**: Traders submit actions such as placing or canceling orders through Alpha Sec.’s user interface or API endpoints. - **Deterministic Ordering**: Transactions are processed in the canonical order in which they are confirmed within the rollup block. - **Matching Logic**: The Matching Engine evaluates the updated orderbook on-chain and matches orders based on strict price-time priority. - **Settlement** : All matched trades are written to the rollup state and finalized on Kaia mainnet guaranteeing tamper-proof execution. This architecture ensures: - Fully deterministic, globally consistent trade outcomes - Front-running and MEV resistance through transparent ordering - On-chain auditability of every trade and match decision ## Matching Rules & Market Structure The Matching Engine enforces key rules to maintain fairness and market integrity: - **Price-Time Priority**: Orders are matched by best price first, and among identical prices, earlier transactions are matched first. - **Tick Size**: Defines the minimum price increment (e.g., 0.01 USDC), preventing excessive fragmentation of the orderbook. - **Lot Size**: Sets a minimum order size (e.g., 10 KAIA), reducing spam and conserving on-chain resources. These constraints create a high-integrity trading environment optimized for both retail and institutional strategies. --- ## Overview # Overview Alpha Sec. is a next-generation orderbook DEX built to deliver the execution speed and precision of centralized exchanges while remaining entirely on-chain, self-custodial, and transparent. Powered by a custom Optimistic Rollup Layer 2 and deeply integrated with the Kaia mainnet, Alpha Sec. introduces a modular, verifiable trading infrastructure that combines performance with decentralization. This overview highlights the four core protocol components that make Alpha Sec. a purpose-built, high-integrity trading environment. - Fully On-Chain Execution - Zero Gas Fees for Users - High Throughput - Sub-Second Latency ## Transfer Gateway The Transfer Gateway enables seamless, high-throughput asset transfers between Kaia mainnet and Alpha Sec. Layer 2. - Fast, low-friction deposits and withdrawals with fast finality - Secure, auditable, and transparently executed via on-chain contracts - Supports all trading assets available on Alpha Sec. ## Matching Engine The Matching Engine executes all trades on-chain with deterministic and transparent logic. - Price-time priority matching within the rollup - Anti-spam rules like tick size and lot size enforcement - Full MEV resistance and auditability ## Session Wallet The Session Wallet enables gasless, real-time trading while preserving self-custody. - No repeated wallet approvals - Temporary and scoped to your session - Private keys never exposed or transferred ## Tokenomics The protocol token will be introduced once Alpha Sec.’s infrastructure is battle-tested in production. - Powers governance and ecosystem participation - Supports trader, LP, and builder incentives - May be used in future safety and risk mitigation mechanisms ## Summary Alpha Sec. is more than a DEX. It is a fully on-chain, high-performance trading layer designed to bring fairness, speed, and transparency to everyone from retail traders to institutional strategies. As Alpha Sec. evolves, these core components will serve as the foundation for a decentralized, composable, and permissionless trading ecosystem. --- ## Session Wallet # Session Wallet The Session Wallet is a temporary, device-bound signing layer that activates when you connect your wallet to Alpha Sec. It enables secure, gasless, and frictionless trading throughout your session without requiring on-chain confirmations for every action. ## Delegated Local Signing When you connect your wallet, a Session Wallet is automatically created for your current session. You temporarily delegate signing authority to this session to enable real-time interaction with the DEX. **Key characteristics**: - **Session-scoped**: Active only during the current session and tied to your device - **Non-custodial**: Your original private key is never exposed or transferred - **No wallet popups**: Trade, cancel, and manage positions instantly without repeated wallet confirmations **Scope of Authorization**: - Session Wallet authorization is strictly limited to DEX trading activities. - It cannot be used independently for deposits, withdrawals, or any direct asset transfers. This approach preserves Alpha Sec.’s low-latency execution experience while maintaining full user control. ## Self-Custody by Defualt Session Wallets are designed to uphold the principles of decentralization and user ownership: - **User-controlled**: No third party, including Alpha Sec., can access or move your funds - **Ephemeral**: The session expires automatically and leaves no persistent authorization - **Auditable**: All actions signed via the Session Wallet are verifiable on-chain With Session Wallets, Alpha Sec. delivers a fast and seamless trading experience—without compromising self-custody or security. ## Sessions Page Guide The Sessions page allows you to manage all active and past Session Wallets. From this page, you can: - **View** all active Session Wallets, including name, address, creation date, and expiration date. - **Create** new Session Wallets after making a deposit (up to 180 days validity). - **Extend** an existing Session Wallet’s validity period through the update modal. - **Delete** a Session Wallet, which immediately expires it. Wallets stored on the current device are labeled **“This Device”** and pinned to the top. Expired Session Wallets are automatically removed from the list. --- ## Tokenomics # Tokenomics Alpha Sec plans to introduce a protocol token once its infrastructure roadmap has been sufficiently validated in production. The token will play a central role in decentralizing the protocol, supporting the trading ecosystem, and enhancing system-level resilience. Key design objectives include: - **Protocol Governance**: The token will be used to participate in decision-making. - **Inclusive Participation**: The token supports community-aligned contributions from traders, liquidity providers, and builders across the Alpha Sec ecosystem. - **Security & Risk Mitigation**: The token may serve as a part of safety mechanisms to help offset user losses caused by protocol-level bugs, unexpected failures, or critical security incidents. A full tokenomics breakdown, including allocation, emissions, and utility models, will be released in a dedicated update closer to the token launch.