Section 5: Custom AMM Engine & CEDEX โ Layers 4 and 5
๐OTCMThePROTOCOLComprehensive Technical Whitepaper โ Version 7.0
ST22 Digital Securities Platform | March 2026 | Groovy Company, Inc. dba OTCM
tradingProtocolinterface
Section 5: Custom AMM Engine & CEDEX โ
aLayers 4 and 5Layer 4 provides the mathematical trading engine that powers all ST22 secondary market activity. Layer 5 โ CEDEX โ is the purpose-built
Centralized-DecentralizedCompliant Exchangecombiningfor Digital Securities that combines Web2 order matching with Web3 settlement finality, nativelysupportingenforcing all 42 Transfer Hook security controls on every trade.
Layer
Component
Function
Layer 4
Custom AMM Engine
Constant Product Market Maker (CPMM) operating against the Global Unified CEDEX Liquidity Pool โ purpose-built for SPL Token-2022 Transfer Hook compatibility
Layer 5
CEDEX
Compliant Exchange for Digital Securities โ dual-layer execution: centralized order matching + decentralized Solana settlement with full 42-control Transfer Hook enforcement
PART A โ LAYER 4: CUSTOM AMM ENGINE
5.1 Why a Custom AMM Is Required
The Custom AMM Engine exists because every major decentralized exchange on Solana โ Raydium, Orca, Jupiter, Meteora โ was built before SPL Token-2022 Transfer Hooks
forexisted. Their smart contracts interact directly with the original SPL Token Program, which lacks Transfer Hook extensions. This is not a configuration gap. It is a fundamental architectural incompatibility.When an ST22 token is transferred through any external DEX, the DEX's swap program calls the Token Program directly, bypassing the Transfer Hook entirely. This would disable all 42 security controls โ including the Empire Stock Transfer custody verification, OFAC/SDN screening, AML risk scoring, accreditation check, and the Rule 144 / Reg S holding period enforcement โ on every trade. The token would cease to be a compliant Digital Security at the moment of its first exchange-executed trade.
DEX Platform
Token-2022 Support
Transfer Hook Support
ST22 Compatible?
Raydium
Partial โ basic transfers only
None โ hooks disabled at swap
No
Orca
Limited โ whitelist
None โ not implemented
No
Jupiter
Aggregates underlying DEXs
None โ inherits DEX limitations
No
Meteora
Basic support
None โ bypassed
No
CEDEX (OTCM Protocol)
Full native support
Full โ all 42 controls per transfer
Yes โ only compliant venue
Critical: SEC Compliance Consequence
If ST22 Digital Securities
compliance.tokens were traded on external DEXs, Transfer Hooks would be bypassed during swap execution. This would disable custody verification (Control 1), OFAC/SDN screening (Controls 8โ10), AML scoring (Control 11), accreditation verification (Control 12), and the Rule 144 / Reg S holding period lock (Control 24) โ making the tokens non-compliant Digital Securities under SEC Release No. 33-11412 and the January 28, 2026 Joint Staff Statement.
๐ก5.2 Custom AMM Architecture5.2.1 Constant Product Market Maker (CPMM) โ Mathematical Foundation
The Custom AMM implements the Constant Product Market Maker formula (x ร y = k), operating against the Global Unified CEDEX Liquidity Pool. The CPMM provides continuous, algorithmically determined pricing without requiring traditional order books or external market makers. Pricing is entirely a function of pool reserve ratios โ as one asset is bought, it becomes more expensive; as it is sold, it becomes cheaper.
Variable
Definition
x
SOL reserve in the Global Unified CEDEX Liquidity Pool
y
ST22 token reserve in the pool for the given issuer
k
Constant product invariant โ maintained (or increased by fees) after every swap
fee
5% protocol fee (500 bps) โ applied before invariant calculation, ensuring k grows with every trade
Example swap โ buying ST22 tokens with 10 SOL from a pool with 100 SOL and 1,000,000 token reserves:
Initial state: x = 100 SOL | y = 1,000,000 tokens | k = 100,000,000
Input: 10 SOL โ after 5% fee: 9.5 SOL effective input
new_x = 100 + 9.5 = 109.5 SOL
new_y = k / new_x = 100,000,000 / 109.5 = 913,242 tokens
tokens_received = 1,000,000 - 913,242 = 86,758 tokens
effective_price = 10 SOL / 86,758 tokens = 0.0001153 SOL/token
k_after = 109.5 ร 913,242 = 99,999,999 โฅ original k โ invariant preserved
5.2.2 u128 Overflow-Safe Arithmetic
The CPMM formula requires multiplying two u64 reserve values. The maximum u64 value is 2โค โ 1 โ 18.4 ร 10ยนโธ. Multiplying two maximum u64 values produces a value requiring 128 bits. All intermediate CPMM calculations use u128 arithmetic to prevent overflow:
pub fn calculate_output_amount(
input_amount: u64,
input_reserve: u64,
output_reserve: u64,
fee_bps: u16, // 500 = 5%
) -> Result<SwapResult> {
// Apply fee BEFORE invariant calculation
let fee_multiplier = (10_000 - fee_bps as u64) as u128;
let input_with_fee = (input_amount as u128)
.checked_mul(fee_multiplier)
.ok_or(SwapError::Overflow)?;
// u128 intermediate โ prevents overflow on large reserves
let numerator = input_with_fee
.checked_mul(output_reserve as u128)
.ok_or(SwapError::Overflow)?;
let denominator = (input_reserve as u128)
.checked_mul(10_000)
.ok_or(SwapError::Overflow)?
.checked_add(input_with_fee)
.ok_or(SwapError::Overflow)?;
// Floor rounding โ trader receives slightly less, k never decreases
let output_amount = (numerator / denominator) as u64;
Ok(SwapResult { output_amount,
new_input_reserve: input_reserve + input_amount,
new_output_reserve: output_reserve - output_amount })
}
5.2.3 Rounding Policy
Operation
Rounding Direction
Rationale
amount_out calculation
Floor (truncate)
Trader receives slightly less โ protocol never over-pays. Ensures k can only increase.
amount_in (exact output)
Ceiling
Trader pays slightly more โ protocol never under-receives.
Fee calculation
Floor
Slightly less fee collected โ conservative accounting.
LP share calculation
Floor
LP receives slightly less โ prevents LP share inflation.
Invariant Guarantee
Floor rounding on amount_out ensures new_k โฅ old_k after every swap. The product invariant can only increase or remain equal โ it can never decrease. Because the 5% fee increases the effective input before the invariant calculation, k grows with every trade. The Global Unified CEDEX Liquidity Pool mathematically deepens with every ST22 transaction.
5.2.4 Maximum Safe Operating Parameters
Parameter
Maximum Safe Value
Notes
Single reserve
10ยนโต tokens (u64)
Beyond this, consider reserve splitting
Single swap amount
20% of reserve
Circuit breaker enforces via Transfer Hook Control 16
k value
~10ยณโฐ
Well within u128 range (3.4 ร 10ยณโธ)
Cumulative k growth
Unbounded
k can only grow โ no maximum, reflects permanent pool deepening
5.3 GROO Token Bonding Curve โ GROO Only
The bonding curve price discovery mechanism applies exclusively to the GROO token โ Groovy Company, Inc.'s own ST22 token. It does not apply to third-party issuer ST22 tokens. Third-party issuers distribute 100% of their tokens to verified accredited investors through Regulation D 506(c) private placements and trade directly against the Global Unified CEDEX Liquidity Pool via the CPMM upon the conclusion of their holding period.
Scope: GROO Token Only
Sections 5.3.1 through 5.3.4 describe the bonding curve mechanics that govern the GROO token's initial price discovery phase. These mechanics do not apply to any other ST22 issuer. Third-party ST22 issuers have no bonding curve phase. Their tokens trade via the CPMM against the Global Unified CEDEX Liquidity Pool immediately upon completion of the Rule 144 / Reg S holding period.
5.3.1 Linear Bonding Curve Mathematics
The GROO token's bonding curve implements a linear formula providing predictable price appreciation as adoption increases:
P(n) = initialPrice + (priceGradient ร tokensIssued)
Where:
initialPrice = 0.000001 SOL (1,000 lamports)
priceGradient = 0.0000000079 SOL per token issued
tokensIssued = current circulating supply
pub struct BondingCurve {
pub token_mint: Pubkey,
pub initial_price: u64, // lamports
pub price_gradient: u64, // lamports per token
pub tokens_issued: u64, // current supply
pub sol_reserve: u64, // SOL collected
pub is_graduated: bool,
pub graduation_timestamp: Option<i64>,
}
5.3.2 GROO Graduation Criteria
The GROO token graduates from bonding curve to permanent CPMM trading upon satisfying any one of three criteria (OR logic):
Criterion
Threshold
Rationale
Market Cap
โฅ $250,000 USD
Sufficient liquidity depth for stable CPMM operation
Holder Count
โฅ 127,000 unique wallets
~0.5% of Solana active wallets โ proof of genuine community adoption
Time Elapsed
โฅ 72 hours since deployment
Minimum stabilization period regardless of volume
5.3.3 Graduation State Transition
Upon meeting any graduation criterion, the following irreversible state transitions execute atomically:
โข Bonding curve deactivation โ Smart contract permanently disables bonding curve purchase and sale functions through an immutable state flag โ enforced at bytecode level, not through administrative controls
โข Liquidity migration โ All SOL accumulated in the bonding curve reserve transfers to the Global Unified CEDEX Liquidity Pool
โข CPMM pool initialization โ CPMM pool initializes with the graduated token supply and migrated SOL reserve. liquidity_locked = true โ permanent and immutable
โข Secondary trading activation โ GROO tokens are now tradeable via CPMM on CEDEX with the same 42 Transfer Hook controls enforced on every transfer
pub fn execute_graduation(ctx: Context<Graduate>) -> Result<()> {
let curve = &mut ctx.accounts.bonding_curve;
require!(
curve.check_graduation_criteria()?,
CedexError::GraduationCriteriaNotMet
);
// Permanently disable bonding curve
curve.is_graduated = true;
curve.graduation_timestamp = Some(Clock::get()?.unix_timestamp);
// Migrate all SOL to Global Unified CEDEX Liquidity Pool
let pool = &mut ctx.accounts.cedex_pool;
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(curve.sol_reserve, &ctx.accounts.pool_vault)?;
emit!(GraduationComplete {
token_mint: curve.token_mint,
sol_migrated: curve.sol_reserve,
final_market_cap: calculate_market_cap(curve),
});
Ok(())
}
PART B โ LAYER 5: CEDEX โ COMPLIANT EXCHANGE FOR DIGITAL SECURITIES
5.4 CEDEX Architectural Innovation
CEDEX
(Centralized-DecentralizedโExchange)Compliantrepresents a fundamental reimagining of decentralized exchange architecture, purpose-built from inceptionExchange fortradingDigital Securitieswithin federal securities law frameworks. Under the SEC's March 17, 2026 interpretation (Release No. 33-11412), ST22 tokens are formally classified asDigital Securities โfinancialisinstrumentstheformattedexclusiveastradingcryptovenueassetsforwithallownershipST22recordedtokens.on a crypto network. CEDEXIt is the only exchange built to enforce every compliance obligation that SEC Digital Securities classification entails on every single trade. Under the January 28, 2026 Joint Staff Statement and Release No. 33-11412, ST22 tokens are Digital Securities. Their trading venue must be capable of enforcing the compliance obligations that status entails. CEDEX was built to be that venue.
Unlikeexisting DEX platforms designed for permissionless cryptocurrency trading, CEDEX implements compliance verification as afoundational architectural constraintrather than retrofitted functionality.
"We didn't add compliance to a DEX. We built a compliance engine that happens to execute trades."
๐น5.1.1The DEX Incompatibility Problem
Standard decentralized exchanges โ including market leaders Raydium, Orca, Jupiter, and Meteora โ were architected around three foundational design principles that createirreconcilable conflictwith securities law compliance:
Principle 1: Computational MinimalismTraditional DEXs optimize for maximum throughput by minimizing computational overhead per transaction. A typical Raydium swap executes in approximately 200,000 compute units; adding six Transfer Hook verifications increases this to 800,000+ compute units โ fundamentally changing the economic model.
Principle 2: Compliance AgnosticismDEX protocols intentionally refuse implementation of securities-specific procedures such as KYC verification, accreditation checking, OFAC screening, and investor qualification. This reflects ideological commitment to permissionless trading and practical recognition that compliance creates liability exposure for protocol developers.
Principle 3: Economic Incentive MisalignmentTraditional DEX economics depend on maximizing trading volume with minimal friction. Compliance verification introduces latency, integration complexity, and oracle costs โ factors that directly reduce profitability under existing DEX business models.
๐กCritical Insight:The incompatibility between existing DEXs and Digital 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.
๐น 5.1.2 Why Existing DEXs Cannot Support ST22 Tokens
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
ExistingDEX 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 these protocols have no economic incentive to undertake.5.4.1
โ ๏ธCritical Limitation:If ST22 Digital Securities tokens were traded on existing DEXs, 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 Digital Securities.
๐น 5.1.3Compliance-First vs. Compliance-RetrofittedThe distinction between compliance-first architecture and compliance-retrofitted architecture determines whether non-compliant trades can execute. CEDEX is compliance-first โ it is structurally impossible for a non-compliant trade to complete:
Aspect
Compliance-First (CEDEX)
Compliance-Retrofitted
Verification
TimingtimingBefore execution
(blocking)โ blockingAfter execution
(โ non-blocking)blockingNon-
CompliantcompliantTradestradesCannot execute โ structurally impossible
Execute then flag for review
Regulatory
PostureposturePreventive control
Detective control
Audit
TrailtrailEvery trade verified on-chain โ immutable
Off-chain logs
(mutable)โ mutableSystem
ComplexitycomplexityIntegrated
(โ singlesystem)compliance + trading systemFragmented
(โ multiplesystems)systemsFailure
ModemodeFail-safe
(โ notrade)trade if compliance failsFail-open
(โ tradeexecutes)executes despite compliance failureSEC Release 33-11412 alignment
Category 1 Model B โ compliant
Category 2 exposure or non-compliant
๐๏ธ5.55.2Dual-Layer Execution Architecture
CEDEX implements adual-layer architecturecombining a centralized order management system with decentralized on-chain settlement. The centralized layer handles order matching, price discovery, and user interface at sub-100ms latency. The decentralized layer handles actual asset custody, Transfer Hook enforcement, and settlement finality on Solana.
Layer
Function
Technology
Centralized OMS
Order matching ยท price feeds ยท UI
OTCM matching engine + REST API
Compliance Verification
KYC/AML status ยท accreditation check
Layer 2 Transfer Hook pre-check
Decentralized Settlement
Asset transfer ยท Transfer Hook execution ยท finality
Solana + SPL Token-2022
๐น 5.2.1 Dual-Layer Execution ModelUser Submits ST22 Trade Request โ Centralized OMS โ Pre-flight compliance check โโโ KYC status verified โโโ Accreditation status verified โโโ AML flag check โ CLEAR Compliance Verification Layer (750โ1,350ms) โโโ Hook 1: Custody Verification โโโ Hook 2: OFAC Screening โโโ Hook 3: AML Analytics โโโ Hook 4: Redemption Eligibility โโโ Hook 5: Price Impact Circuit Breaker โโโ Hook 6: Liquidity Pool Sufficiency โ ALL PASS Trading Execution Layer โ CPMM swap (400โ600ms) โ Solana Settlement โ 32 block finality (~13 seconds) โ ANY FAIL Entire Transaction Reverts โ Specific error code returned
๐น 5.2.2 Compliance Verification Layer
Before any trade executes on-chain, CEDEX runs apre-flight compliance checkagainst the investor's current verification status, querying the Issuers Portal compliance state in real-time. Traders with lapsed KYC, expired accreditation, or flagged AML status are blocked at the order entry stage โ before any on-chain transaction is attempted โ preventing failed transactions and wasted fees.pub struct ComplianceVerification { pub transfer_id: Pubkey, pub sender: Pubkey, pub recipient: Pubkey, pub token_mint: Pubkey, pub amount: u64, pub verification_start: i64, pub hook_results: [HookResult; 6], pub final_status: VerificationStatus, } pub enum VerificationStatus { Pending, Verified, Rejected { hook_number: u8, error_code: u16, reason: String, }, }
Hook Execution Sequence:
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
๐น 5.2.3 Trading Execution Layer
Approved orders are submitted to the Solana network as signed transactions. The SPL Token-2022 Transfer Hook extensions executeatomically with settlementโ there is no separation between trade execution and compliance enforcement.
CEDEX implements the constant product formula (x ร y = k):pub fn calculate_swap_output( input_amount: u64, input_reserve: u64, output_reserve: u64, fee_bps: u16, // 500 = 5% ) -> Result<SwapResult> { let fee_multiplier = 10000u128 - fee_bps as u128; let input_with_fee = (input_amount as u128) .checked_mul(fee_multiplier) .ok_or(SwapError::Overflow)?; let numerator = input_with_fee .checked_mul(output_reserve as u128) .ok_or(SwapError::Overflow)?; let denominator = (input_reserve as u128) .checked_mul(10000) .ok_or(SwapError::Overflow)? .checked_add(input_with_fee) .ok_or(SwapError::Overflow)?; let output_amount = (numerator / denominator) as u64; // Floor Ok(SwapResult { output_amount, fee_amount: (input_amount as u128 * fee_bps as u128 / 10000) as u64, new_input_reserve: input_reserve + input_amount, new_output_reserve: output_reserve - output_amount, }) }
๐น 5.2.4 Layer Synchronization Protocol
The centralized OMS maintains a real-time synchronized view of on-chain state through OTCM's dedicated Helius RPC node cluster. Order book updates reflect confirmed on-chain settlements within400ms(one Solana block) โ ensuring no price discrepancy between displayed quotes and executable on-chain prices during normal network conditions.
๐ก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.
๐ 5.3 Bonding Curve Bootstrap Phase
Upon deployment, each new ST22 Digital Securities token initially trades on abonding curverather than the permanent CPMM-based AMM. This bootstrap phase enables initial price discovery in a controlled environment, prevents flash crashes during early trading, and provides favorable entry prices for early community participants.
๐น 5.3.1 Linear Bonding Curve MathematicsP(n) = initialPrice + (priceGradient ร tokensIssued)pub struct BondingCurve { pub token_mint: Pubkey, pub initial_price: u64, // In lamports (0.000001 SOL) pub price_gradient: u64, // Price increase per token pub tokens_issued: u64, pub sol_reserve: u64, pub is_graduated: bool, 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 record_purchase(&mut self, tokens: u64, sol_amount: u64) { self.tokens_issued += tokens; self.sol_reserve += sol_amount; } }
๐น 5.3.2 Graduation Criteria
ST22 tokens graduate from bonding curve to permanent CPMM trading upon satisfyinganyof three criteria (OR logic):
Criterion
Threshold
Rationale
Market Cap
โฅ $250,000 USD
Sufficient liquidity for CPMM stability
Holder Count
โฅ 127,000 unique wallets
~0.5% of Solana active wallets โ proof of genuine adoption
Time Elapsed
โฅ 72 hours since deployment
Minimum stabilization period regardless of volume
๐น 5.3.3 Transition to Permanent AMM
Upon graduation, the followingirreversiblestate transitions occur:pub fn execute_graduation(ctx: Context<Graduation>) -> Result<()> { require!( curve.check_graduation_criteria()?, CedexError::GraduationCriteriaNotMet ); // Permanently disable bonding curve โ IMMUTABLE FLAG curve.is_graduated = true; curve.graduation_timestamp = Some(Clock::get()?.unix_timestamp); curve.can_reactivate = false; // Initialize CPMM pool with graduated reserves 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 // Atomic transfer of all bonding curve reserves to CPMM pool transfer_sol(curve.sol_reserve, &ctx.accounts.pool_vault)?; emit!(GraduationCompleted { 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.
๐ข CPMM Arithmetic Precision Specification
Version: 6.1 | Applies To: Layer 4 AMM โ All swap calculations
u128 Overflow-Safe Arithmetic
The CPMM formula x ร y = k requires multiplying two u64 reserve values. The maximum u64 value is 2โถโด โ 1 โ 18.4 ร 10ยนโธ. Multiplying two maximum u64 values produces a value requiring 128 bits.All intermediate CPMM calculations MUST use u128 arithmetic to prevent overflow.
Rounding Policy
Operation
Rounding Direction
Rationale
amount_out
calculation
Floor (truncate)
Trader receives slightly less โ protocol never over-pays
amount_in
calculation (exact output)
Ceiling
Trader pays slightly more โ protocol never under-receives
Fee calculation
Floor
Slightly less fee collected โ conservative
LP share calculation
Floor
LP receives slightly less โ prevents LP share inflation
Invariant guarantee:Floor rounding onamount_outensuresnew_k โฅ old_kafter every swap. The product invariant can only increase or stay equal, never decrease.
Maximum Safe Operating Parameters
Parameter
Maximum Safe Value
Notes
Single reserve
10ยนโต tokens (u64)
Beyond this, consider reserve splitting
Single swap amount
20% of reserve
Circuit breaker enforces this (Hook 5)
k value
~10ยณโฐ
Well within u128 range (3.4 ร 10ยณโธ)
Cumulative k growth
Unbounded
k can only grow โ no maximum
๐ 5.4 Constant Product Market Maker (CPMM)
Post-graduation, ST22 Digital Securities tokens trade on CEDEX'sConstant Product Market Makerimplementation. The CPMM model provides continuous liquidity at algorithmically determined prices without requiring traditional order books or market makers.
๐น 5.4.1 CPMM Mathematical Foundation
The CPMM maintains the invariantk = x ร y, where:
x= SOL reserve in the liquidity pooly= ST22 token reserve in the liquidity poolk= constant product (invariant)
Example swap โ buying 10 SOL worth of tokens:Initial state: k = 100 SOL ร 1,000,000 tokens = 100,000,000 After 10 SOL buy: 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 Invariant check: k = 110 ร 909,091 โ 100,000,000 โ
๐น 5.4.2 Price Impact Calculationpub fn calculate_price_impact( input_amount: u64, input_reserve: u64, output_reserve: u64, ) -> f64 { let spot_price = input_reserve as f64 / output_reserve as f64; let new_input = input_reserve as f64 + input_amount as f64; let new_output = (input_reserve as f64 * output_reserve as f64) / new_input; let executed_price = input_amount as f64 / (output_reserve as f64 - new_output); let impact = (executed_price - spot_price) / spot_price * 100.0; impact.abs() }
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
Examples assume 100 SOL pool reserve. Circuit breaker activates at >2% price impact.
๐น 5.4.3 Slippage Protectionpub 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(ctx: Context<Swap>, params: SwapParams) -> Result<()> { require!( Clock::get()?.unix_timestamp <= params.deadline, SwapError::DeadlineExceeded ); let output = calculate_swap_output(params.input_amount, ...)?; require!( output >= params.min_output, SwapError::SlippageExceeded ); execute_swap(output)?; Ok(()) }
๐น 5.4.4 Liquidity Depth Analysis
Pool TVL
Max Trade (2% impact)
Market Depth
Classification
$100K
~$2,000
Low
Early Stage
$500K
~$10,000
Moderate
Developing
$1M
~$20,000
Good
Mature
$5M+
~$100,000+
Deep
Institutional
๐๏ธ 5.5 Circuit Breaker Architecture
CEDEX implements a comprehensive circuit breaker system protecting Digital Securities 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 withno administrative override capability.
๐น 5.5.1 Price Impact Limitspub const MAX_PRICE_IMPACT_BPS: u16 = 200; // 2% maximum pub fn check_price_impact( ctx: Context<PriceImpactCheck>, proposed_trade: &SwapParams, ) -> Result<()> { require!( deviation_bps <= MAX_PRICE_IMPACT_BPS as u64, CedexError::PriceImpactExceeded // Error 6006 ); Ok(()) }
This mechanism forces market participants to execute large trades gradually, allowing the market to absorb supply incrementally.
๐น 5.5.2 Volume-Based Halts
If any single wallet attempts to sell greater than30% of circulating ST22 supplywithin a 24-hour period, transaction execution pauses for 24 hours: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>, }
๐น 5.5.3 Coordinated Activity Detection
CEDEX implements ML-based detection of coordinated selling patterns suggesting manipulative intent:
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.
๐น 5.5.4 Time-Weighted Average Price (TWAP) Oraclepub 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> { require!( valid_observations.len() >= self.min_observations as usize, OracleError::InsufficientObservations ); let mut weighted_sum = 0u128; let mut total_time = 0u128; 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) } }
๐ 5.6 Order Types and Execution
๐น 5.6.1 Market Orders
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
๐น 5.6.2 Limit Orderspub struct LimitOrder { pub order_id: u64, pub owner: Pubkey, pub token_mint: Pubkey, pub side: OrderSide, // Buy or Sell pub amount: u64, pub limit_price: u64, // Price threshold (lamports per token) pub expiry: i64, pub status: OrderStatus, } pub enum OrderSide { Buy, Sell } pub enum OrderStatus { Open, Filled, Cancelled, Expired }
๐น 5.6.3 Swap Interfaceinterface SwapRequest { inputToken: 'SOL' | ST22Address; outputToken: 'SOL' | ST22Address; inputAmount: bigint; minOutputAmount: bigint; slippageTolerance: number; // Basis points deadline: number; // Unix timestamp } 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 }; }
๐ธ 5.7 Fee Structure and Distribution
๐น 5.7.1 Transaction Fee Breakdown
Every CEDEX swap incurs a5% total transaction fee(500 basis points):
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
TOTAL
5.00%
Complete fee structure
๐น 5.7.2 Fee Distribution Smart Contractpub fn distribute_fees( fee_amount: u64, issuer_treasury: &Pubkey, staking_pool: &Pubkey, protocol_treasury: &Pubkey, liquidity_pool: &Pubkey, ) -> Result<()> { const ISSUER_SHARE: u64 = 4000; // 40% of fee = 2.00% of trade const STAKING_SHARE: u64 = 3000; // 30% of fee = 1.50% of trade const PROTOCOL_SHARE: u64 = 2120; // 21.2% of fee = 1.06% of trade const LP_SHARE: u64 = 880; // 8.8% of fee = 0.44% of trade 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 Ok(()) }
๐น 5.7.3 Fee Comparison Analysis
Platform
Swap Fee
Compliance
LP Rewards
Issuer Revenue
CEDEX
5.00%
โ Full Digital Securities
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, permanent liquidity growth, and full Digital Securities classification enforcement. For institutional securities trading, this represents significant cost savings versus traditional broker-dealer infrastructure.
๐ค 5.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.
๐น 5.8.1 Frontrunning Prevention
Private Transaction Submissionโ Transactions route through Jito's private mempool, invisible to searchers until block inclusionSlippage Enforcementโ Strict slippage limits (default 1%) reduce profitability of frontrunning attemptsCircuit Breaker Integrationโ 2% price impact limit prevents large frontrun trades from executing
๐น 5.8.2 Sandwich Attack MitigationAttack Requirement: CEDEX Defense: Buy before victim โโโ Private mempool (not visible) Victim trade โโโ Jito bundle (atomic โ cannot be inserted between) Sell after victim โโโ 2% circuit breaker limits residual profitability
๐น 5.8.3 Jito Bundle Integration
Feature
Implementation
Bundle Submission
All CEDEX trades submitted as Jito bundles with guaranteed atomicity
Private Mempool
Transactions invisible until block inclusion
Priority Fees
Dynamic priority fee calculation for reliable inclusion
Backrun Protection
Bundle structure prevents insertion between compliance verification and execution
โก Jito Bundle MEV Protection โ Technical Specification
Version: 6.1 | Applies To: All CEDEX trade submissions
Bundle Failure Handling
Failure Mode
Cause
CEDEX Response
Bundle timeout (>10 slots)
Network congestion or low tip
Resubmit with 2ร tip โ up to 3 attempts
Bundle simulation failure
Transfer Hook rejection
Return hook error code to user โ no resubmit
Block engine unreachable
Jito infrastructure outage
Fallback to standard RPC submission with priority fee
Bundle partially included
Should not occur (atomic guarantee)
Log as critical alert โ investigate immediately
Fallback Mode:If Jito block engine is unavailable for >30 seconds, CEDEX automatically falls back to standard priority-fee RPC submission via Helius. In fallback mode, MEV protection is degraded โ CEDEX displays a"MEV Protection Degraded"banner in the trading UI and logs all fallback transactions for post-incident review.
Sandwich Attack Prevention โ Mathematical Proof
A sandwich attack requires inserting a buy transaction before and a sell transaction after the victim's trade. Jito bundles make this impossible because:
The victim's transaction is invisible in the public mempool โ it exists only in Jito's private relay networkThe bundle is atomic โ no transaction can be inserted between bundle transactions by any party including validatorsEven if the bundle contents leak, the attacker cannot front-run because the bundle tip gives the victim's bundle priority over unbundled transactions
Residual risk:A malicious Jito validator with block production rights could theoretically see bundle contents and sandwich around the entire bundle. This risk is mitigated by: (a) CEDEX's2% price impact circuit breaker(Hook 5) limits sandwich profitability to near-zero, and (b) Jito's validator reputation system and slashing mechanisms disincentivize this behavior.
โก 5.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
๐๏ธ 5.10 Security Architecture
Smart Contract Security
Formal verification using Certora ProverSecurity audits by Quantstamp ยท Halborn ยท OtterSecActive bug bounty program (up to $100K rewards)Immutable core contracts post-deployment
Economic Security
Circuit breakers prevent flash loan attacksTWAP oracle resists price manipulationPermanent liquidity locks prevent rug pullsVolume limits prevent coordinated dumps
Operational Security
Multi-signature admin keys (4-of-7 threshold)48-hour timelock on all parameter changesReal-time monitoring and alertingIncident response playbooks documented and tested
Groovy Company, Inc. dba OTCM Protocol ยท Wyoming Corporation ยท invest@otcm.io ยท otcm.io
๐ The OTCM trading interface โ a purpose-built Centralized-Decentralized Exchange combining Web2 order matching with Web3 settlement finality, natively supporting SPL Token-2022 Transfer Hooks.
๐ก 5.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.
๐น 5.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. 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, and 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 friction (latency), complexity (integration requirements), and 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.
๐น 5.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.
๐น 5.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:
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.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.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.
๐น 5.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)
4.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.
๐น 5.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.
// Dual-Layer Architecture Diagram โ---โ โ 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 โ โ โ โ---โ โ โ---โ
๐น 5.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
// 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
๐น 5.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:
// 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,
})
}
๐น 5.2.4 Layer Synchronization Protocol
The two layers synchronize through a handoff protocol ensuring atomic execution guarantees:
Verification Request: User initiates swap, generating unique transfer_idParallel Processing: UI displays "Verifying compliance..." while hooks executeVerification Complete: All hooks pass, verification_status set to VERIFIEDExecution Authorization: Trading layer receives signed verification confirmationAtomic Swap: CPMM calculation and token transfer execute in single transactionSettlement: 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.
๐๏ธ 5.2 Dual-Layer Execution Architecture
๐น 5.2.1 Dual-Layer Execution ModelCEDEX implements a dual-layer architecture combining a centralized order management system with decentralized on-chain settlement. The centralized layer
handles order matching, price discovery, and user interface at sub-100ms latency. The decentralized layer handles actual asset custody, transfer execution, and Transfer Hook enforcement on Solana. This architecture deliversprovides Web2-grade user experiencewithโ sub-100ms order matching, real-time price feeds, and a professional trading interface. The decentralized layer provides Web3-grade settlementfinality.finality โ atomic Transfer Hook enforcement and irreversible on-chain settlement on Solana.
Layer
Function
Technology
Centralized OMS
Order
matching,matching ยท pricefeeds,discoveryUIยท user interfaceOTCM matching engine + REST API
Pre-flight Compliance
VerificationKYC/AML
status,status check ยท accreditationcheckverificationLayer 2 Transfer Hook pre-check against Empire registry
Decentralized Settlement
Asset
transfer,transfer ยท all 42 Transfer Hookexecution,controls ยท finalitySolana + SPL Token-2022
๐น5.5.15.2.2Compliance Verification LayerBefore any trade executes on-chain, CEDEX runs a pre-flight compliance check against the investor's current verification
status.statusThis check queriesin theIssuersEmpirePortalStockcomplianceTransferstateregistry.in real-time. TradersInvestors with lapsed KYC, expiredaccreditation,accreditationorcertification, flagged AMLstatusstatus, or OFAC/SDN matches are blocked attheorder entrystageโ before any on-chain transaction isattempted โattempted, preventing failed transactions and wastedgas.fees. The pre-flight check is in addition to, not a replacement for, the on-chain Transfer Hook enforcement.
Order
Hook
Oracle Source
Target Latency
Failure Action
1
Custody Verification โ Control 1
Empire Stock Transfer API (~400ms refresh)
100โ150ms
Revert 6001
2
OFAC Screening โ Controls 8โ10
OFAC SDN Oracle (hourly refresh)
200โ500ms
Revert 6003โ6005
3
AML Analytics โ Control 11
Chainalysis / TRM Labs
300โ400ms
Revert 6006
4
Accreditation & KYC โ Controls 12โ18
Empire investor registry
50โ100ms
Revert 6004
5
Holding Period Lock โ Control 24
On-chain HoldingPeriodAccount
< 10ms
Revert 6024
6
Price Impact Limit โ Control 25
TWAP Oracle
50โ100ms
Revert 6006
7โ42
Extended Controls
Various
Parallel
Various 60XX
๐น5.5.25.2.3Trading Execution LayerApproved orders are submitted to the Solana network as signed transactions. The SPL Token-2022 Transfer Hook extensions execute atomically with settlement โ there is no separation between trade execution and compliance enforcement. If any of the 42 Transfer Hook controls reject the transaction, it reverts entirely with a specific error
codecode.enablingTherapidtransactiondiagnosis.either completes fully with all compliance verified, or it does not complete at all.
pub fn execute_swap(
ctx: Context<Swap>,
input_amount: u64,
min_output: u64,
deadline: i64,
) -> Result<()> {
// Deadline check
require!(Clock::get()?.unix_timestamp <= deadline, SwapError::DeadlineExceeded);
// CPMM calculation
let result = calculate_output_amount(
input_amount,
ctx.accounts.pool.sol_reserve,
ctx.accounts.pool.token_reserve,
500, // 5% fee in bps
)?;
// Slippage check
require!(result.output_amount >= min_output, SwapError::SlippageExceeded);
// Distribute fee โ 5 recipients
distribute_fees(result.fee_amount, &ctx.accounts.fee_recipients)?;
// Token transfer โ Transfer Hook invoked here automatically by Token-2022
// All 42 controls execute atomically before this returns
token_transfer(result.output_amount, &ctx)?;
emit!(SwapExecuted { input: input_amount, output: result.output_amount });
Ok(())
}
๐น5.5.35.2.4Layer Synchronization ProtocolThe centralized OMS maintains a real-time synchronized view of on-chain state through OTCM's dedicated Helius RPC node cluster. Order book updates reflect confirmed on-chain settlements within 400ms
(โ one Solanablock).blockThisโsynchronization ensuresensuring no price discrepancy between displayed quotes and executable on-chain pricesduringunder normal network conditions.
๐ 5.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: enabling initial price discovery in a controlled environment, preventing flash crashes and wash trading during early trading, and providing favorable entry prices for early community participants.
๐น 5.4.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 โ---โ โ BONDING CURVE PRICE DISCOVERY โ โ---โ Price โ (USD) โ โญ--- Graduation โ โญ---โฏ Threshold $0.15โ โญ---โฏ ($250K MC) โ โญ---โฏ $0.10โ โญ---โฏ โ โญ---โฏ $0.05โ โญ---โฏ โ โญ---โฏ $0.01โ_____________________โญ---โฏ โ โญ---โฏ $0.001โ______________โญ---โฏ โ---โด---โบ
Tokens Issued (millions)
โโ--- Early Buyers ---โบโโ--- Growth Phase ---โบโโ--- Graduation ---โบ โ
๐น 5.4.2 Linear Bonding Curve Mathematics
CEDEX implements a linear bonding curve formula providing predictable price appreciation as token adoption increases:
// Bonding Curve Price Formula // 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: // At 0 tokens sold: P = $0.001 + (0.00001 ร 0) = $0.001 // At 1M tokens sold: P = $0.001 + (0.00001 ร 1,000,000) = $0.011 // At 10M tokens sold: P = $0.001 + (0.00001 ร 10,000,000) = $0.101 // At 25M tokens sold: P = $0.001 + (0.00001 ร 25,000,000) = $0.251
Implementation
// 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 { // 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)
}
}
๐น 5.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.
๐น 5.4.4 Transition to Permanent AMM
Upon graduation, the following irreversible state transitions occur:
Bonding Curve Deactivation: Smart contract permanently disables bonding curve purchase/sale functions through immutable state flagLiquidity Migration: All SOL accumulated in bonding curve reserve transfers to CEDEX CPMM poolPool Initialization: CPMM pool initializes with graduated token supply and migrated SOL reservePermanent Lock: Liquidity becomes permanently lockedโcannot be withdrawn by any party including protocol administrators
// Graduation Function (Rust/Anchor) pub fn graduate_to_amm(ctx: Context) -> 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.
๐
๐ข CPMM ARITHMETIC PRECISION SPECIFICATION
Version:6.0 |Applies To:Layer 4 AMM โ All swap calculations
u128 Overflow-Safe Arithmetic
The CPMM formulax ร y = krequires multiplying two u64 reserve values. The maximum u64 value is 2โถโด โ 1 = 18,446,744,073,709,551,615. Multiplying two maximum u64 values produces a value requiring 128 bits. All intermediate CPMM calculations MUST use u128 arithmetic to prevent overflow.
rust
Atomicity Guarantee
If
///complianceOverflow-safeverificationCPMMcompletesswapbutoutputexecutioncalculationfails/// Uses u128 intermediate arithmetic throughout pub fn calculate_swap_output( amount_in: u64, reserve_in: u64, reserve_out: u64, fee_bps: u16, // Fee in basis points (500 = 5%) ) -> Result { // Cast to u128 BEFORE any multiplication let amount_in_u128 = amount_in as u128; let reserve_in_u128 = reserve_in as u128; let reserve_out_u128 = reserve_out as u128; let fee_numerator = 10_000u128 - fee_bps as u128; // e.g. 9_500โ for5%example, slippage exceeded, deadline passed, or insufficient balance โ the entire transaction reverts atomically. No partial state changes persist. Investors never face a situation where compliance verification succeeds but tokens transfer incorrectly, or where a fee// Apply fee to input amount (fee taken from input) let amount_in_with_fee = amount_in_u128 .checked_mul(fee_numerator) .ok_or(AmmError::Overflow)?; // Numerator: amount_in_with_fee ร reserve_out ร 10_000 // (multiply by 10_000 to preserve fee precision) let numerator = amount_in_with_fee .checked_mul(reserve_out_u128) .ok_or(AmmError::Overflow)?; // Denominator: (reserve_in ร 10_000) + amount_in_with_fee let denominator = (reserve_in_u128 .checked_mul(10_000u128) .ok_or(AmmError::Overflow)?) .checked_add(amount_in_with_fee) .ok_or(AmmError::Overflow)?; // Division โ floor (conservative โ output slightly less than theoretical) let amount_out_u128 = numerator .checked_div(denominator) .ok_or(AmmError::DivisionByZero)?; // Safe downcast โ output cannot exceed reserve_out (u64) u64::try_from(amount_out_u128).map_err(|_| error!(AmmError::Overflow)) } /// Maximum reserve size before precision degradation /// At reserve = 10^15 tokens (1 quadrillion), intermediate u128 values reach: /// numerator max โ (10^15)^2 ร 10^4 = 10^34 โ within u128 range (3.4 ร 10^38) /// Maximum safe reserve per token: 10^15 units (with 9 decimal places = 10^6 whole tokens) pub const MAX_SAFE_RESERVE: u64 = 1_000_000_000_000_000; // 10^15 /// Invariant verification after every swap โ must hold within rounding tolerance pub fn verify_invariant( old_k: u128, new_reserve_in: u64, new_reserve_out: u64, ) -> Result<()> { let new_k = (new_reserve_in as u128) .checked_mul(new_reserve_out as u128) .ok_or(AmmError::Overflow)?; // k should be equal or slightly larger (fees increase k) // Tolerance: 1 unit of precision (rounding) require!( new_k >= old_k.saturating_sub(1), AmmError::InvariantViolation ); Ok(()) }
Rounding Policy
Operation
Rounding Direction
Rationale
amount_out
calculation
Floor (truncate)
Trader receives slightly less โ protocol never over-pays
amount_in
calculation (exact output)
Ceiling
Trader pays slightly more โ protocol never under-receives
Fee calculation
Floor
Slightly less feeis collectedโ conservative
LP share calculation
Floor
LP receives slightly less โ prevents LP share inflation
Invariant guarantee:Floor rounding onamount_outensuresnew_k โฅ old_kafter every swap. This means the product invariant can only increase or stay equal, never decrease. This is a stronger guarantee than the theoretical constant product formula implies.
Maximum Safe Operating Parameters
Parameter
Maximum Safe Value
Notes
Single reserve
10ยนโต tokens (u64)
Beyond this, consider reserve splitting
Single swap amount
20% of reserve
Circuit breaker enforces this (Hook 5)
k value
~10ยณโฐ
Well within u128 range (3.4 ร 10ยณโธ)
Cumulative k growth
Unbounded (fees)
k can only grow โ no maximum
๐น 5.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 priceswithoutrequiring traditional order books or market makers.
๐น 5.4.1 CPMM Mathematical Foundation
The CPMM maintains the invariant k = x ร y, where:
x = SOL reserve in the liquidity pooly = ST22 token reserve in the liquidity poolk = 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)
๐น 5.4.2 Price Impact Calculation
Price impact measures how mucha trademoves the market price. Larger trades relative to pool reserves create larger price impacts:executing.
//PriceImpact 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()
}
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
Note:Examples assume 100 SOL pool reserve. Circuit breaker activates at >2% price impact.
๐น5.6
5.4.3Slippage Protection
CEDEX provides configurable slippage protection ensuring users receive expected value:
// 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(())
}
๐น 5.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
๐๏ธ 5.5Circuit Breaker ArchitectureCEDEX implements a comprehensive circuit breaker system protecting Digital Securities markets from manipulation, flash crashes, and coordinated attacks.
InspiredModeledbyon traditional securities exchange mechanisms(โ NYSE Rule 80B, NASDAQ haltprocedures),procedures โ these protections operate at the smart contract levelwiththrough the Transfer Hook architecture. There is no administrative override capability.
๐น5.6.15.5.1Price ImpactLimitsLimit โ Control 25rejected.
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 automaticallyrejected:
// 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
mechanismforcesmarket participants to provide liquidity gradually versus attempting sudden massive liquidation. Largelarge sellersmustto split orders across multiple transactions, allowing the market to absorb supplyincrementally.incrementally rather than experiencing sudden price dislocations.
pub const MAX_PRICE_IMPACT_BPS: u16 = 200; // 2% maximum
pub fn check_price_impact(
proposed_trade: &SwapParams,
twap: u64,
current_price: u64,
) -> Result<()> {
let deviation_bps = ((current_price as i64 - twap as i64).abs() as u64)
.checked_mul(10_000)
.ok_or(CedexError::Overflow)?
/ twap;
require!(
deviation_bps <= MAX_PRICE_IMPACT_BPS as u64,
CedexError::PriceImpactExceeded // Error 6006
);
Ok(())
}
Trade Size (% of pool)
Price Impact
Circuit Breaker Status
1%
~0.99%
โ Allowed
2%
~1.96%
โ Allowed
3%
~2.91%
โ Blocked โ 6006
5%
~4.76%
โ Blocked โ 6006
๐น5.6.25.5.2Volume-BasedHaltsHalt โ Control 27If any single wallet attempts to sell
greatermore than 30% of circulating ST22 supply within a 24-hourperiod,window,transactiontradingexecutionforpausesthat wallet is suspended for 24hours:hours. This prevents coordinated dump scenarios while allowing normal institutional-size trading.
//
Volume-BasedHaltImplementationpub const MAX_DAILY_SELL_PERCENT: u8 = 30; // 30%
maxofdailycirculatingsalesupplypub const HALT_DURATION_SECONDS: i64 =
86400;86_400; // 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>,
}
pubfncheck_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(())
}
๐น5.6.35.5.3Coordinated Activity DetectionCEDEX implements
machine learning-ML-based detection of coordinated sellingpatternspatterns.suggesting manipulative intent. The algorithm analyzes fourFour correlationdimensions:dimensions are analyzed on every trade:
Dimension
Analysis Method
Suspicious Threshold
Wallet
ClusteringclusteringGraph analysis of common funding sources
>More than 5 wallets sharing a funding sourceTiming
CorrelationcorrelationTransaction timestamp clustering
>More than 3 sells within a 10-second windowAmount
CorrelationcorrelationStatistical analysis of sale sizes
<Less than 5% variance across multiple coordinated salesPrice
ImpactimpactCorrelationcorrelationSequential impact accumulation
Cumulative
>impact exceeding 5% within 1 hour
When coordinated activity is detected, affected wallets enter 24-hour cooldown
periods,periods and the compliance team receives alerts for manual review. Confirmed coordinated manipulation results in permanent blacklisting via Transfer Hook Control 34 (account frozen).
๐น5.6.45.5.4Time-Weighted Average Price (TWAP)TWAP OracleThe TWAP oracle provides manipulation-resistant price data for all circuit breaker
calculations.calculations:The
rolling//oracleTWAPmaintainsOracleaImplementation
pub struct TwapOracle {
pub token_mint: Pubkey,
pub price_observations: Vec<PriceObservation>,of
pub observation_window: i64, // 11-hourinwindowseconds
pubpricemin_observations:observationsu32,with//aMinimumminimum of 60 observations required for a valid TWAP calculation. Any attempt to manipulate the spot price โ for example, to create artificial circuit breaker conditions โ is absorbed by the time-weighted average, which requires sustained manipulation across the full observation window to move.
}
impl TwapOracle {
pub fn calculate_twap(&self) -> Result { 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)
}
}
๐5.75.6Order Types and Execution
CEDEX5.7.1
supportsmultiple order types optimized for different trading strategies while maintaining compliance verification for all executions.Market Orders
๐น 5.6.1
Market orders execute immediately at current pool prices, subject to slippage tolerance:Parameter
Specification
Parameter
SpecificationExecution
SpeedspeedImmediate
(โ subject to complianceverificationpre-flight (~2-2โ3seconds)seconds total)Price
GuaranteeguaranteeNone โ executes at current CPMM pool price
Slippage
ProtectionprotectionConfigurable (default 1%,
maxmaximum 5%)Partial
FillsfillsNot supported โ all-or-nothing execution
Circuit
BreakerbreakerRejects if price impact exceeds 2% TWAP deviation
๐น5.7.25.6.2Limit OrdersLimit orders specify a maximum buy price or minimum sell price, executing only when the CPMM pool price reaches the specified
threshold:threshold. All 42 Transfer Hook controls execute at the moment of limit order settlement โ limit orders do not pre-authorize compliance status. If a wallet's KYC or accreditation has lapsed between order placement and execution, the settlement transaction reverts.
//
LimitOrderData Structurepub struct LimitOrder {
pub order_id: u64,
pub owner: Pubkey,
pub token_mint: Pubkey,
pub side: OrderSide, // Buy
or| Sellpub amount: u64, // Token amount
pub limit_price: u64, //
Price threshold (lamportsLamports pertoken)tokenpub expiry: i64, // Unix timestamp
pub status: OrderStatus, // Open | Filled | Cancelled | Expired
}
pubenumOrderSide{
Buy,// Execute when pool price <= limit_price
Sell, // Execute when pool price >= limit_price
}
pub enum OrderStatus {
Open,
Filled,
Cancelled,
Expired,
}
๐น 5.6.3 Swap Interface
The primary trading interface presents unified swap functionality:
// Swap Interface (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
};
}
๐ธ5.85.7Fee Structure and Distribution
CEDEX5.8.1
implementsa 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.Transaction Fee Breakdown
๐น 5.7.1Every CEDEX swap incurs a 5% total transaction fee (500 basis points)
,distributedconfiguredasatfollows:the SPL Token-2022 Transfer Fee Extension level โ it cannot be bypassed by any wallet or trading interface. Distribution is automatic and on-chain:
Fee
ComponentRecipientRate
BPS
Purpose
Lock Status
Issuer
Allocationtreasury2.00%
200
Revenue
sharetoissuingtokenizing companytreasuryโ accrues per tradeWithdrawable by issuer
StakingOTCMRewardsstaking pool1.50%
150
Distributed to OTCM
tokenstakers(8-โ 8โ60%APY)APYDistributed per epoch
Protocol
Operationsoperations1.06%
106
Infrastructure, compliance oracles, development
LiquidityWithdrawablePool Growth
0.44%
Permanently locked inby OTCMLPProtocolforGlobal Unified CEDEX Pool
0.44%
44
Permanent pool depth โ routes to Global Pool
PERMANENTLY LOCKED
TOTAL
5.00%
Complete500feestructureโ
โ
๐น5.8.25.7.2FeeDistribution MechanismJustification
// 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)
// 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(())
}
๐น 5.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
WhileCEDEX's 5% fee significantly exceedstraditionalstandard DEXfees,fees.itTheincludespremiumcomprehensivereflectscompliancetheverificationgenuine(infrastructure cost and value delivered: each trade incurs $2-2โ5per transactionin oraclecosts)verification costs (Empire custody attestation, OFAC/SDN screening, AML scoring, TWAP price feed), funds issuer revenuesharing,sharingandthat makes the platform commercially viable for tokenizing companies, contributes permanent liquiditygrowth.depth to the Global Pool, and enforces the full Digital Securities compliance framework that makes the tokens legally tradeable in the first place. For institutional securities trading,this5%representscomparessignificantfavorably to the 7โ10% all-in costsavings versusof traditional broker-dealerinfrastructure.infrastructure for comparable compliance-grade execution.
๐ค5.95.8MEV ProtectionMaximum Extractable Value (MEV) attacks
representposeoneaofmaterialthe most significant threatsrisk toDeFiinstitutionalusers, with an estimated $1.38 billion extracted from tradersinvestors in2023anyalone.blockchain trading environment. CEDEX implements multiple independent protection layers making MEV extraction economicallyunfeasible.unfeasible against ST22 trades.
๐น5.9.15.8.1Frontrunning 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:
Private Transaction Submission: Transactions route through Jito's private mempool, invisible to searchers until block inclusionSlippage Enforcement: Strict slippage limits (default 1%) reduce profitability of frontrunning attemptsCircuit Breaker Integration: 2% price impact limit prevents large frontrun trades from executing
๐น 5.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 Prevention // 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
๐น 5.8.3Jito Bundle Integration
CEDEX integrates with Jito's block-building infrastructure for institutional-grade MEV protection:Feature
Implementation
Feature
ImplementationBundle
SubmissionsubmissionAll CEDEX trades submitted as Jito bundles with guaranteed atomicity โ the trade either executes as a complete unit or not at all
Private
MempoolmempoolTransactions are invisible to searchers until block inclusion
(โ no public mempoolexposure)exposure windowPriority
FeesfeesDynamic priority fee calculation
forensures reliable block inclusion under network congestionBackrun
ProtectionprotectionBundle structure prevents insertion of any transaction between compliance verification and trade execution
โก
JITOBUNDLE5.9.2
MEVPROTECTIONSandwich Attack Prevention โTECHNICALStructuralSPECIFICATION
Version:6.0 |Applies To:All CEDEX trade submissions
Bundle Construction ArchitectureProof
EveryACEDEXsandwichtradeattackisrequiressubmitted asinserting a buy transaction before and a sell transaction after the victim's trade. Jito bundle architecture makes this structurally impossible:
โข Private relay โ
aThegroupvictim'softransaction is invisible in the public mempool โ it exists only in Jito's private relay network until block inclusionโข Atomic bundle โ No transaction can be inserted between bundle transactions
thatbyareanyatomicallyparty,includedincluding validatorsโข Priority guarantee โ Even if bundle contents were somehow leaked, the bundle tip gives the victim's transaction priority over any unbundled front-run attempt
โข Circuit breaker backstop โ Even in
atheblockworstor entirely excluded. This eliminatescase, themempool2%visibilitypricewindowimpactthatcircuitenablesbreakerfrontrunning(Controland25) limits the economic value extractable from any individual trade, making sandwichattacks.attacks unprofitable even if technically executable
typescript
5.9.3
FallbackinterfaceJitoBundleConfig{ // Jito block engine endpoints (regional for latency) blockEngineUrl: string; // "https://mainnet.block-engine.jito.wtf" // Tip account โ paid to Jito validators for bundle inclusion priority tipAccount: PublicKey; // Jito tip account (rotated by Jito Labs) tipLamports: bigint; // Dynamic โ see tip calculation below // Bundle composition transactions: VersionedTransaction[]; // [0]: tip tx, [1..n]: trade txs // Expiry โ bundle dropped if not included within window expirySlotOffset: number; // 10 slots (~4 seconds) โ configurable } // Tip calculation โ proportional to trade size for priority function calculateTipLamports(tradeSizeUsd: number): bigint { const BASE_TIP_LAMPORTS = 10_000n; // ~$0.001 at $100 SOL const SIZE_MULTIPLIER = 0.0001; // 0.01% of trade value const solPriceUsd = getCurrentSolPrice(); const sizeTip = BigInt( Math.floor((tradeSizeUsd * SIZE_MULTIPLIER / solPriceUsd) * 1e9) ); return BASE_TIP_LAMPORTS + sizeTip; }
Bundle Failure HandlingMode
FailureIfMode
Cause
CEDEX Response
Bundle timeout (>10 slots)
Network congestion or low tip
Resubmit with 2x tip โ up to 3 attempts
Bundle simulation failure
Transfer Hook rejection
Return hook error code to user โ no resubmit
Block engine unreachable
Jito infrastructure outage
Fallback to standard RPC submission with priority fee
Bundle partially included
Should not occur (atomic guarantee)
Log as critical alert โ investigate immediately
Fallback Mode:Ifthe Jito block engine is unavailable for>more than 30 seconds, CEDEX automatically falls back to standard priority-fee RPC submission via Helius. In fallback mode, MEV protection isdegraded โdegraded. CEDEX displays a"'MEV ProtectionDegraded"Degraded' banner in the tradingUIinterface and logs all fallback transactions for post-incident compliance review.
Sandwich
Attack Prevention โ Mathematical Proof
A sandwich attack requires an attacker to insert a buy transaction before and a sell transaction after the victim's trade. Jito bundles make this impossible because:
The victim's transaction is invisible in the public mempool โ it exists only in Jito's private relay networkThe bundle is atomic โ no transaction can be inserted between bundle transactions by any party including validatorsEven if the bundle contents leak, the attacker cannot front-run because the bundle tip gives the victim's bundle priority over unbundled transactions
Residual risk:A malicious Jito validator with block production rights could theoretically see bundle contents and sandwich around the entire bundle. This risk is mitigated by: (a) CEDEX's 2% price impact circuit breaker (Hook 5) limits sandwich profitability to near-zero, and (b) Jito's validator reputation system and slashing mechanisms disincentivize this behavior.
โก5.105.9Performance Specifications
Metric
Specification
Notes
Throughput
(TPS)400โ600 TPS
400-600Limited by compliance verification oracle latency
CompliancePre-flightLatencycompliance2,
000-000โ3,000msSix primary hooks + oracle queries โ runs before on-chain submission
Execution
Latencylatency
400-400โ600msCPMM swap post-verification
Block
Finalityfinality~13 seconds
32 Solana
blocksblock confirmationsCompute
Unitsunits~800,000 CU
Per complete swap transaction including all 42 Transfer Hook controls
Network
Feefee~$0.
01-01โ$0.05Solana base fee + dynamic priority fee
Order book sync
400ms
One Solana block โ Helius RPC cluster synchronization
๐๏ธ5.115.10Security Architecture
CEDEX5.11.1
securitycombines smart contract hardening, economic attack resistance, and operational security measures:Smart Contract SecurityDocumented and tested runbooks for P0 (active exploit), P1 (service degradation), P2 (partial failure), and P3 (monitoring alerts)
โข Formal verification โ CEDEX and Custom AMM pool logic formally verified using Certora Prover
Securityprior to production deploymentโข Independent audits
byโ Quantstamp, Halborn, and OtterSecActivebugโ audit reports published publicly. CEDEX-specific scope: CPMM arithmetic, fee routing, circuit breaker logic, Transfer Hook integration pointsโข Bug bounty program
(upโ Up to $100Krewards)- rewards for critical vulnerability reports. Priority targets: price impact calculation exploit, fee routing bypass, CPMM invariant violation, circuit breaker bypass
โข Immutable core contracts
post-deploymentโ CEDEX and AMM pool contracts use no upgrade proxy pattern โ eliminating the attack surface where an upgrade could introduce unauthorized fund extraction
5.11.2 Economic Security
โข Flash loan attack prevention โ Circuit breakers (price impact + volume halt) prevent the large coordinated trades required to make flash loan attacks
- profitable
โข Price manipulation resistance โ TWAP oracle
resistsrequires sustained manipulation across a 60-observation, 1-hour window to move the circuit breaker reference pricemanipulationPermanentโข
liquidityCoordinatedlocksdump prevention โ Volume halt (30% daily limit per wallet) and coordinated activity detection preventrugthepullsVolumemulti-walletlimitsstrategiespreventusedcoordinatedindumpsorganized market manipulationโข Wash trading detection โ Timing correlation and amount correlation analysis identifies and blacklists wash trading patterns
5.11.3 Operational Security
โข Multi-signature admin
keysโ(4-of-7threshold)- threshold for any parameter change โ geographically distributed key holders
โข 48-hour timelock
onโ All governance-approved parameter changes- subject to 48-hour timelock before execution
โข Real-time monitoring
andโalerting- Automated anomaly detection on all CEDEX order flow with incident escalation to compliance team
โข Incident response
playbooksโ---
Groovy Company, Inc. dba OTCM Protocol | CIK: 1499275 | Version 7.0 | March 2026 | Confidential
Back to top