Skip to main content

🔐 Section 3: SPL Token-2022 Transfer Hooks — Layer 2


🔐 The security primitive at the heart of OTCM Protocol — 42 mathematically enforced controls that execute atomically on every ST22 token transfer via SPL Token-2022 Transfer Hook extensions.


🔐 SECTION 3: SPL TOKEN-2022 TRANSFER HOOKS

💡 3.1 🚀 Architectural Innovation

CEDEXSPL (Centralized-DecentralizedToken-2022 Exchange)Transfer representsHooks represent a fundamental reimaginingarchitectural innovation in blockchain-based securities infrastructure, enabling execution of decentralizedarbitrary exchangesmart architecture,contract purpose-builtcode during token transfers on the Solana blockchain. This capability transforms compliance from inceptiona fordiscretionary tradingadministrative tokenizedfunction securitiesinto withinan immutable, mathematically-enforced property of the token itself.

OTCM Protocol leverages Transfer Hooks to implement federal securities law frameworks.requirements Unlikeas existingnon-discretionary DEXsmart platformscontract thatcode, werecreating designeda forparadigm permissionlesswhere cryptocurrencyregulatory tradingcompliance andis subsequentlynot facea irreconcilablematter conflictsof withcorporate securitiespolicy regulation,but CEDEXof implementscryptographic certainty. Every ST22 transfer triggers sequential execution of six independent verification hooks, completing comprehensive compliance verification asbefore atransaction foundational architectural constraint rather than retrofitted functionality.settlement.

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 SPL TheToken-2022 DEXStandard Incompatibility ProblemOverview

StandardSPL decentralizedToken-2022 exchanges—including(also marketknown leadersas Raydium,Token Orca,Extensions Jupiter,Program) andis Meteora—wereSolana's architectednext-generation aroundtoken threestandard, foundationalintroducing designprogrammable principlesextensions that createenable irreconcilablesophisticated conflicttoken functionality impossible with securitiesthe laworiginal compliance:

SPL
Token

⚡ 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.Program:

MetricExtension

Traditional DEXCapability

WithOTCM Transfer HooksUsage

🔢Transfer Compute UnitsHook

~200,000Execute CUcustom logic on every transfer

~800,000+42 CUsecurity controls, compliance verification

📉Permanent ImpactDelegate

BaselineIrrevocable transfer authority

4xProtocol-level increaserecovery capability

Confidential Transfers

Zero-knowledge encrypted amounts

Future: Privacy-preserving compliance

Transfer Fee

Protocol-level fee collection

5% fee distribution automation

Metadata Pointer

On-chain token metadata

Security details, issuer info, CUSIP

Non-Transferable

Soulbound token capability

Compliance NFTs, investor credentials

A

🔹 typical Raydium swap executes in approximately 200,000 compute units; adding six3.1.2 Transfer Hook verificationsExtension 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 TokensMechanism

Beyond philosophical design conflicts, existing DEX codebases face concrete technical barriers preventing ST22 token support:

DEX Platform

🪙 Token-2022 Support

🪝The Transfer Hook Support

🔴extension Raydium

Partialenables (basictoken transfersmints only)

to Nonespecify a hooksprogram disabled

🔴that Orca

Limitedmust (whitelist)

be Noneinvoked during notevery implemented

🔴token Jupiter

Aggregatestransfer. underlyingThis DEXs

mechanism Noneoperates at inheritsthe limitations

🔴Solana Meteora

Basicruntime support

level, Nonemaking it bypassed

🟢impossible

CEDEX

Full native support

Full — 6 hooks perto transfer tokens without executing the hook program:

The core technical issue: existing DEX codebases were written before

// SPL Token-2022 existed.Transfer TheirHook smartMechanism
contracts interact directly with the original SPL Token Program, which lacks// Transfer Hook extensions.Extension RetrofittingData Structure

pub struct TransferHook {

/// The program ID that implements the transfer hook

pub program_id: Pubkey,

/// Optional: Authority that can update the hook program

pub authority: Option<Pubkey>,

}

// When a transfer occurs, Solana runtime automatically:
// 1. Checks if mint has TransferHook extension
// 2. If yes, invokes the specified program_id with transfer context
// 3. If hook returns error, ENTIRE transaction reverts
// 4. If hook succeeds, transfer completes
// This is MANDATORY - there is no way to bypass the hook
// The token literally cannot move without hook approval

🔹 3.1.3 Compliance-as-Code Philosophy

OTCM's Transfer Hook supportimplementation 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—makingembodies the tokens"Compliance-as-Code" non-compliantphilosophy: securities.

regulatory
requirements

3.1.3are 🎯translated Theinto 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. Everydeterministic smart contract instruction,logic that executes identically every datatime, structure,without everyhuman executiondiscretion, pathadministrative wasoverride, designedor withinterpretation variability.

"Traditional compliance verificationasks: as'Did ayou first-classfollow requirement.

2️⃣

Optimizedthe Smartrules?' ContractOTCM's Architecture

SmartTransfer contractHooks architectureask: optimizes'Can foryou compliancemathematically executionprove fromcompliance?' 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 distinctionanswer betweenis compliance-firstalways andverifiable compliance-retrofitted architecture has profound implications for system reliability, security, and regulatory acceptance:on-chain."

Aspect

Traditional Compliance-First (CEDEX)Compliance

Transfer Compliance-RetrofittedHook Compliance

⏱️

Verification TimingEnforcement

BeforePolicy-based, execution (blocking)discretionary

AfterCode-based, execution (non-blocking)deterministic

🚫Override

Non-Compliant TradesCapability

CannotAdmin executecan (impossible)bypass

ExecuteNo thenbypass flag for reviewpossible

