A confidential stock trading protocol that enables users to trade real-world stocks using cryptocurrency—combining the liquidity and accessibility of digital assets with the stability of traditional equity markets.
Deployed Contract: 0x5c7B3c7AC4640d5eB9424e93F10F9ab299516333 (Base Mainnet)
- Oracles: Pyth Network, Chainlink
- Frontend: Next.js, React, Scaffold-ETH
- Smart Contracts: Solidity
- Brokerage Integration: Alpaca
- Languages: TypeScript, Solidity
Market fragmentation—driven by regulatory and infrastructure silos—fundamentally limits how users buy, sell, and hold fractional ownership of assets. Today's financial landscape forces participants to choose between two incompatible systems:
Cryptocurrency markets offer freedom, speed, global access, and self-custody.
Traditional equity markets provide stability, deep liquidity, and regulated market structure.
These systems operate in isolation, creating inefficiencies and barriers to capital flow. TradeLayer eliminates this fragmentation by creating a unified market infrastructure that abstracts away the underlying currency and liquidity sources.
Users gain access to:
- Global Markets: Trade equities without off-ramping to fiat currency
- Faster Settlements: Leverage blockchain's near-instant finality
- Reduced Friction: Lower fees and fewer intermediaries
- Privacy Preservation: Confidential order execution
- Self-Custody: Maintain control of digital assets throughout the process
TradeLayer is a confidential stock trading protocol that unifies traditional equity markets and cryptocurrency markets into a single, seamless trading infrastructure. The system enables users to access both on-chain and off-chain liquidity without dependency on specific currencies or jurisdictions, while maintaining comprehensive privacy guarantees.
- Institutional Participants: Confidential execution for large block trades
- High-Volatility Assets: Protection against manipulation in low-cap, high-volatility stocks
- Cross-Border Trading: Simplified access to global equity markets
- Privacy-Focused Traders: End-to-end confidentiality for sensitive trading strategies
- Front-Running Protection: Encrypted order submission prevents mempool observation
- MEV Resistance: Order details concealed until execution
- Information Leakage Prevention: Multi-layer privacy architecture
- Collateralization Guarantees: Cryptographic proof of reserves
The architecture comprises five primary components:
- Responsibility: Intent drafting and token escrow
- Privacy Mechanism: Orders encrypted using user's private key and service's public key
- Access Control: Only client and service can decrypt order contents
- Asset Transfer: Deposits USDC or DSTOCK tokens into on-chain escrow
- Smart Contracts: On-chain database and escrow management
- Custody: Holds user funds (USDC) and tokenized stocks (DSTOCK)
- Transparency: Public verification of escrow balances and reserve proofs
- Invariants: Enforces protocol guarantees through on-chain logic
- Order Processing: Decrypts user intents using service private key
- Brokerage Integration: Executes stock purchases/sales via traditional brokers
- Optimal Routing: Selects best execution venue based on liquidity and pricing
- Transaction Signing: Signs blockchain transactions via Lit Protocol MPC
- Reserve Proofs: Submits Chainlink Proof of Reserve attestations on-chain
- Key Management: Secures service private key using distributed custody
- Decryption: Can decrypt user intents encrypted with Lit's public key
- Signing: Generates valid signatures without exposing private key
- Fault Tolerance: Continues operation even if subset of nodes fail
- Market Access: Provides connectivity to traditional equity markets
- Settlement: Handles fiat settlement and regulatory compliance
- Custody: Maintains stocks on behalf of the protocol
- Reporting: Provides inventory attestations for proof of reserve
Objective: Prevent on-chain observers from determining order details
Implementation:
- Encryption (Client-Side): Orders encrypted using user's private key + service's public key
- Decryption (Service-Side): Service decrypts using its private key
- Privacy Guarantee: Only user and service can access plaintext order data
Threat Model:
- ✅ Prevents mempool observers from front-running
- ✅ Protects against MEV exploitation
- ✅ Conceals trading strategy from competitors
Objective: Obscure asset-specific holdings from on-chain analysis
Design:
- Single fungible token representing one share of any stock
- Asset-agnostic representation prevents portfolio reconstruction
- On-chain observers see quantity but not underlying asset
Example:
User deposits: 100 DSTOCK
On-chain visibility: User holds 100 shares
Hidden information: Which stock(s) these shares represent
Privacy Properties:
- Portfolio composition remains confidential
- Trading patterns cannot be linked to specific securities
- Reduces information leakage during redemption
Objective: Secure private key storage and distributed signing
Implementation (Lit Protocol):
- Key Sharding: Private key split across multiple Lit nodes
- Threshold Signatures: Transactions signed when m-of-n nodes agree
- TEE Execution: Signing operations performed inside Trusted Execution Environments
- Encrypted Communication: Inter-node communication secured via TLS
Security Properties:
- No Single Point of Failure: Compromise of individual nodes insufficient for key extraction
- Decentralized Trust: No single entity controls signing authority
- Auditability: All signing operations logged and verifiable
Objective: Cryptographically prove protocol solvency and full collateralization
Mechanism:
- Attestation: Custodian or auditor provides signed inventory data
- Oracle Validation: Decentralized Chainlink nodes verify attestation authenticity
- On-Chain Publication: Verified reserve amounts posted to smart contracts
- Programmatic Enforcement: Contracts enforce collateralization requirements
Verification Properties:
- Real-time solvency proofs
- Independent third-party attestation
- Tamper-proof on-chain records
- Automated under-collateralization detection
Mechanism:
- Protocol stakes proportional ETH amounts in escrow contract
- Funds subject to slashing via user governance voting
- Malicious behavior results in stake redistribution to affected users
Incentive Alignment:
- Economic penalty for protocol misbehavior
- Skin-in-the-game for protocol operators
- Community-governed dispute resolution
Core Function: getValidatedPrice()
TradeLayer implements a robust multi-oracle validation system to protect against adversarial oracle behavior, price manipulation, and stale data.
- Dual Oracle Fetch: Query both Pyth and Chainlink price feeds
- Consensus Mechanism:
- If both oracles return valid prices:
- Calculate deviation between the two sources
- Deviation > 30%: Use Time-Weighted Average Price (TWAP) as tiebreaker; select price closer to TWAP
- Deviation ≤ 30%: Use median (average) of both prices
- If only one oracle returns valid data:
- Validate against TWAP (deviation must be ≤ 30%)
- Revert if deviation exceeds threshold
- If both oracles return valid prices:
- Circuit Breaker: Reject price updates with >10% movement within 5-minute window
- TWAP Update: Continuously update Time-Weighted Average Price using validated final price
- Manipulation Resistance: Requires collusion of multiple oracle sources
- Staleness Protection: Enforces maximum data age requirements
- Volatility Guards: Circuit breakers prevent flash-crash exploitation
- Historical Validation: TWAP provides additional verification layer
We implemented 6 critical invariants using Foundry's fuzzing framework to mathematically prove the security and correctness of our tokenized stock trading protocol.
- Tool: Foundry Invariant Testing with Handler-based fuzzing
- Runs: 256+ iterations per invariant
- Approach: Stateful fuzzing with ghost variables tracking system state
- Coverage: All user actions (buy, redeem) and backend fulfillment scenarios
Contract USDC Balance ≥ Sum of Pending Buy Orders
What it proves: The protocol always holds enough USDC to cover all unfulfilled purchase requests. Users' funds are never at risk.
Why it matters: Prevents insolvency and ensures users can always get their money back if orders fail.
totalSupply() == Σ(totalHoldings[user][stock])
What it proves: Every DSTOCK token corresponds to exactly one unit of real stock holdings. No inflation or deflation of tokens.
Why it matters: Core accounting invariant - proves 1:1 backing of tokens to actual stocks.
∀ orderId: orderProcessed[orderId] can only transition false → true once
What it proves: Each order (buy or redeem) is fulfilled exactly once, never double-processed.
Why it matters: Prevents double-spending attacks and duplicate minting/burning.
∀ user: balanceOf(user) ≥ Σ(totalHoldings[user][stock])
What it proves: Users always have enough DSTOCK tokens to cover their recorded stock positions.
Why it matters: Ensures users can always redeem their stocks - no "phantom holdings" that can't be sold.
transfer() and transferFrom() always revert
What it proves: DSTOCK tokens are non-transferable, preventing secondary market trading.
Why it matters: Maintains regulatory compliance - users can only trade through the official protocol, not peer-to-peer.
(Total Minted - Total Burned) == Current Total Supply
What it proves: Our internal accounting (ghost variables) matches the actual on-chain state throughout all operations.
Why it matters: Validates our testing framework and ensures no hidden state corruption.
✅ All 6 invariants held across 256+ fuzzing runs
✅ No violations detected
✅ Protocol proven secure under adversarial conditions
- Solvency: Always enough USDC to cover obligations
- Accuracy: Tokens perfectly match real holdings
- Atomicity: No race conditions or double-processing
- Immutability: Transfers blocked as designed
- Consistency: System state always mathematically sound
Tested with Foundry invariant testing framework - industry standard for DeFi security
TradeLayer eliminates the artificial divide between cryptocurrency and traditional equity markets by creating a unified, privacy-preserving trading infrastructure. Through advanced cryptographic techniques, multi-oracle validation, and robust collateralization proofs, the protocol enables seamless access to global liquidity while maintaining the security, privacy, and decentralization guarantees expected by modern financial participants.
Key Innovations:
- Confidential order execution via two-way encryption
- Asset-agnostic tokenization preventing portfolio reconstruction
- Multi-oracle price validation with circuit breakers
- Cryptographic proof of reserve for transparency
- MPC-secured key management and transaction signing
- Contract Address:
0x5c7B3c7AC4640d5eB9424e93F10F9ab299516333 - Network: Base Mainnet
- Demo Video: YouTube