Skip to content

Chapter 4: Technical Roadmap and Core Contract Mechanisms

4.1 Overall Technical Architecture

Architecture Design Philosophy

The MSX platform adopts "off-chain matching + on-chain settlement" as its core architectural philosophy, building a layered and modularized technical system around four major goals: "high concurrency, low latency, on-chain verifiability, and scalability." This architecture processes high-frequency trading off-chain and ensures asset security on-chain, balancing the transparent attributes of decentralized finance with traditional finance-grade trading performance, providing underlying technical support for stock tokenization (RWA) trading.

The system is vertically divided into five core business layers: user layer, matching layer, settlement layer, custody/cross-chain layer, and monitoring layer. Horizontally, it integrates supporting capabilities such as compliance auditing, real-time monitoring, and data security, forming a technical framework of "vertical efficient circulation and horizontal security coverage," ensuring efficiency and security balance throughout the trading process.

Underlying Network and Technology Stack: EVM-Compatible Layer 2 Support

On top of the overall architecture, MSX adopts EVM-compatible Layer 2 blockchains as on-chain infrastructure to achieve a decentralized settlement environment with both high performance and low cost. The platform's core trading logic is deployed on Base chain and BSC chain, implementing high-speed asset circulation and secure settlement through multi-chain collaboration and cross-chain bridge technology.

High-Performance Guarantee

The platform leverages Base chain's high throughput (TPS) and fast data finality to support high-frequency trading and second-level settlement needs for stock tokenized assets, achieving low-latency coordination between matching engine and contract settlement layer.

Low-Cost Advantage

Compared to Ethereum mainnet, both Base and BSC have lower Gas fees, making batch matching and high-frequency settlement possible, significantly reducing user trading costs and system operating expenses.

Security and Transparency

All transaction data and contract states inherit EVM's underlying security mechanisms, and through fraud proofs and multi-signature permission control, ensure transparent verification and traceability of off-chain matching results, ensuring system decentralization and compliance trustworthiness.

System Layered Design and Function Description

The MSX system architecture is centered on layered design, clearly distinguishing the responsibilities and communication methods of each layer. Each layer achieves decoupling through independent communication interfaces and security gateways, ensuring system stability and scalability in high-concurrency environments.

The following table shows the five core levels, functional modules, interface forms, and corresponding responsibilities of MSX's technical architecture:

LayerComponent ModulesInterface FormsFunctional Logic
User LayerUser ApplicationsHTTPS (Web/Mobile)
RESTful/WebSocket (API)
Provides multi-terminal access entry, covering trading operation needs of retail and institutional users
GatewayFrontend HTTPS
Backend Internal RPC
Handles user authentication, request throttling, routing distribution, and data encryption, serving as the unified platform access point, routing orders to internal event bus after compliance
Matching LayerEvent BusKafka/RocketMQ ProtocolImplements asynchronous distribution and load balancing of high-concurrency order flows based on message queues
Matching Service ClusterInternal RPC (Receive Orders)
Event Bus (Push Matching Results)
Adopts event-driven + lock-free queue architecture, maintains order books in full memory and executes matching, ensuring sub-millisecond processing latency
Risk Control ServiceInternal RPC (Matching Interaction)
HTTP (Connect to Monitoring)
Real-time verification of margin sufficiency, position limits, and account risk exposure, triggering automatic position reduction or forced liquidation logic when thresholds are reached
Settlement LayerBatch Submission ServiceInternal RPC (Receive Matching Results)
Web3 (Call Smart Contracts)
Aggregates and batch packages matching results, generating on-chain verifiable settlement batches (Merkle Root)
Layer 2 ContractsEVM-Compatible Solidity Contract InterfaceResponsible for executing on-chain settlement and position updates, confirming off-chain matching results on blockchain, generating immutable records
Custody/Cross-Chain LayerCustody Institution InterfaceHTTPS (API Connect to Custody System)
On-chain Query (On-chain Reserve Verification)
Connects to custody institutions, verifies 1:1 pegging relationship between stock tokens and physical stocks, ensuring real and redeemable assets
Monitoring LayerMonitoring SystemHTTP/WebSocket, connecting all system levelsResponsible for full-chain operation status monitoring, real-time tracking and anomaly alerting of key links, supporting automated alerting and trace analysis

System Workflow

Based on the above layered architecture, the trading lifecycle of MSX from user order placement to on-chain settlement follows the following core process:

  1. Users initiate trading orders through web or mobile terminals
  2. Gateway module verifies identity and forwards to matching service cluster
  3. Matching service completes order matching and pushes results to risk control service module
  4. Risk control module verifies margin and position security, then submits trading results to Batch Submission service
  5. Batch service uniformly packages transaction data and performs on-chain settlement through Layer 2 smart contracts
  6. Custody layer synchronously updates backed asset information
  7. Monitoring layer tracks data status throughout

4.2 Core Matching Engine

The matching engine is the core module of MSX's trading system, designed with goals of "extreme performance, fair matching, and controllable risk," supporting order processing and matching needs in high-concurrency scenarios, providing users with low slippage and high responsiveness trading experience.

Architecture Design

Adopts event-driven + lock-free queue architecture, built based on Golang and distributed microservice technology:

Event-Driven

Centers on events such as "new order submission," "order cancellation," and "matching execution," decoupling order flow and matching logic through event bus, avoiding synchronous call bottlenecks.