📋Audit

Regulatory PostureTrail

PreventiveMutable controllogs, editable

DetectiveImmutable controlblockchain record

📝

Audit TrailVerification

EveryRequires tradetrust verifiedin on-chainoperator

Off-chainCryptographically logs (mutable)verifiable

🔧

System ComplexityConsistency

IntegratedVaries (singleby system)analyst/day

Fragmented100% (multipleidentical systems)execution

⚠️

Failure ModeTiming

Fail-safePost-trade review (no trade)T+n)

Fail-openPre-trade blocking (trade executes)T-0)


🔹

3.21.4 ⚖️Regulatory Custom AMM Architecture

Advantages

CEDEXTransfer implementsHook aexecution modifiedprovides Automatedregulatory Marketadvantages Makerunattainable (AMM)through architecturetraditional engineeredcompliance specificallyprocedures:

  • Immutable Audit Trails: Every compliance check is recorded on-chain with cryptographic proof of execution timestamp, inputs, and outcomes
  • Zero Discretion: Compliance decisions are algorithmic—no analyst judgment, no selective enforcement, no regulatory arbitrage
  • Real-Time Enforcement: Non-compliant transfers are blocked before execution, not flagged for review after the fact
  • Cryptographic Proof: Regulators can independently verify any historical compliance decision by replaying on-chain data
  • Continuous Operation: 24/7/365 enforcement with no business hours, holidays, or staffing gaps 💡 SEC Modernization Alignment

OTCM's Transfer Hook integration.architecture Unlikealigns traditionalwith AMMsSEC thatChair executeGensler's stated goal of 'bringing crypto into compliance' and the SEC Crypto Task Force's exploration of blockchain-native compliance mechanisms.

🔗 3.2 Transfer Hook Execution Flow

This section details the precise execution sequence when an ST22 token swapstransfer asis atomic operations, CEDEX separates compliance verificationinitiated, from trading execution into distinct architectural layers, enabling asynchronous compliance checking without blocking user interaction.action through final settlement.


🔹

3.2.1 🔀Hook Dual-LayerInvocation Sequence

When a user initiates an ST22 transfer, the following sequence executes:

// Sequential Hook Execution ModelFlow

The dual-layer execution model represents CEDEX's core architectural innovation: segregating compliance verification from trading execution while maintaining atomic transaction guarantees.

┌─────────────────────────────────────────────────────────────────────────┐
│                  🔀ST22 CEDEXTRANSFER DUAL-LAYERHOOK EXECUTION MODELSEQUENCE                  │
└─────────────────────────────────────────────────────────────────────────┘
👤

User RequestInitiates Transfer

│
▼
┌────────────────────────────────────────────────────────────────────┐
│  ⚖️SOLANA COMPLIANCERUNTIME: VERIFICATIONDetects LAYERTransferHook extension on ST22 mint     │
│  ┌──────────────────────────────────────────────────────────────┐Invokes OTCM │  │  ⏱️ Asynchronous Execution (2,000-3,000ms)                   │  │
│  │                                                              │  │
│  │Transfer Hook 1:Program 🔍 Custody                                          │  │
│  │      ▼                                                       │  │
│  │  Hook 2: 🚫 OFAC                                             │  │
│  │      ▼                                                       │  │
│  │  Hook 3: 🕵️ AML                                              │  │
│  │      ▼                                                       │  │
│  │  Hook 4: 🪪 KYC                                              │  │
│  │      ▼                                                       │  │
│  │  Hook 5: 📉 Price Impact                                     │  │
│  │      ▼                                                       │  │
│  │  Hook 6: 💧 LP Ratio                                         │  │
│  │                                                              │  │
│  │  Result: ✅ VERIFIED | ❌ REJECTED (with errortransfer code)         │  │context        │
└──────────────────────────────────────────────────────────────┘  │
└────────────────────────────────┬───────────────────────────────────┘
│
▼
┌────────────────────────────────────────────────────────────────────┐
│                    💹HOOK TRADING1: EXECUTIONCUSTODY LAYERVERIFICATION                  │
│                         (100-150ms)                              │
│  Query Empire Stock Transfer → Verify 1:1 backing → Error 6001   │
└────────────────────────────┬─────────────────────────────────────┘
│ PASS
▼
──────────────────────────────────────────────────────────────────┐
│                    HOOK 2: OFAC Synchronous Execution (400-600ms)SCREENING                        │
│                         (200-500ms)                              │
│  Check SDN List 1️⃣ ReceiveAddress verificationclustering confirmation Error │
│  │  2️⃣ Calculate CPMM output amount                            │  │
│  │  3️⃣ Update pool reserves atomically                         │  │
│  │  4️⃣ Execute token transfer                                  │  │
│  │  5️⃣ Distribute fees                                         │  │
│  │                                                              │  │
│  │  Result: ✅ EXECUTED | ❌ REVERTED                           │  │6002                │
└────────────────────────────┬─────────────────────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────────────────────────┐
│                    HOOK 3: AML ANALYTICS                         │
│                         (300-400ms)                              │
│  ML risk scoring → 200+ features → Error 6003                    │
└────────────────────────────┬─────────────────────────────────────
│ PASS
▼
┌──────────────────────────────────────────────────────────────────┐
│                    HOOK 4: REDEMPTION ELIGIBILITY                │
│                         (50-100ms)                               │
│  KYC status → Accreditation → 72hr cooling → Error 6004          │
└────────────────────────────┬─────────────────────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────────────────────────┐
│                    HOOK 5: PRICE IMPACT LIMIT                    │
│                         (50-100ms)                               │
│  Calculate impact → Compare TWAP → 2% threshold → Error 6006     │
└────────────────────────────┬─────────────────────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────────────────────────┐
│                    HOOK 6: LIQUIDITY SUFFICIENCY                 │
│                         (50-100ms)                               │
│  Check LP ratio → 150% minimum → Error 6007                      │
└────────────────────────────┬─────────────────────────────────────┘
│ PASS
▼
┌──────────────────────────────────────────────────────────────────┐
│                    ALL HOOKS PASSED                              │
│              Transfer executes, transaction commits              │
│                 Settlement: ~13 seconds (32 blocks)              │
└────────────────────────────────────────────────────────────────────

