← Back to Archive
DeFi / Algorithmic Trading Protocols Case Study

Elektrik DEX

A high-frequency Central Limit Order Book (CLOB) DEX on LightLink L2 featuring TWAP execution and ve-Tokenomics.

NestJS Solidity (Foundry) Redis (Binary Search Trees) The Graph WebSockets EIP-712

Architecture Overview

A hybrid 'Off-Chain Match, On-Chain Settle' architecture. An in-memory Node.js matching engine (backed by Redis) pairs orders instantly, while a high-concurrency transaction queue batches settlements to the Ethereum L2.

The Challenges

O(log n) Matching Engine

Problem

Matching thousands of limit orders requires sorting by Price and Time. Standard database queries are too slow for an exchange engine, and array sorting is O(n log n), which degrades with volume.

Solution

Built a custom In-Memory Matching Engine using Binary Search Trees (BST). This ensures insertion and lookup time complexity stays at O(log n). We used Redis for persistence, serializing the tree state to disk to survive server restarts without losing the order book position.

matchingEngine/index.ts

Smart Wallet Signatures (ERC-1271)

Problem

Institutional traders use Gnosis Safe (Smart Contract Wallets), not simple Private Keys (EOAs). Standard `ecrecover` signature verification fails for smart contracts.

Solution

Implemented a dual-verification signature layer. The protocol checks the signer type: if it's an EOA, it uses ECDSA recovery. If it's a Contract, it invokes the `isValidSignature` method (ERC-1271). This allows DAOs and Multisigs to place Limit Orders and TWAP strategies natively.

AdvancedOrderEngine.sol

High-Frequency Nonce Management

Problem

Settling matched trades involves submitting hundreds of transactions per minute from a single 'Operator' wallet. A single failed transaction or 'stuck nonce' would halt the entire exchange pipeline.

Solution

Engineered a custom 'Transaction Queue' with a semaphore-based concurrency limit (Max 10 parallel Tx). It manages nonces locally, enforcing strict sequential ordering and implementing aggressive gas-price bumping (10% increments) to clear mempool congestion automatically.

transactionQueue.ts

Conditional Order Logic (TWAP)

Problem

Whales cannot dump tokens all at once; they need TWAP (Time-Weighted Average Price) to execute orders in small slices over time. Building this logic on-chain is expensive and complex.

Solution

Developed a 'Composable Order Engine' based on Predicates. Orders are cryptographically signed with 'Conditions' (e.g., 'Only execute if Block.Timestamp > X AND Price > Y'). We use Merkle Proofs to validate these batches on-chain, allowing users to program complex trading strategies that the off-chain 'WatchTower' service executes automatically.

ComposableOrderEngine.sol