Lock-Free Queue

Uses components like Disruptor to eliminate thread competition, implementing parallel processing of producers (order receiving threads) and consumers (matching worker threads), supporting hundreds of thousands of orders per second per machine.

Full In-Memory Storage

Order books and user position data are stored in memory, with asynchronous persistence and snapshot mechanisms balancing performance and data security.

Matching Mechanism

Strictly follows the price priority, time priority principle to ensure trading fairness:

Price Priority

Buy orders are sorted from high to low price, sell orders are sorted from low to high price, prioritizing optimal quotes for matching.

Time Priority

When prices are the same, orders are sorted by submission time (microsecond-level timestamps), with earlier submitted orders prioritized for matching.

Incremental Update

Order books adopt red-black tree structure, with new orders or partial fills only incrementally updating nodes, avoiding full refresh, implementing instant long-short position hedging.

Performance and Risk Control Guarantee

Performance Metrics

Order processing latency at microsecond level, supports horizontal scaling (adding worker nodes can linearly improve throughput), large transactions (over $1 million) slippage rate < 0.1%.

Risk Control

Real-time linkage with risk control service, verifying margin sufficiency and position limits upon order submission; triggering automatic position reduction in extreme market conditions, prioritizing liquidation of high-leverage, low-liquidity positions, preventing risk spread.

4.3 Core Contract Mechanisms

Perpetual Contract Core Contracts: Liquidation and Funding Rates

Perpetual contracts, as core products of derivative trading, have their operating logic fully defined by smart contracts, ensuring rules are immutable and execution requires no human intervention. The liquidation mechanism achieves transparent calculation through quantitative formulas, ensuring balanced rights for both longs and shorts.

Funding Rate Contract

Maintains linkage between perpetual contract prices and underlying spot prices. Through periodic funding rate adjustments, avoids contract prices deviating from spot prices due to market sentiment, ensuring derivative prices are pegged to underlying asset values.

Funding rate (F) is automatically calculated every 8 hours, with the following formula:

F = α × (P_contract - P_index) / P_index + β × (P_TWAP - P_index) / P_index

Variable Description:

  • P_contract: Current perpetual contract market fair price (weighted calculation from optimal bid/ask prices in order book)
  • P_index: Underlying stock token spot index price (aggregates real-time quotes from major exchanges such as NASDAQ and NYSE, taking median)
  • P_TWAP: Time-Weighted Average Price of contract prices over the past 8 hours, smoothing short-term price fluctuations
  • α: Contract price deviation coefficient (default 0.7, adjusting immediate price deviation impact weight)
  • β: Historical price deviation coefficient (default 0.3, adjusting medium to long-term price trend impact weight)

4.4 Liquidation Contract

When user margin ratio falls below the maintenance margin ratio threshold, an automated liquidation process is triggered, quickly disposing of risk positions to prevent 穿仓 (穿倉) leading to system losses, while ensuring liquidation efficiency through quantitative incentive mechanisms.

User Real-Time Margin Ratio Calculation

User real-time margin ratio (M) calculation formula:

M = Equity / InitialMargin × 100%

Variable Description:

  • Equity: User account equity (available balance + unrealized profit/loss from positions)
  • InitialMargin: Initial margin (determined based on leverage multiples, e.g., 20x leverage initial margin ratio is 5%, i.e., InitialMargin = Position Value × 5%)

Trigger Rules

When M < M_maintenance (maintenance margin ratio, default 2% for 20x leverage), the liquidation contract automatically marks the position as "pending liquidation status" and opens the liquidation interface for external liquidation bots to call.

Decentralized Liquidation Mechanism and Incentive Calculation

Liquidation Execution Logic

External liquidation bots call the liquidation contract by sending opBNB on-chain transactions. The contract executes liquidation according to the "liquidation price priority" principle—prioritizing placing orders close to P_index. If not executed within 30 seconds, forced liquidation is performed as follows:

  • Long position liquidation: P_index × (1 - γ)
  • Short position liquidation: P_index × (1 + γ)

Where γ is the liquidation slippage coefficient, dynamically adjusted based on underlying liquidity.

Liquidation Reward Calculation

Liquidator rewards (R) adopt tiered calculation, ensuring liquidation efficiency while avoiding excessive incentives.

4.5 Multi-Source Aggregated Oracle Contract and Cross-Chain Bridge

Multi-Source Aggregated Oracle

To ensure accuracy of derivative pricing and liquidation, a multi-source aggregated price feed mechanism is adopted:

Data Sources

Integrates self-built oracles, third-party service providers, and major exchange APIs, covering stock spot and cryptocurrency prices.

Anti-Manipulation Design

Adopts median price algorithm, sets price fluctuation thresholds (isolates data sources if deviation from median > 5%), preventing single point of failure and price manipulation.

Update Frequency

Updates price data every 1 second, synchronously verifies historical trends, pauses trading when anomalies occur, ensuring data reliability.

Cross-Chain Bridge Contract

Supports secure transfer of stock tokens and mainstream cryptocurrencies across blockchains including Solana, Ethereum, Tron, BNB Chain, Base, etc.:

Security Mechanisms

Adopts combination of multi-signature authentication, on-chain time locks, and asset locking verification schemes to prevent cross-chain risks.

Multi-Chain Management

Unified multi-chain asset management platform, laying foundation for future RWA asset diversified custody and liquidity aggregation.

Released under the MIT License.