🔹

3.2.2 ⚖️Sequential Compliancevs VerificationParallel LayerExecution

TheOTCM Complianceimplements Verificationsequential Layerhook executesexecution duringrather everythan ST22parallel tokenfor transfer,critical implementingsecurity OTCM'sreasons:

six

Mode

Advantage

Trade-off

Sequential Transfer(OTCM)

Early exit on failure, deterministic order, simpler debugging

Higher latency (750-1,350ms total)

Parallel

Lower latency (~500ms total)

Non-deterministic, race conditions, wasted compute on early failures

Sequential execution ensures that if Hook 1 (Custody Verification) fails, Hooks in2-6 sequentialnever order.execute—saving Thisoracle layercosts operatesand asynchronouslycompute fromresources. It also provides deterministic error reporting: users always know which specific hook rejected their transaction.

🔹 3.2.3 Atomic Transaction Guarantees

Solana's account model provides atomic transaction guarantees: if any hook fails, the user'sentire perspective—verificationtransaction completionreverts occursas independentlyif ofit usernever action,occurred. enablingThere ais responsiveno interfaceintermediate despitestate comprehensivewhere tokens have transferred but compliance checking.verification is incomplete.

📋 Verification Flow

rust

// ComplianceAtomicity Verification Data Structure (Rust)
pub struct ComplianceVerification {
    pub transfer_id: Pubkey,Guarantee
// UniqueAtomic transferExecution identifier
    pub sender: Pubkey,Guarantee
// SourceScenario 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,     //A: All hooks passed
    Rejected {pass
// AtResult: leastTransaction onecommits, hooktokens failedmove, hook_number:state u8,updates
error_code:// u16,Scenario reason:B: String,Hook },3 }(AML) rejects due to risk score
// Result: ENTIRE transaction reverts
//   - No tokens moved
//   - No fees charged
//   - No state changes
//   - Error returned to user: 6003 (AML_RISK_EXCEEDED)
// There is NO partial execution state
// This is guaranteed by Solana runtime, not OTCM code

🪝

🔹 Hook3.2.4 Execution Sequence

Timing

Each Transfer Hook executes in strict sequence, with failure at any point causing immediate transaction reversion:

Diagram

OrderHook

HookMin Name(ms)

OracleMax Source(ms)

LatencyAvg (ms)

FailPrimary ActionBottleneck

1️⃣1. Custody Oracle

🔍 Custody Verification100

150

125

Empire StockAPI API

100-150ms

Revert 6001latency

2️⃣

🚫2. OFAC Screening

SDN List Oracle200

200-500ms500

Revert350

SDN 6002list size, clustering

3️⃣

🕵️3. AML Analytics

Chainalysis/TRM300

300-400ms400

Revert350

ML 6003inference time

4️⃣

🪪4. Redemption Eligibility

KYC Registry50

50-100ms100

Revert75

KYC 6004database lookup

5️⃣5. Price Impact

📉 Price Impact Limit50

100

75

TWAP Oracle

50-100ms

Revert 6006calculation

6️⃣6. LP Sufficiency

💧 Liquidity Ratio50

100

75

Pool Statestate read

TOTAL

50-100ms750

Revert1,350

1,050

Sequential 6007sum


🔗 3.3 Hook 1: Custody Verification Oracle

The Custody Verification Oracle confirms that all circulating ST22 tokens are backed by equivalent equity shares held at Empire Stock Transfer, the SEC-registered transfer agent providing qualified custody services for OTCM Protocol.

🔹 3.2.33.1 💹Oracle Trading Execution LayerArchitecture

The Tradingcustody Executionoracle Layeroperates receivesas verifieda tokenscryptographically-signed anddata executesfeed tradesfrom onlyEmpire uponStock successfulTransfer's completionregistry of all compliance verification. This layer implements the Constant Product Market Maker (CPMM) formula for price discovery and liquidity provision.systems:

🔢 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

// CPMMCustody SwapOracle CalculationData (Rust)Structure

pub fnstruct calculate_swap_output(CustodyOracleData input_amount:{

u64, input_reserve: u64, output_reserve: u64, fee_bps: u16,
/// BasisCIK pointsnumber (500of =the 5%)issuing )company
->

pub Result<SwapResult>issuer_cik: {[u8; 10],

/// ApplyCUSIP feeidentifier tofor inputthe letsecurity
fee_multiplier

pub =cusip: 10000[u8; -9],

fee_bps as u64; let input_with_fee = input_amount .checked_mul(fee_multiplier) .ok_or(SwapError::Overflow)?;
/// CalculateShare outputclass using(Series constantM productpreferred)
formula

pub share_class: ShareClass,

/// outputTotal =shares (input_with_feeheld ×in output_reserve)custody

pub custodied_balance: u64,

/ 
    // (input_reserveTotal ×ST22 10000tokens +in 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,
    })
}circulation

pub circulating_tokens: u64,

/// Ed25519 signature from Empire's HSM

pub attestation_signature: [u8; 64],

/// Merkle root of current shareholder registry

pub registry_hash: [u8; 32],

/// Unix timestamp of attestation

pub attestation_timestamp: i64,

/// Block height when attestation was recorded

pub attestation_slot: u64,

}

🔹 3.2.43.2 🔄Empire LayerStock SynchronizationTransfer ProtocolIntegration

TheEmpire twoStock layersTransfer synchronizeprovides real-time custody attestations through a handoffdedicated protocolAPI ensuring atomic execution guarantees:

Step

Phase

Description

1️⃣

Verification Request

User initiates swap, generating unique

transfer_id

2️⃣

Parallel Processing

UI displays "Verifying compliance..." while hooks execute

3️⃣

Verification Complete

All hooks pass,

verification_status

