๐ฆ SECTION 3: CEDEX - CENTRALIZED-DECENTRALIZED EXCHANGE
3.1 ๐ Architectural Innovation
CEDEX (Centralized-Decentralized Exchange) represents a fundamental reimagining of decentralized exchange architecture, purpose-built from inception for trading tokenized securities within federal securities law frameworks. Unlike existing DEX platforms that were designed for permissionless cryptocurrency trading and subsequently face irreconcilable conflicts with securities regulation, CEDEX implements compliance verification as a foundational architectural constraint rather than retrofitted functionality.
This section provides comprehensive technical documentation of CEDEX's architectural innovations, explaining why existing DEX solutions cannot serve the tokenized securities market and how CEDEX's compliance-first design creates categorical advantages for institutional adoption.
3.1.1 โ The DEX Incompatibility Problem
Standard decentralized exchangesโincluding market leaders Raydium, Orca, Jupiter, and Meteoraโwere architected around three foundational design principles that create irreconcilable conflict with securities law compliance:
โก Principle 1: Computational Minimalism
Traditional DEXs optimize for maximum throughput by minimizing computational overhead per transaction. Every additional instruction reduces theoretical TPS capacity, creating strong architectural pressure against compliance verification.
Metric | Traditional DEX | With Transfer Hooks |
|---|---|---|
๐ข Compute Units | ~200,000 CU | ~800,000+ CU |
๐ Impact | Baseline | 4x increase |
A typical Raydium swap executes in approximately 200,000 compute units; adding six Transfer Hook verifications would increase this to 800,000+ compute units, fundamentally changing the economic model.
๐ซ Principle 2: Compliance Agnosticism
DEX protocols intentionally refuse implementation of securities-specific procedures such as:
- ๐ชช KYC verification
- ๐๏ธ Accreditation checking
- ๐ซ OFAC screening
- โ Investor qualification
This design choice reflects ideological commitment to permissionless trading and practical recognition that compliance creates liability exposure for protocol developers.
๐ธ Principle 3: Economic Incentive Misalignment
Traditional DEX economics depend on maximizing trading volume with minimal friction. Compliance verification introduces:
Factor | Impact on DEX |
|---|---|
โฑ๏ธ Friction | Latency (2-3 seconds) |
๐ง Complexity | Integration requirements |
๐ฐ Cost | Oracle fees |
These factors directly reduce profitability under existing DEX business models, creating structural resistance to compliance implementation.
๐ก Critical Insight: The incompatibility between existing DEXs and securities compliance is not a technical limitation that can be solved with additional development. It represents a fundamental architectural conflict where the design goals of permissionless trading and regulated securities trading are mutually exclusive.
3.1.2 ๐ง Why Existing DEXs Cannot Support ST22 Tokens
Beyond philosophical design conflicts, existing DEX codebases face concrete technical barriers preventing ST22 token support:
DEX Platform | ๐ช Token-2022 Support | ๐ช Transfer Hook Support |
|---|---|---|
๐ด Raydium | Partial (basic transfers only) | โ None โ hooks disabled |
๐ด Orca | Limited (whitelist) | โ None โ not implemented |
๐ด Jupiter | Aggregates underlying DEXs | โ None โ inherits limitations |
๐ด Meteora | Basic support | โ None โ bypassed |
๐ข CEDEX | Full native support | โ Full โ 6 hooks per transfer |
The core technical issue: existing DEX codebases were written before SPL Token-2022 existed. Their smart contracts interact directly with the original SPL Token Program, which lacks Transfer Hook extensions. Retrofitting Transfer Hook support would require complete protocol rewritesโa multi-year effort that these protocols have no economic incentive to undertake.
โ ๏ธ Critical Limitation: If ST22 tokens were traded on existing DEXs (assuming technical compatibility), Transfer Hooks would be bypassed during swaps. This would disable all 42 security controls, including custody verification, OFAC screening, and AML checksโmaking the tokens non-compliant securities.
3.1.3 ๐ฏ The CEDEX Design Philosophy
CEDEX inverts traditional DEX design priorities. Rather than implementing compliance verification as bolted-on functionality to existing trading infrastructure, CEDEX implements compliance verification as the foundational architectural constraint shaping every element of trading system design.
"We didn't add compliance to a DEX. We built a compliance engine that happens to execute trades."
This philosophical inversion creates three categorical advantages:
# | Advantage | Description |
|---|---|---|
1๏ธโฃ | Compliance Integration at Design Phase | Verification logic integrates at system design phase rather than being retrofitted. Every smart contract instruction, every data structure, every execution path was designed with compliance verification as a first-class requirement. |
2๏ธโฃ | Optimized Smart Contract Architecture | Smart contract architecture optimizes for compliance execution from inception. Compute budget allocation, account structure, and instruction ordering all prioritize successful compliance verification over raw trading speed. |
3๏ธโฃ | Aligned Economic Incentives | Economic incentive structure aligns operator profitability with successful compliance implementation. CEDEX generates revenue from compliant trades; non-compliant trades generate zero revenue because they cannot execute. |
3.1.4 โ๏ธ Compliance-First vs Compliance-Retrofitted
The distinction between compliance-first and compliance-retrofitted architecture has profound implications for system reliability, security, and regulatory acceptance:
Aspect | โ Compliance-First (CEDEX) | โ Compliance-Retrofitted |
|---|---|---|
โฑ๏ธ Verification Timing | Before execution (blocking) | After execution (non-blocking) |
๐ซ Non-Compliant Trades | Cannot execute (impossible) | Execute then flag for review |
๐ Regulatory Posture | Preventive control | Detective control |
๐ Audit Trail | Every trade verified on-chain | Off-chain logs (mutable) |
๐ง System Complexity | Integrated (single system) | Fragmented (multiple systems) |
โ ๏ธ Failure Mode | Fail-safe (no trade) | Fail-open (trade executes) |
3.2 โ๏ธ Custom AMM Architecture
CEDEX implements a modified Automated Market Maker (AMM) architecture engineered specifically for Transfer Hook integration. Unlike traditional AMMs that execute token swaps as atomic operations, CEDEX separates compliance verification from trading execution into distinct architectural layers, enabling asynchronous compliance checking without blocking user interaction.
3.2.1 ๐ Dual-Layer Execution Model
The dual-layer execution model represents CEDEX's core architectural innovation: segregating compliance verification from trading execution while maintaining atomic transaction guarantees.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ CEDEX DUAL-LAYER EXECUTION MODEL โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ค User Request
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ๏ธ COMPLIANCE VERIFICATION LAYER โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โฑ๏ธ Asynchronous Execution (2,000-3,000ms) โ โ
โ โ โ โ
โ โ Hook 1: ๐ Custody โ โ
โ โ โผ โ โ
โ โ Hook 2: ๐ซ OFAC โ โ
โ โ โผ โ โ
โ โ Hook 3: ๐ต๏ธ AML โ โ
โ โ โผ โ โ
โ โ Hook 4: ๐ชช KYC โ โ
โ โ โผ โ โ
โ โ Hook 5: ๐ Price Impact โ โ
โ โ โผ โ โ
โ โ Hook 6: ๐ง LP Ratio โ โ
โ โ โ โ
โ โ Result: โ
VERIFIED | โ REJECTED (with error code) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐น TRADING EXECUTION LAYER โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โก Synchronous Execution (400-600ms) โ โ
โ โ โ โ
โ โ 1๏ธโฃ Receive verification confirmation โ โ
โ โ 2๏ธโฃ Calculate CPMM output amount โ โ
โ โ 3๏ธโฃ Update pool reserves atomically โ โ
โ โ 4๏ธโฃ Execute token transfer โ โ
โ โ 5๏ธโฃ Distribute fees โ โ
โ โ โ โ
โ โ Result: โ
EXECUTED | โ REVERTED โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
3.2.2 โ๏ธ Compliance Verification Layer
The Compliance Verification Layer executes during every ST22 token transfer, implementing OTCM's six Transfer Hooks in sequential order. This layer operates asynchronously from the user's perspectiveโverification completion occurs independently of user action, enabling a responsive interface despite comprehensive compliance checking.
๐ Verification Flow
rust
// Compliance Verification Data Structure (Rust)
pub struct ComplianceVerification {
pub transfer_id: Pubkey, // Unique transfer identifier
pub sender: Pubkey, // Source wallet
pub recipient: Pubkey, // Destination wallet
pub token_mint: Pubkey, // ST22 token address
pub amount: u64, // Transfer amount
pub verification_start: i64, // Unix timestamp
pub hook_results: [HookResult; 6], // Results from each hook
pub final_status: VerificationStatus,
}
pub enum VerificationStatus {
Pending, // Verification in progress
Verified, // All hooks passed
Rejected { // At least one hook failed
hook_number: u8,
error_code: u16,
reason: String,
},
}
๐ช Hook Execution Sequence
Each Transfer Hook executes in strict sequence, with failure at any point causing immediate transaction reversion:
Order | Hook Name | Oracle Source | Latency | Fail Action |
|---|---|---|---|---|
1๏ธโฃ | ๐ Custody Verification | Empire Stock API | 100-150ms | Revert 6001 |
2๏ธโฃ | ๐ซ OFAC Screening | SDN List Oracle | 200-500ms | Revert 6002 |
3๏ธโฃ | ๐ต๏ธ AML Analytics | Chainalysis/TRM | 300-400ms | Revert 6003 |
4๏ธโฃ | ๐ชช Redemption Eligibility | KYC Registry | 50-100ms | Revert 6004 |
5๏ธโฃ | ๐ Price Impact Limit | TWAP Oracle | 50-100ms | Revert 6006 |
6๏ธโฃ | ๐ง Liquidity Ratio | Pool State | 50-100ms | Revert 6007 |
3.2.3 ๐น Trading Execution Layer
The Trading Execution Layer receives verified tokens and executes trades only upon successful completion of all compliance verification. This layer implements the Constant Product Market Maker (CPMM) formula for price discovery and liquidity provision.
๐ข CPMM Core Formula
CEDEX implements the constant product formula (x ร y = k) where x represents SOL reserves, y represents ST22 token reserves, and k is the invariant constant:
rust
// CPMM Swap Calculation (Rust)
pub fn calculate_swap_output(
input_amount: u64,
input_reserve: u64,
output_reserve: u64,
fee_bps: u16, // Basis points (500 = 5%)
) -> Result<SwapResult> {
// Apply fee to input
let fee_multiplier = 10000 - fee_bps as u64;
let input_with_fee = input_amount
.checked_mul(fee_multiplier)
.ok_or(SwapError::Overflow)?;
// Calculate output using constant product formula
// output = (input_with_fee ร output_reserve) /
// (input_reserve ร 10000 + input_with_fee)
let numerator = input_with_fee
.checked_mul(output_reserve)
.ok_or(SwapError::Overflow)?;
let denominator = input_reserve
.checked_mul(10000)
.ok_or(SwapError::Overflow)?
.checked_add(input_with_fee)
.ok_or(SwapError::Overflow)?;
let output_amount = numerator / denominator;
let fee_amount = input_amount - (input_amount * fee_multiplier / 10000);
Ok(SwapResult {
output_amount,
fee_amount,
new_input_reserve: input_reserve + input_amount,
new_output_reserve: output_reserve - output_amount,
})
}
3.2.4 ๐ Layer Synchronization Protocol
The two layers synchronize through a handoff protocol ensuring atomic execution guarantees:
Step | Phase | Description |
|---|---|---|
1๏ธโฃ | Verification Request | User initiates swap, generating unique
|
2๏ธโฃ | Parallel Processing | UI displays "Verifying compliance..." while hooks execute |
3๏ธโฃ | Verification Complete | All hooks pass,
set to
|
4๏ธโฃ | Execution Authorization | Trading layer receives signed verification confirmation |
5๏ธโฃ | Atomic Swap | CPMM calculation and token transfer execute in single transaction |
6๏ธโฃ | Settlement | Transaction finalizes after 32 Solana blocks (~13 seconds) |
๐ก Atomicity Guarantee: If verification completes but execution fails (e.g., slippage exceeded), the entire transaction reverts. Users never face situations where compliance verification succeeds but tokens transfer incorrectly.
3.3 ๐ Bonding Curve Bootstrap Phase
Upon deployment, each new ST22 token initially trades on a bonding curve rather than the permanent CPMM-based AMM. This bootstrap phase serves critical functions:
Function | Description |
|---|---|
๐ Price Discovery | Enabling initial price discovery in a controlled environment |
๐ก๏ธ Stability | Preventing flash crashes and wash trading during early trading |
๐ Early Adopter Advantage | Providing favorable entry prices for early community participants |
3.3.1 ๐ Initial Price Discovery Mechanism
The bonding curve creates a mathematically predictable relationship between token supply and price, eliminating the need for external price oracles during the bootstrap phase. As tokens are purchased, the price increases along a predetermined curve; as tokens are sold, the price decreases.
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ BONDING CURVE PRICE DISCOVERY โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Price โ
(USD) โ โญโโโโโโ ๐ Graduation
โ โญโโโฏ Threshold
$0.15โ โญโโโฏ ($250K MC)
โ โญโโโฏ
$0.10โ โญโโโฏ
โ โญโโโฏ
$0.05โ โญโโโฏ
โ โญโโโฏ
$0.01โ_____________________โญโโโโฏ
โ โญโโโฏ
$0.001โ______________โญโโโโฏ
โโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโบ
Tokens Issued (millions)
โโโโ ๐ฑ Early โโโบโโโโโโ ๐ Growth Phase โโโโโบโโโ ๐ Graduation โโบโ
Buyers
3.3.2 ๐งฎ Linear Bonding Curve Mathematics
CEDEX implements a linear bonding curve formula providing predictable price appreciation as token adoption increases:
// Linear Bonding Curve Formula
P(n) = initialPrice + (priceGradient ร tokensIssued)
// Parameters:
// initialPrice = $0.001 per token (starting price)
// priceGradient = 0.001% per token sold
๐ Example Calculations:
Tokens Sold | Price Calculation | Result |
|---|---|---|
0 tokens | P = $0.001 + (0.00001 ร 0) | $0.001 |
1M tokens | P = $0.001 + (0.00001 ร 1,000,000) | $0.011 |
10M tokens | P = $0.001 + (0.00001 ร 10,000,000) | $0.101 |
25M tokens | P = $0.001 + (0.00001 ร 25,000,000) | $0.251 |
๐ง Implementation
rust
// Bonding Curve Implementation (Rust)
pub struct BondingCurve {
pub token_mint: Pubkey,
pub initial_price: u64, // In lamports (0.001 SOL = 1,000,000 lamports)
pub price_gradient: u64, // Price increase per token (in lamports)
pub tokens_issued: u64, // Current tokens in circulation
pub sol_reserve: u64, // SOL collected from purchases
pub is_graduated: bool, // Whether curve has graduated
pub graduation_timestamp: Option<i64>,
}
impl BondingCurve {
pub fn current_price(&self) -> u64 {
self.initial_price + (self.price_gradient * self.tokens_issued / 1_000_000)
}
pub fn buy_tokens(&mut self, sol_amount: u64) -> Result<u64> {
// Calculate tokens receivable at current price
let current_price = self.current_price();
let tokens = sol_amount * 1_000_000_000 / current_price; // 9 decimals
// Update state
self.tokens_issued += tokens;
self.sol_reserve += sol_amount;
Ok(tokens)
}
}
3.3.3 ๐ Graduation Criteria
ST22 tokens graduate from bonding curve to permanent CPMM trading upon satisfying either of two criteria:
Criterion | Threshold | Rationale |
|---|---|---|
๐ฐ Market Cap | โฅ $250,000 USD | Sufficient liquidity for CPMM stability |
๐ฅ Holder Count | โฅ 127,000 unique wallets | Mathematical proof of community adoption (~0.5% of Solana active wallets) |
โฑ๏ธ Time Elapsed | โฅ 72 hours since deployment | Minimum stabilization period regardless of volume |
๐ Graduation occurs automatically when ANY criterion is met (OR logic). The 127,000 holder threshold represents approximately 0.5% of Solana's active wallet base, providing mathematical proof of genuine community adoption rather than artificial inflation.
3.3.4 ๐ Transition to Permanent AMM
Upon graduation, the following irreversible state transitions occur:
Step | Action | Description |
|---|---|---|
1๏ธโฃ | Bonding Curve Deactivation | Smart contract permanently disables bonding curve purchase/sale functions through immutable state flag |
2๏ธโฃ | Liquidity Migration | All SOL accumulated in bonding curve reserve transfers to CEDEX CPMM pool |
3๏ธโฃ | Pool Initialization | CPMM pool initializes with graduated token supply and migrated SOL reserve |
4๏ธโฃ | Permanent Lock | Liquidity becomes permanently lockedโcannot be withdrawn by any party including protocol administrators |
rust
// Graduation Function (Rust/Anchor)
pub fn graduate_to_amm(ctx: Context<Graduate>) -> Result<()> {
let curve = &mut ctx.accounts.bonding_curve;
let pool = &mut ctx.accounts.cpmm_pool;
// Verify graduation criteria met
require!(
curve.check_graduation_criteria()?,
CedexError::GraduationCriteriaNotMet
);
// Permanently disable bonding curve
curve.is_graduated = true;
curve.graduation_timestamp = Some(Clock::get()?.unix_timestamp);
// Initialize CPMM pool with migrated liquidity
pool.sol_reserve = curve.sol_reserve;
pool.token_reserve = curve.tokens_issued;
pool.k_invariant = pool.sol_reserve * pool.token_reserve;
pool.liquidity_locked = true; // PERMANENT - cannot be unlocked
// Transfer SOL to pool
transfer_sol(curve.sol_reserve, &ctx.accounts.pool_vault)?;
emit!(GraduationEvent {
token_mint: curve.token_mint,
final_market_cap: calculate_market_cap(curve),
holder_count: get_holder_count(curve.token_mint)?,
sol_migrated: curve.sol_reserve,
});
Ok(())
}
โ ๏ธ Irreversibility: Smart contract explicitly prevents bonding curve re-activation post-graduation through permanent disabling of bonding curve contract functions. This is enforced at the bytecode levelโnot through administrative controls that could be overridden.
3.4 ๐ข Constant Product Market Maker (CPMM)
Post-graduation, ST22 tokens trade on CEDEX's Constant Product Market Maker implementation. The CPMM model, pioneered by Uniswap, provides continuous liquidity at algorithmically determined prices without requiring traditional order books or market makers.
3.4.1 ๐งฎ CPMM Mathematical Foundation
The CPMM maintains the invariant k = x ร y, where:
Variable | Description |
|---|---|
x | SOL reserve in the liquidity pool |
y | ST22 token reserve in the liquidity pool |
k | Constant product (invariant) |
Every swap changes reserves while maintaining the invariant:
// CPMM Swap Example
// Pre-swap state:
k = x ร y = 100 SOL ร 1,000,000 tokens = 100,000,000
// User swaps 10 SOL for tokens:
new_x = 100 + 10 = 110 SOL
new_y = k / new_x = 100,000,000 / 110 = 909,091 tokens
tokens_received = 1,000,000 - 909,091 = 90,909 tokens
// Post-swap state:
k = 110 ร 909,091 โ 100,000,000 (invariant maintained) โ
3.4.2 ๐ Price Impact Calculation
Price impact measures how much a trade moves the market price. Larger trades relative to pool reserves create larger price impacts:
rust
// Price Impact Calculation
pub fn calculate_price_impact(
input_amount: u64,
input_reserve: u64,
output_reserve: u64,
) -> f64 {
// Spot price before trade
let spot_price = output_reserve as f64 / input_reserve as f64;
// Effective price for this trade
let output_amount = calculate_output(input_amount, input_reserve, output_reserve);
let effective_price = output_amount as f64 / input_amount as f64;
// Price impact as percentage
let impact = (spot_price - effective_price) / spot_price * 100.0;
impact.abs()
}
๐ Price Impact Examples (100 SOL Pool Reserve)
Trade Size | % of Pool | Price Impact | Circuit Breaker |
|---|---|---|---|
1 SOL | 1% | ~0.99% | โ Allowed |
2 SOL | 2% | ~1.96% | โ Allowed |
3 SOL | 3% | ~2.91% | ๐ Blocked |
5 SOL | 5% | ~4.76% | ๐ Blocked |
โ ๏ธ Circuit breaker activates at >2% price impact.
3.4.3 ๐ก๏ธ Slippage Protection
CEDEX provides configurable slippage protection ensuring users receive expected value:
rust
// Slippage Protection Implementation
pub struct SwapParams {
pub input_amount: u64,
pub min_output: u64, // Minimum acceptable output
pub max_slippage_bps: u16, // Maximum slippage in basis points
pub deadline: i64, // Unix timestamp expiry
}
pub fn execute_swap_with_protection(
ctx: Context<Swap>,
params: SwapParams,
) -> Result<()> {
// Check deadline
require!(
Clock::get()?.unix_timestamp <= params.deadline,
SwapError::DeadlineExceeded
);
// Calculate output
let output = calculate_output(...)?;
// Verify slippage tolerance
require!(
output >= params.min_output,
SwapError::SlippageExceeded
);
// Execute swap
execute_swap(output)?;
Ok(())
}
3.4.4 ๐ง Liquidity Depth Analysis
Pool liquidity depth determines trading efficiency. CEDEX targets minimum liquidity levels ensuring acceptable price impacts:
Pool TVL | Max Trade (2%) | Market Depth | Classification |
|---|---|---|---|
๐ฐ $100K | ~$2,000 | ๐ก Low | Early Stage |
๐ฐ $500K | ~$10,000 | ๐ Moderate | Developing |
๐ฐ $1M | ~$20,000 | ๐ข Good | Mature |
๐ฐ $5M+ | ~$100,000+ | ๐ต Deep | Institutional |
3.5 ๐ Circuit Breaker Architecture
CEDEX implements a comprehensive circuit breaker system protecting markets from manipulation, flash crashes, and coordinated attacks. Inspired by traditional securities exchange mechanisms (NYSE Rule 80B, NASDAQ halt procedures), these protections operate at the smart contract level with no administrative override capability.
3.5.1 ๐ Price Impact Limits
CEDEX enforces a hard limit on price impact per transaction. Any single transaction causing greater than 2% price movement against the Time-Weighted Average Price (TWAP) oracle is automatically rejected:
rust
// Price Impact Limit Implementation
pub const MAX_PRICE_IMPACT_BPS: u16 = 200; // 2% maximum
pub fn check_price_impact(
ctx: Context<PriceImpactCheck>,
proposed_trade: &SwapParams,
) -> Result<()> {
let twap = ctx.accounts.twap_oracle.get_price()?;
let expected_price = calculate_expected_price(proposed_trade)?;
// Calculate deviation from TWAP
let deviation_bps = ((twap - expected_price).abs() * 10000) / twap;
require!(
deviation_bps <= MAX_PRICE_IMPACT_BPS as u64,
CedexError::PriceImpactExceeded // Error 6006
);
Ok(())
}
๐ก This mechanism forces market participants to provide liquidity gradually versus attempting sudden massive liquidation. Large sellers must split orders across multiple transactions, allowing the market to absorb supply incrementally.
3.5.2 ๐ Volume-Based Halts
If any single wallet attempts to sell greater than 30% of circulating ST22 supply within a 24-hour period, transaction execution pauses for 24 hours:
rust
// Volume-Based Halt Implementation
pub const MAX_DAILY_SELL_PERCENT: u8 = 30; // 30% max daily sale
pub const HALT_DURATION_SECONDS: i64 = 86400; // 24 hours
pub struct WalletTrackingState {
pub wallet: Pubkey,
pub daily_sell_amount: u64,
pub tracking_window_start: i64,
pub is_halted: bool,
pub halt_expiry: Option<i64>,
}
pub fn check_volume_limit(
ctx: Context<VolumeCheck>,
sell_amount: u64,
) -> Result<()> {
let tracking = &mut ctx.accounts.wallet_tracking;
let circulating_supply = ctx.accounts.mint.supply;
// Reset tracking window if >24h elapsed
let current_time = Clock::get()?.unix_timestamp;
if current_time - tracking.tracking_window_start > HALT_DURATION_SECONDS {
tracking.daily_sell_amount = 0;
tracking.tracking_window_start = current_time;
}
// Check if halt is active
if tracking.is_halted {
if current_time < tracking.halt_expiry.unwrap() {
return Err(CedexError::WalletHalted.into());
}
tracking.is_halted = false;
}
// Check if this sale would exceed limit
let new_daily_total = tracking.daily_sell_amount + sell_amount;
let threshold = circulating_supply * MAX_DAILY_SELL_PERCENT as u64 / 100;
if new_daily_total > threshold {
tracking.is_halted = true;
tracking.halt_expiry = Some(current_time + HALT_DURATION_SECONDS);
return Err(CedexError::DailySellLimitExceeded.into());
}
tracking.daily_sell_amount = new_daily_total;
Ok(())
}
3.5.3 ๐ต๏ธ Coordinated Activity Detection
CEDEX implements machine learning-based detection of coordinated selling patterns suggesting manipulative intent. The algorithm analyzes four correlation dimensions:
Dimension | Analysis Method | ๐จ Suspicious Threshold |
|---|---|---|
๐ฅ Wallet Clustering | Graph analysis of funding sources | >5 wallets sharing funding source |
โฑ๏ธ Timing Correlation | Transaction timestamp clustering | >3 sells within 10-second window |
๐ฐ Amount Correlation | Statistical analysis of sale sizes | <5% variance across multiple sales |
๐ Price Impact Correlation | Sequential impact accumulation | Cumulative >5% within 1 hour |
When coordinated activity is detected, affected wallets enter 24-hour cooldown periods, and the compliance team receives alerts for manual review.
3.5.4 ๐ Time-Weighted Average Price (TWAP) Oracle
The TWAP oracle provides manipulation-resistant price data for circuit breaker calculations:
rust
// TWAP Oracle Implementation
pub struct TwapOracle {
pub token_mint: Pubkey,
pub price_observations: Vec<PriceObservation>,
pub observation_window: i64, // 1 hour in seconds
pub min_observations: u32, // Minimum 60 observations
}
impl TwapOracle {
pub fn calculate_twap(&self) -> Result<u64> {
let current_time = Clock::get()?.unix_timestamp;
let window_start = current_time - self.observation_window;
// Filter observations within window
let valid_observations: Vec<_> = self.price_observations
.iter()
.filter(|o| o.timestamp >= window_start)
.collect();
require!(
valid_observations.len() >= self.min_observations as usize,
OracleError::InsufficientObservations
);
// Time-weighted calculation
let mut weighted_sum: u128 = 0;
let mut total_time: u128 = 0;
for i in 1..valid_observations.len() {
let time_delta = valid_observations[i].timestamp -
valid_observations[i-1].timestamp;
weighted_sum += valid_observations[i-1].price as u128 * time_delta as u128;
total_time += time_delta as u128;
}
Ok((weighted_sum / total_time) as u64)
}
}
3.6 ๐ Order Types and Execution
CEDEX supports multiple order types optimized for different trading strategies while maintaining compliance verification for all executions.
3.6.1 ๐น Market Orders
Market orders execute immediately at current pool prices, subject to slippage tolerance:
Parameter | Specification |
|---|---|
โก Execution Speed | Immediate (subject to compliance verification ~2-3 seconds) |
๐ฐ Price Guarantee | None โ executes at current pool price |
๐ก๏ธ Slippage Protection | Configurable (default 1%, max 5%) |
๐ฆ Partial Fills | Not supported โ all-or-nothing execution |
๐ Circuit Breaker | Rejects if price impact exceeds 2% TWAP deviation |
3.6.2 โณ Limit Orders
Limit orders specify maximum buy price or minimum sell price, executing only when pool price reaches specified threshold:
rust
// Limit Order Data Structure
pub struct LimitOrder {
pub order_id: u64,
pub owner: Pubkey,
pub token_mint: Pubkey,
pub side: OrderSide, // Buy or Sell
pub amount: u64, // Token amount
pub limit_price: u64, // Price threshold (lamports per token)
pub expiry: i64, // Unix timestamp
pub status: OrderStatus,
}
pub enum OrderSide {
Buy, // Execute when pool price <= limit_price
Sell, // Execute when pool price >= limit_price
}
pub enum OrderStatus {
Open,
Filled,
Cancelled,
Expired,
}
3.6.3 ๐ Swap Interface
The primary trading interface presents unified swap functionality:
typescript
// User-facing swap interface
interface SwapRequest {
inputToken: 'SOL' | ST22Address;
outputToken: 'SOL' | ST22Address;
inputAmount: bigint;
minOutputAmount: bigint;
slippageTolerance: number; // Basis points
deadline: number; // Unix timestamp
}
// Response includes compliance verification status
interface SwapResponse {
transactionId: string;
inputAmount: bigint;
outputAmount: bigint;
effectivePrice: number;
priceImpact: number;
fees: {
protocol: bigint;
network: bigint;
};
complianceVerification: {
status: 'VERIFIED' | 'PENDING' | 'REJECTED';
hooks: HookResult[];
duration: number; // milliseconds
};
}
3.7 ๐ฐ Fee Structure and Distribution
CEDEX implements a transparent fee structure aligned with protocol sustainability and participant incentives. Unlike traditional exchanges with complex fee tiers, CEDEX applies uniform fees ensuring equal treatment of all market participants.
3.7.1 ๐ Transaction Fee Breakdown
Every CEDEX swap incurs a 5% total transaction fee (500 basis points), distributed as follows:
Fee Component | Rate | Purpose |
|---|---|---|
๐ข Issuer Allocation | 2.00% | Revenue share to issuing company treasury |
๐ฅฉ Staking Rewards | 1.50% | Distributed to OTCM token stakers (8-60% APY) |
โ๏ธ Protocol Operations | 1.06% | Infrastructure, compliance oracles, development |
๐ง Liquidity Pool Growth | 0.44% | Permanently locked in OTCM LP for depth |
๐ TOTAL | 5.00% | Complete fee structure |
3.7.2 ๐ Fee Distribution Mechanism
rust
// Fee Distribution Implementation
pub fn distribute_fees(
fee_amount: u64,
issuer_treasury: &Pubkey,
staking_pool: &Pubkey,
protocol_treasury: &Pubkey,
liquidity_pool: &Pubkey,
) -> Result<()> {
// Fee distribution ratios (basis points of 5% fee)
const ISSUER_SHARE: u64 = 4000; // 40% of 5% = 2.00%
const STAKING_SHARE: u64 = 3000; // 30% of 5% = 1.50%
const PROTOCOL_SHARE: u64 = 2120; // 21.2% of 5% = 1.06%
const LP_SHARE: u64 = 880; // 8.8% of 5% = 0.44%
// Calculate individual amounts
let issuer_amount = fee_amount * ISSUER_SHARE / 10000;
let staking_amount = fee_amount * STAKING_SHARE / 10000;
let protocol_amount = fee_amount * PROTOCOL_SHARE / 10000;
let lp_amount = fee_amount * LP_SHARE / 10000;
// Execute transfers atomically
transfer_sol(issuer_amount, issuer_treasury)?;
transfer_sol(staking_amount, staking_pool)?;
transfer_sol(protocol_amount, protocol_treasury)?;
transfer_sol(lp_amount, liquidity_pool)?; // Permanently locked
emit!(FeeDistributed { ... });
Ok(())
}
3.7.3 ๐ Fee Comparison Analysis
Platform | ๐ธ Swap Fee | โ๏ธ Compliance | ๐ LP Rewards | ๐ข Issuer Rev |
|---|---|---|---|---|
๐ข CEDEX | 5.00% | โ Full | 8-60% APY | 2.00% |
๐ต Raydium | 0.25% | โ None | Variable | 0% |
๐ต Orca | 0.30% | โ None | Variable | 0% |
๐ก Pump.fun | 1.00% | โ None | None | 0% |
๐ก Fee Justification: While CEDEX's 5% fee exceeds traditional DEX fees, it includes comprehensive compliance verification ($2-5 per transaction in oracle costs), issuer revenue sharing, and permanent liquidity growth. For institutional securities trading, this represents significant cost savings versus traditional broker-dealer infrastructure.
3.8 ๐ก๏ธ MEV Protection
Maximum Extractable Value (MEV) attacks represent one of the most significant threats to DeFi users, with an estimated $1.38 billion extracted from traders in 2023 alone. CEDEX implements multiple protection layers making MEV extraction economically unfeasible.
3.8.1 ๐ Frontrunning Prevention
Frontrunning occurs when malicious actors observe pending transactions and insert their own transactions ahead in the block order to profit from predictable price movements. CEDEX prevents frontrunning through:
Protection | Mechanism |
|---|---|
๐ Private Transaction Submission | Transactions route through Jito's private mempool, invisible to searchers until block inclusion |
๐ Slippage Enforcement | Strict slippage limits (default 1%) reduce profitability of frontrunning attempts |
๐ Circuit Breaker Integration | 2% price impact limit prevents large frontrun trades from executing |
3.8.2 ๐ฅช Sandwich Attack Mitigation
Sandwich attacks bracket victim transactions with buy-before and sell-after trades, extracting value through induced price movements. CEDEX's protection mechanisms:
// Sandwich Attack Scenario (Without Protection):
// 1. ๐ฆ Attacker sees: User wants to buy 10,000 tokens
// 2. ๐ Attacker frontruns: Buys 50,000 tokens (price increases)
// 3. ๐ข User trade executes: Buys at higher price
// 4. ๐ธ Attacker backruns: Sells 50,000 tokens (profit extracted)
// โ
CEDEX Protection:
// 1. ๐ Transaction in private Jito mempool (invisible to attacker)
// 2. ๐ Even if visible, 2% circuit breaker blocks attacker's frontrun
// 3. ๐ก๏ธ User trade protected by slippage tolerance
// 4. ๐ต๏ธ Sequential large trades trigger coordinated activity detection
3.8.3 ๐ฆ Jito Bundle Integration
CEDEX integrates with Jito's block-building infrastructure for institutional-grade MEV protection:
Feature | Implementation |
|---|---|
๐ฆ Bundle Submission | All CEDEX trades submitted as Jito bundles with guaranteed atomicity |
๐ Private Mempool | Transactions invisible until block inclusion (no public mempool exposure) |
โก Priority Fees | Dynamic priority fee calculation for reliable inclusion |
๐ก๏ธ Backrun Protection | Bundle structure prevents insertion between compliance verification and execution |
3.9 ๐ Performance Specifications
Metric | Specification | Notes |
|---|---|---|
โก Throughput (TPS) | 400-600 | Limited by compliance verification |
โ๏ธ Compliance Latency | 2,000-3,000ms | Six hooks + oracle queries |
๐น Execution Latency | 400-600ms | CPMM swap post-verification |
โ Block Finality | ~13 seconds | 32 Solana blocks |
๐ข Compute Units | ~800,000 CU | Per complete swap transaction |
๐ต Network Fee | ~$0.01-0.05 | Solana base + priority fee |
3.10 ๐ Security Architecture
CEDEX security combines smart contract hardening, economic attack resistance, and operational security measures:
๐ Smart Contract Security
Measure | Description |
|---|---|
โ Formal Verification | Using Certora Prover |
๐ Security Audits | By Quantstamp, Halborn, and OtterSec |
๐ Bug Bounty | Active program (up to $100K rewards) |
๐ Immutable Contracts | Core contracts immutable post-deployment |
๐ฐ Economic Security
Measure | Description |
|---|---|
๐ Circuit Breakers | Prevent flash loan attacks |
๐ TWAP Oracle | Resists price manipulation |
๐ Permanent Locks | Prevent rug pulls |
๐ Volume Limits | Prevent coordinated dumps |
๐ง Operational Security
Measure | Description |
|---|---|
๐ Multi-signature | Admin keys (4-of-7 threshold) |
โฑ๏ธ Timelock | 48-hour timelock on parameter changes |
๐๏ธ Monitoring | Real-time monitoring and alerting |
๐ Incident Response | Playbooks for crisis management |
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ยฉ 2025 OTCM Protocol, Inc. | All Rights Reserved