 set to

VERIFIED

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:integration:

FunctionComponent

DescriptionSpecification

📊API

Price DiscoveryEndpoint

Enabling initial price discovery in a controlled environmenthttps://api.empirestocktransfer.com/v1/custody/verify

🛡️

StabilityAuthentication

PreventingAPI flashKey crashes+ andEd25519 washrequest trading during early tradingsigning

🎁Response

Early Adopter AdvantageSigning

ProvidingHSM-secured favorableEd25519 entrysignature priceson forevery earlyattestation

Update communityFrequency

Every participantsSolana slot (~400ms)

Failover

Multi-region deployment with automatic failover


🔹

3.3.13 🔍Discrepancy Initial Price Discovery MechanismDetection

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

CEDEXhook implements astrict lineardiscrepancy bondingdetection curvewith formulaconfigurable thresholds: providing predictable price appreciation as token adoption increases:

// LinearCustody BondingVerification CurveImplementation Formula(Rust/Anchor)
P(n)

pub const MAX_DISCREPANCY_BPS: u64 = initialPrice + (priceGradient × tokensIssued)1; // Parameters:0.01% //maximum 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

rustdiscrepancy

// 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)
    }
}verify_custody(

oracle_data:

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&CustodyOracleData,

transfer_amount: u64,

//
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 graduationsignature criteriaauthenticity
met

verify_ed25519_signature(

&oracle_data.attestation_signature,

&EMPIRE_PUBLIC_KEY,

&oracle_data.serialize(),

)?;

// Check attestation freshness (max 10 minutes old)
let current_time = Clock::get()?.unix_timestamp;
require!(
curve.check_graduation_criteria(

current_time - oracle_data.attestation_timestamp <= 600,

CustodyError::StaleAttestation // 6001

)?;

// Calculate discrepancy
let expected_tokens = oracle_data.custodied_balance;
let actual_tokens = oracle_data.circulating_tokens;
let discrepancy = if expected_tokens > actual_tokens {

expected_tokens - actual_tokens

} else {

actual_tokens - expected_tokens

};

let discrepancy_bps = discrepancy * 10000 / expected_tokens;
require!(

discrepancy_bps <= MAX_DISCREPANCY_BPS,

CustodyError::CustodyDiscrepancy // 6001

);

// Verify sufficient custody for this transfer
require!(

oracle_data.custodied_balance >= transfer_amount,

CustodyError::InsufficientCustody // 6001

);

Ok(())

}

📋 Regulatory Reference: 17 CFR Section 240.17a-1 et seq. — Transfer Agent Custody Requirements

✗ Error Code 6001: CUSTODY_VERIFICATION_FAILED

Indicates custody verification failure. Possible causes: stale attestation (>10 min), CedexError:discrepancy >0.01%, insufficient custodied shares, or invalid Empire signature. User should wait for fresh attestation or contact issuer.

🔗 3.4 Hook 2: OFAC Sanctions Screening

The OFAC Sanctions Screening hook prevents transactions to or from wallets associated with the Office of Foreign Assets Control's Specially Designated Nationals (SDN) list, implementing federal sanctions law requirements at the protocol level.

🔹 3.4.1 SDN List Integration

OTCM maintains an on-chain oracle updated hourly from OFAC's official SDN list, supplemented by blockchain-specific address intelligence:

// OFAC Screening Implementation

pub struct OfacOracleData {

/// Merkle root of current SDN list

pub sdn_merkle_root: [u8; 32],

/// Number of entries in SDN list

pub sdn_entry_count: u32,

/// Blockchain-specific blocked addresses

pub crypto_sdn_addresses: Vec<Pubkey>,

/// Last update timestamp

pub last_update: i64,

/// OFAC publication reference

pub publication_id: [u8; 16],

}

// Screening checks BOTH sender and recipient
pub fn screen_ofac(

sender: &Pubkey,

recipient: &Pubkey,

oracle: &OfacOracleData,

) -> Result<OfacScreeningResult> {

// Direct address matching
let sender_blocked = oracle.crypto_sdn_addresses.contains(sender);
let recipient_blocked = oracle.crypto_sdn_addresses.contains(recipient);

if sender_blocked || recipient_blocked {

return Err(OfacError::GraduationCriteriaNotMet SanctionedAddress.into()); // 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:6002

}

// CPMMAddress Swapclustering 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,000analysis (invariantsee maintained) ✅3.4.2)

check_cluster_association(sender, recipient, oracle)?;

Ok(OfacScreeningResult::Clear)

}

🔹 3.4.2 📊Address PriceClustering Impact CalculationAnalysis

PriceBeyond impactdirect measuresSDN howaddress muchmatching, aOTCM tradeimplements movessophisticated theaddress marketclustering price. Larger trades relativeanalysis to pooldetect reserveswallets createassociated largerwith pricesanctioned impacts:entities:

rust

  • Funding

    Source Analysis: Traces wallet funding sources to identify indirect SDN connections
  • Common Ownership Detection: Identifies wallets controlled by same entity through transaction pattern analysis
  • Mixer/Tumbler Detection: Flags wallets with significant exposure to known mixing services
  • High-Risk Jurisdiction Exposure: Elevated scrutiny for wallets with connections to OFAC-sanctioned jurisdictions

🔹 3.4.3 Implementation

// PriceCluster ImpactAnalysis CalculationImplementation
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()
}check_cluster_association(

📋

sender: 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:&Pubkey,

rustrecipient: &Pubkey,

oracle: &OfacOracleData,

//
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<()> {

// Query clustering oracle for both addresses
let sender_cluster = get_cluster_data(sender)?;
let recipient_cluster = get_cluster_data(recipient)?;
// Check deadlinefor require!(SDN Clock:cluster membership

if sender_cluster.sdn_association_score > 70 {

return Err(OfacError::get(ClusterAssociation {

address: *sender,

score: sender_cluster.sdn_association_score,

reason: "High SDN cluster association".to_string()?,

}.unix_timestamp <= params.deadline, SwapError::DeadlineExceeded into());

}

if recipient_cluster.sdn_association_score > 70 {

return Err(OfacError::ClusterAssociation {

address: *recipient,

score: recipient_cluster.sdn_association_score,

reason: "High SDN cluster association".to_string(),

}.into());

}

Ok(())

}

📋 Regulatory Reference: 31 CFR § 500-598 — OFAC Sanctions Administration Regulations

✗ Error Code 6002: OFAC_SANCTIONS_MATCH

Indicates wallet is blocked due to OFAC sanctions. This is a PERMANENT block—the wallet cannot transact ST22 tokens. There is no appeal process through OTCM; affected parties must resolve sanctions status with OFAC directly.

🔗 3.5 Hook 3: Blockchain Analytics Screening

The Blockchain Analytics Screening hook implements Bank Secrecy Act Anti-Money Laundering (AML) requirements through machine learning-based risk assessment, analyzing 200+ transaction features to identify money laundering patterns, sanctions evasion, theft proceeds, and coordinated suspicious activity.

🔹 3.3.1 ML Risk Assessment

OTCM integrates with institutional-grade blockchain analytics providers to execute real-time risk assessment on every transfer:

// AML Risk Assessment Data Structure

pub struct AmlRiskAssessment {

/// Overall risk score (0-100)

pub risk_score: u8,

/// Risk category breakdown

pub categories: AmlRiskCategories,

/// Specific risk flags triggered

pub triggered_flags: Vec<AmlFlag>,

/// Confidence in assessment

pub confidence: u8,

/// Model version used

pub model_version: [u8; 8],

}

pub struct AmlRiskCategories {

pub sanctions_evasion: u8, // Calculate0-100

output

pub letmoney_laundering: output = calculate_output(...)?;u8, // Verify0-100

slippage

pub tolerancetheft_proceeds: require!( output >= params.min_output, SwapError::SlippageExceeded );u8, // Execute0-100

swap

pub execute_swap(output)?;darknet_exposure: Ok(())u8, // 0-100

pub mixer_exposure: u8, // 0-100

pub gambling_exposure: u8, // 0-100

pub coordinated_activity: u8, // 0-100

}


🔹 3.4.43.2 💧Risk LiquidityScoring Depth AnalysisModel

PoolThe liquidityrisk depthscoring determinesmodel tradingclassifies efficiency.transactions CEDEXinto targetsthree minimumtiers liquiditywith levelsautomated ensuring acceptable price impacts:responses:

Pool TVLScore

MaxRisk Trade (2%)Level

MarketAutomated DepthAction

ClassificationFollow-up

💰 $100K0-30

~$2,000

🟡 Low

EarlyAuto-approve

None Stagerequired

💰 $500K31-70

~$10,000Medium

🟠Enhanced Moderatereview queue

DevelopingManual analyst review within 24h

💰 $1M71-100

~$20,000High

🟢Auto-reject Good(Error 6003)

MatureSAR filing evaluation

🔹 5.3.3 Chainalysis/TRM Integration

OTCM integrates with industry-leading blockchain analytics providers:

  • Chainalysis KYT (Know Your Transaction): Real-time transaction screening with 15-second SLA
  • TRM Labs Forensics: Deep historical analysis and entity resolution
  • Elliptic Navigator: Cross-chain exposure analysis for multi-chain actors

🔹 5.3.4 Implementation

// AML Screening Implementation

pub const LOW_RISK_THRESHOLD: u8 = 30;

pub const HIGH_RISK_THRESHOLD: u8 = 71;

pub fn screen_aml(

sender: &Pubkey,

recipient: &Pubkey,

amount: u64,

) -> Result<AmlScreeningResult> {

// Query analytics providers
let sender_risk = query_chainalysis(sender)?;
let recipient_risk = query_chainalysis(recipient)?;
// Use higher of two risk scores
let max_risk = sender_risk.risk_score.max(recipient_risk.risk_score);

match max_risk {

0..=30 => Ok(AmlScreeningResult::AutoApprove),

31..=70 => {

// Queue for enhanced review but allow transaction
emit!(EnhancedReviewQueued {

sender: *sender,

recipient: *recipient,

risk_score: max_risk,

amount,

});

Ok(AmlScreeningResult::ApproveWithReview)

},

71..=100 => {

// Auto-reject high-risk transactions

Err(AmlError::RiskThresholdExceeded {

score: max_risk,

threshold: HIGH_RISK_THRESHOLD,

}.into()) // 6003

},

_ => unreachable!(),

}

}

📋 Regulatory Reference: 31 CFR § 1010 — Bank Secrecy Act AML Requirements

✗ Error Code 6003: AML_RISK_EXCEEDED

Transaction rejected due to high AML risk score (71-100). Wallet may have exposure to: money laundering, sanctions evasion, theft proceeds, darknet markets, or coordinated suspicious activity. Appeal requires compliance review.

🔗 3.6 Hook 4: Redemption Eligibility Verification

The Redemption Eligibility Verification hook implements a critical distinction in OTCM's compliance architecture: while permissionless trading allows any wallet to purchase and transfer ST22 tokens, redemption (conversion to underlying equity shares) requires investor verification in accordance with federal securities law.

🔹 3.6.1 KYC/AML Requirements

Before a wallet can redeem ST22 tokens for underlying shares, the beneficial owner must complete comprehensive verification:

Requirement

Verification Method

Identity Verification

Government-issued photo ID + liveness check via Jumio/Onfido

💰Address $5M+Verification

~$100,000+Utility bill or bank statement within 90 days

SSN/TIN Verification

🔵IRS DeepW-9 form with SSN/TIN matching

Sanctions Screening

Institutional72-hour waiting period after initial OFAC/SDN clear

PEP Screening

Politically Exposed Person database check


🔹 3.6.2 Accredited Investor Verification

For offerings conducted under SEC Regulation D Rule 506(c), additional accreditation verification is required:

// Accreditation Status Types

pub enum AccreditationStatus {

/// Not verified - cannot redeem Reg D offerings

NotVerified,

/// Verified accredited investor

Accredited {

method: AccreditationMethod,

verification_date: i64,

expiration_date: i64, // Typically 90 days

verifier: String, // e.g., "VerifyInvestor.com"

},

/// Non-accredited but permitted (Reg A+ or Reg CF)

NonAccreditedPermitted {

regulation: OfferingRegulation,

investment_limit: u64,

},

}

pub enum AccreditationMethod {

Income, // $200K/$300K annual income

NetWorth, // $1M+ net worth excluding residence

Professional, // Series 7, 65, or 82 license

Entity, // Qualified entity (bank, trust, etc.)

KnowledgeTest, // SEC proposed "accreditation exam"

}

🔹 3.6.3 Implementation

// Redemption Eligibility Verification
pub fn verify_redemption_eligibility(

wallet: &Pubkey,

token_mint: &Pubkey,

amount: u64,

) -> Result<()> {

// Load investor record
let investor = get_investor_record(wallet)?;
// Check KYC completion
require!(

investor.kyc_status == KycStatus::Verified,

RedemptionError::KycIncomplete // 6004

);

// Check 72-hour sanctions cooling period
let current_time = Clock::get()?.unix_timestamp;
let cooling_period = 72 * 60 * 60;  // 72 hours in seconds
require!(

current_time - investor.sanctions_clear_timestamp >= cooling_period,

RedemptionError::SanctionsCoolingPeriod // 6004

);

// Load offering details
let offering = get_offering_details(token_mint)?;
// Check accreditation if Reg D 506(c)

if offering.regulation == Regulation::RegD506c {

match &investor.accreditation {

AccreditationStatus::Accredited { expiration_date, .. } => {

require!(

current_time < *expiration_date,

RedemptionError::AccreditationExpired // 6004

);

},

_ => {

return Err(RedemptionError::AccreditationRequired.into());

}

}

}

Ok(())

}

📋 Regulatory Reference: 17 CFR 230.506(c) — Regulation D Accredited Investor Requirements

✗ Error Code 6004: REDEMPTION_ELIGIBILITY_FAILED

Wallet not eligible for redemption. Possible causes: KYC incomplete, sanctions cooling period active (<72h), accreditation expired/missing for Reg D offerings. Note: Trading is still permitted; only redemption to shares is blocked.

🔗 3.57 🛑Hook 5: Price Impact Circuit Breaker

The Price Impact Circuit Breaker Architectureprevents

CEDEXsingle implements a comprehensive circuit breaker system protecting marketstransactions from manipulation,causing flashexcessive crashes,market andmovement, coordinatedimplementing attacks.regulatory Inspiredobjectives byprohibiting traditionalmanipulative securitiestrading 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.devices. Any single transaction causing greater than 2% price movement against the Time-Weighted Average Price (TWAP) oracle is automatically rejected:rejected.

🔹 3.7.1 TWAP Oracle Integration

The TWAP oracle provides manipulation-resistant reference pricing:

// TWAP Oracle Implementation

pub struct TwapOracle {

rustpub token_mint: Pubkey,

/// Rolling 1-hour TWAP

pub twap_1h: u64,

/// Rolling 24-hour TWAP

pub twap_24h: u64,

/// Number of observations in window

pub observation_count: u32,

/// Minimum observations required

pub min_observations: u32,

/// Last update slot

pub last_update_slot: u64,

}

impl TwapOracle {

pub fn get_reference_price(&self) -> Result<u64> {
// Use shorter TWAP for more responsive circuit breakers
// but require minimum observations to prevent manipulation
require!(

self.observation_count >= self.min_observations,

OracleError::InsufficientObservations

);

Ok(self.twap_1h)

}

}

🔹 3.7.2 2% Threshold Enforcement

The 2% threshold forces large market participants to execute trades gradually, preventing sudden price dislocations:

// Price Impact LimitCircuit Breaker Implementation

pub const MAX_PRICE_IMPACT_BPS: u16u64 = 200; // 2%2.00%

maximum
pub fn check_price_impact(
ctx: Context<PriceImpactCheck>, proposed_trade:

pool: &SwapParams,LiquidityPool,

trade_amount: u64,

trade_direction: TradeDirection,

) -> Result<()> {

// Get TWAP reference price
let twap = ctx.accounts.pool.twap_oracle.get_price(get_reference_price()?;
// Calculate expected post-trade price using CPMM formula
let expected_price(new_sol_reserve, new_token_reserve) = calculate_expected_price(proposed_trade)match trade_direction {

TradeDirection::Buy => (

pool.sol_reserve + trade_amount,

pool.token_reserve - calculate_output(trade_amount, pool)?,

),

TradeDirection::Sell => (

pool.sol_reserve - calculate_output(trade_amount, pool)?,

pool.token_reserve + trade_amount,

),

};

let post_trade_price = new_sol_reserve * 1_000_000_000 / new_token_reserve;
// Calculate deviation from TWAP
let deviation_bpsdeviation = if post_trade_price > twap {

(post_trade_price - twap) * 10000 / twap

} else {

(twap - expected_price).abs()post_trade_price) * 10000)10000 / twap;twap

};

require!(
deviation_bps

deviation <= MAX_PRICE_IMPACT_BPSMAX_PRICE_IMPACT_BPS,

as u64, CedexError:

CircuitBreakerError::PriceImpactExceeded {

expected_impact_bps: deviation,

max_allowed_bps: MAX_PRICE_IMPACT_BPS,

} // Error6006

6006

);

Ok(())
}

💡}

📋 Regulatory Reference: 17 CFR 240.10b-5(b) — Prohibition on Manipulative Trading Devices

✗ Error Code 6006: PRICE_IMPACT_EXCEEDED

Transaction would cause >2% price movement from TWAP. User should reduce trade size or split into multiple smaller transactions. This mechanismprotects forcesall market participants to provide liquidity gradually versus attemptingfrom sudden massiveprice liquidation.manipulation.

Large

🔗 sellers3.8 mustHook split6: ordersLiquidity acrossPool multipleSufficiency

transactions,

The allowingLiquidity Pool Sufficiency hook ensures the marketOTCM Liquidity Pool maintains adequate reserves to absorbsupport supplyall incrementally.

outstanding
ST22

3.5.2tokens. 📊The Volume-Basedhook Halts

confirms

Ifthe anypool singlemaintains walleta attemptsminimum 150% ratio of locked capital to sell greater than 30% of circulating ST22 supplyvalue withinbefore allowing redemption transactions.

🔹 3.8.1 150% Ratio Requirement

The 150% over-collateralization provides a 24-hoursafety period,buffer transactionensuring executionredemptions pausescan always be honored:

Component

Calculation

Locked Capital

Total SOL in unified LP (permanently locked)

Circulating Value

Sum of (ST22 supply × current price) for 24all hours:tokens

Sufficiency Ratio

rustLocked Capital / Circulating Value × 100%

Minimum Required

≥ 150% — redemptions pause if below

🔹 3.8.2 Implementation

// Volume-BasedLiquidity HaltSufficiency ImplementationCheck

pub const MAX_DAILY_SELL_PERCENT:MIN_SUFFICIENCY_RATIO_BPS: u8u64 = 30;15000; // 30%150%

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(check_liquidity_sufficiency(
ctx:

pool: Context<VolumeCheck>,&UnifiedLiquidityPool,

sell_amount:

redemption_amount: u64,

) -> Result<()> {

// Calculate current ratio
let trackinglocked_capital = &mut ctx.accounts.wallet_tracking;pool.total_sol_reserve;
let circulating_supplycirculating_value = ctx.accounts.mint.supply;calculate_total_circulating_value(pool)?;
// ResetAdd trackingredemption window if >24h elapsedimpact
let current_timepost_redemption_capital = Clock::get()?.unix_timestamp;
    if current_timelocked_capital - tracking.tracking_window_startredemption_amount;
>let HALT_DURATION_SECONDS {
        tracking.daily_sell_amountpost_redemption_ratio = 0;post_redemption_capital tracking.tracking_window_start* 10000 / circulating_value;
require!(

post_redemption_ratio >= current_time;MIN_SUFFICIENCY_RATIO_BPS,

LiquidityError::InsufficientLiquidity {

current_ratio: post_redemption_ratio,

required_ratio: MIN_SUFFICIENCY_RATIO_BPS,

} // Check6007

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

📋 🕵Regulatory Reference: Securities Exchange Act Rule 15c2-11 — Capital Adequacy Requirements

✗ Error Code 6007: LIQUIDITY_INSUFFICIENT

Pool ratio below 150% threshold. Redemptions temporarily paused until trading volume rebuilds reserves. Regular ST22 trading (non-redemption) remains permitted. Users can wait for ratio recovery or reduce redemption amount.

🛡Coordinated3.9 ActivityThirty-Six Detection

Supplementary Security Controls

CEDEXBeyond the six primary Transfer Hooks, OTCM implements machinethirty-six learning-basedsupplementary detectionsecurity ofcontrols coordinatedintegrated sellinginto patternsthe suggestingtransfer manipulativehook intent.logic, Thecreating algorithma analyzescomprehensive four42-point correlationsecurity dimensions:framework.

🔹 3.9.1 Smart Contract Controls (1-6)

Dimension#

Analysis MethodControl

🚨 Suspicious ThresholdDescription

👥

Wallet Clustering1

GraphFormal analysis of funding sourcesVerification

>5Certora walletsProver sharingmathematical fundingproof sourceof contract correctness

⏱️

Timing Correlation2

TransactionMulti-Audit timestamp clusteringRequirement

>3Independent sellsaudits withinby 10-secondQuantstamp, windowHalborn, and OtterSec

💰

Amount Correlation3

StatisticalImmutable analysis of sale sizesBytecode

<5%No varianceproxy acrosspattern—code multiplecannot salesbe changed post-deployment

📉

Price Impact Correlation4

SequentialBug impactBounty accumulationProgram

CumulativeUp >5%to within$500K 1rewards hourfor critical vulnerabilities

5

Reentrancy Guards

Check-Effects-Interactions pattern enforcement

6

Integer Overflow Protection

Rust's checked arithmetic prevents overflow attacks

When

🔹 coordinated3.9.2 activityAccess isControl detected, affected wallets enter 24-hour cooldown periods, and the compliance team receives alerts for manual review.


3.5.4 📊 Time-Weighted Average PriceFramework (TWAP) Oracle7-12)

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#

RateControl

PurposeDescription

🏢

Issuer Allocation7

2.00%Multi-Sig Administration

Revenue4-of-7 sharethreshold tofor issuingadministrative company treasuryactions

🥩

Staking Rewards8

1.50%Timelock Delays

Distributed48-hour todelay OTCMon tokenall stakersparameter (8-60% APY)changes

⚙️

Protocol Operations9

1.06%Role-Based Access

Infrastructure,Granular compliancepermission oracles,system development(operator, compliance, admin)

💧

Liquidity Pool Growth10

0.44%Emergency Pause

Permanently2-of-7 lockedemergency inpause OTCMwith LP24hr for depthauto-unpause

📊 TOTAL11

5.00%DAO Override

Complete2/3 feesupermajority structurerequired for lock override

12

Key Rotation

Quarterly key rotation with HSM backing


🔹 3.9.3 Transaction Integrity Controls (13-18)

  1. Atomic Execution: All-or-nothing transaction commitment
  2. Orphan Prevention: No partial execution states possible
  3. Replay Protection: Unique transaction signatures prevent replay
  4. Deadline Enforcement: Transactions expire after specified block height
  5. Slippage Protection: User-configurable maximum price deviation

🔹 3.7.29.4 🔄Oracle Fee& DistributionData MechanismControls (19-24)

rust

  1. Multi-Oracle

    //Consensus: FeeCross-reference Distributionmultiple Implementationdata pubsources
  2. Staleness fnDetection: distribute_fees(Reject fee_amount:data u64,older issuer_treasury:than &Pubkey, staking_pool: &Pubkey, protocol_treasury: &Pubkey, liquidity_pool: &Pubkey, ) -> Result<()> { // Fee distribution ratiosthreshold (basis10 pointsmin)
  3. Signature Verification: Ed25519 verification of 5%all fee)oracle constdata
  4. Rate ISSUER_SHARE:Limiting: u64Maximum =oracle 4000;queries //per 40%block per mint
  5. Fallback Oracles: Automatic failover to backup data sources
  6. Data Freshness Proofs: On-chain attestation of 5%data =recency
2.00%

🔹 const3.9.5 STAKING_SHARE:Monitoring u64& =Alerting 3000;(25-30)

//
  1. Real-Time 30%Monitoring: 24/7 transaction pattern analysis
  2. Anomaly Detection: ML-based unusual activity identification
  3. SEC Notification: Automatic reporting of 5%compliance =failures
  4. Compliance 1.50%Dashboard: constReal-time PROTOCOL_SHARE:visibility u64for =regulators
  5. Audit 2120;Log //Export: 21.2%On-demand ofhistorical 5%data =retrieval
  6. Alert 1.06%Escalation: constTiered LP_SHARE:notification u64for =severity 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(()) }
    levels

🔹 3.7.39.6 📊Governance Fee& ComparisonRecovery Analysis(31-36)

  1. Proposal System: On-chain governance for parameter changes
  2. Voting Mechanism: Token-weighted voting with delegation
  3. Quorum Requirements: Minimum participation thresholds
  4. Veto Power: Compliance officer veto on security-relevant proposals
  5. Migration Capability: Controlled upgrade path for critical fixes
  6. Disaster Recovery: Documented procedures for catastrophic scenarios

❌ 3.10 Error Handling and Recovery

PlatformCode

💸 Swap FeeHook

⚖️ ComplianceCondition

📈User LP Rewards

🏢 Issuer RevAction

🟢

CEDEX6001

5.00%Custody

Discrepancy Full>0.01%

8-60%Wait, APY

2.00%retry, contact issuer

🔵 Raydium6002

0.25%OFAC

Sanctioned Noneaddress

Variable

0%PERMANENT — contact OFAC

🔵 Orca6003

0.30%AML

Risk Nonescore 71-100

Variable

0%Request compliance review

🟡 Pump.fun6004

1.00%Redemption

KYC/accreditation Noneissue

NoneComplete verification

6006

0%Price Impact

>2% TWAP deviation

Reduce size, split trade

6007

Liquidity

<150% pool ratio

Wait for ratio recovery

💡 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 📊11 Performance Specifications

Metric

SpecificationValue

Notes

Total

ThroughputHook (TPS)Latency

400-600750-1,350ms

LimitedSequential by compliance verificationexecution

⚖️

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 transactiontransfer

💵Effective

Network FeeTPS

~$0.01-0.05400-600

SolanaCompliance baseoverhead

Oracle +Cost/Transfer

$2-5

Chainalysis, priorityEmpire feeAPIs


🛡️

3.10 🔐12 Security ArchitectureAudit Status

CEDEX

  • Quantstamp: securityAudit combinesscheduled smartQ1 contract2026
  • Halborn: hardening,Engagement economicin attackprogress
  • OtterSec: resistance,Preliminary andreview operationalcomplete
  • Certora security measures:


    📜 Smart Contract Security

    Measure

    Description

    Formal Verification

    UsingVerification: CertoraSpecification Prover

    🔍development

    Security Audits

    By Quantstamp, Halborn, and OtterSec

    🐛

    underway

  • Bug Bounty

  • ActiveBounty: $500K program (uplaunching towith $100Kmainnet 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