Section 3: SPL Token-2022 Transfer Hooks โ Layer 2
๐ The security primitive at the heart ofOTCMProtocolPROTOCOLComprehensive Technical Whitepaper โ
42mathematicallyVersionenforced7.0controls that execute atomically on everyST22 Digital Securities
transferPlatformviaSPL|Token-2022TransferMarchHook2026extensions.| Groovy Company, Inc. dba OTCM Protocol
๐ก3.1Architectural Innovation
Section 3: SPL Token-2022 Transfer Hooks
representโaLayerfundamental2architecturalThe
innovationcompleteintechnicalblockchain-basedspecificationsecuritiesforinfrastructure,OTCMenablingProtocol'sexecution42-controlofTransferarbitraryHooksmartsecuritycontractarchitecturecode during token transfers onโ theSolana blockchain. This capability transformsfoundational compliancefromenforcementamechanismdiscretionarythatadministrativemakesfunctionregulatoryintobypassanstructurally impossible.immutable, mathematically-enforced property of the token itself.
OTCMMetricProtocolleveragesValue
Document reference
OTCM-TH-SPEC-001 v2.0 (aligned with Whitepaper V7.0)
Total security controls
42
Transfer
Hookscoveragetoimplementfederal securities law requirements as non-discretionary smart contract code100% โ
creating a paradigm where regulatory compliance is not a matter of corporate policy but ofcryptographic certainty. Everyevery ST22Digital Securitiestransfertriggersinvokessequentialallexecution42ofcontrolssixindependentverificationhooks, completing comprehensive compliance verification before transaction settlement.
UnderBypassthepossibilitySEC'sMarch17,Zero
2026โinterpretationenforced at SPL Token-2022 program levelTarget validation latency
< 1,000ms (
ReleaseparallelNo.execution)33-11412),ST22tokensareformallyCompute
classifiedunitasbudget< 5,000 CU per validation
Implementation language
Rust / Anchor framework
Immutability
Transfer Hook cannot be removed or disabled after mint creation
V7 change vs V6
Control 24 updated: vesting schedule removed; Rule 144 / Reg S holding period enforcement added
3.1
DigitalTheSecurities.Alesia Doctrine โ Compliance by EncirclementThe Transfer Hook architecture
isembodiespreciselywhat OTCM Protocol calls themechanismAlesia Doctrine: the principle thatmakescompliancethisshouldclassificationbesustainableenforced through structural encirclement rather than trust. In traditional securities markets, compliance depends on intermediaries โitbroker-dealers,automatesclearinghouses, and regulators โ acting in good faith. These actors can fail, be compromised, or simply be absent in the OTC microcap context where infrastructure has been abandoned.OTCM Protocol's Transfer Hook architecture eliminates the dependency on good-faith intermediary behavior by embedding compliance enforcement
obligations that come with that classification atin the token transfer primitive itself. Every ST22 token transfer โ regardless of which wallet, front-end, or trading venue initiates it โ must pass through all 42 controls before the transaction executes on-chain. There is no path around this enforcement. There is no administrative override. There is no whitelist for trusted parties. The controls execute identically for every participant on every transfer, including OTCM Protocol itself.
๐น3.1.1SPLToken-2022WhyStandardApplication-LayerOverviewCompliance Fails
SPLTheToken-2022January(Token28,Extensions2026Program)Joint Staff Statement on Tokenized Securities explicitly identified the compliance gap that results when securities compliance isSolana'simplementednext-generationat the application layer rather than the tokenstandard,standardintroducinglevel.programmableWhenextensionscompliance is enforced by an issuer's portal or a specific trading venue, any participant who routes around thatenableportalsophisticatedortokenvenuefunctionalitybypassesimpossibleallwithcompliance controls. This is theoriginalarchitecturalSPLvulnerabilityTokenthatProgram:defines Category 2 (Third-Party Sponsored) tokenization โ and it is precisely what the Transfer Hook architecture eliminates.
ExtensionCompliance Location
CapabilityVulnerabilityOTCM
UsageProtocol ApproachApplication layer (portal)
Any alternative front-end bypasses all controls
Layer 2 enforcement โ no front-end can bypass
Trading venue (exchange)
Any DEX that doesn't enforce compliance disables all controls
CEDEX exclusive โ only venue that preserves all 42 hooks
Issuer policy
Policy can be changed, ignored, or overridden
Immutable smart contract โ policy is code, code is law
Third-party custodian
Custodian can withdraw backing assets, creating de-peg risk
Transfer Hook
ExecutecustomControllogic1 verifies custody on every transfer
42 security controls ยท compliance verification
Permanent Delegate
Irrevocable transfer authority
Protocol-level recovery 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
๐น 3.1.2Transfer HookExtension(LayerMechanism2)Cannot be bypassed โ any failure reverts entire transaction
This is the OTCM approach โ compliance at the primitive
3.2 Architecture
3.2.1 Transaction Flow
The Transfer Hook
extensionisenablesinvoked by the SPL Token-2022 program on every ST22 tokenmintstransfertoviaspecifyCross-ProgramaInvocationprogram that must be invoked during every token transfer.(CPI). Thismechanisminvocationoperatesis mandatory at theSolana runtimeprotocol level,makingโ itimpossiblecannottobe disabled by the issuer, by OTCM Protocol, or by any trading venue. The six-step flow is as follows:
โข Step 1 โ Transfer initiation โ User initiates transfer
tokensthroughwithoutanyexecutingentry point: CEDEX order execution, hardware wallet, mobile wallet, or programmatic callโข Step 2 โ Token-2022 receives instruction โ SPL Token-2022 program receives the
hooktransferprogram:instruction from the initiating partypubโข
structStepTransferHook { pub program_id: Pubkey, pub authority: Option<Pubkey>, }
๐น 3.1.3Compliance-as-Code Philosophy
OTCM'sโ Transfer Hookimplementationinvokedembodiesviathe"Compliance-as-Code"philosophy: regulatory requirements are translated into deterministic smart contract logic that executes identically every time, without human discretion, administrative override, or interpretation variability.
"Traditional compliance asks: 'Did you follow the rules?' OTCM's Transfer Hooks ask: 'Can you mathematically prove compliance?' The answer is always verifiable on-chain."
Aspect
Traditional Compliance
Transfer Hook Compliance
Enforcement
Policy-based ยท discretionary
Code-based ยท deterministic
Override Capability
Admin can bypass
No bypass possible
Audit Trail
Mutable logs ยท editable
Immutable blockchain record
Verification
Requires trust in operator
Cryptographically verifiable
Consistency
Varies by analyst / day
100% identical execution
Timing
Post-trade review (T+n)
Pre-trade blocking (T-0)
๐น 3.1.4 Regulatory Advantages
Transfer Hook execution provides regulatory advantages unattainable through traditional compliance procedures:
Immutable Audit TrailsCPI โEvery compliance check recorded on-chain with cryptographic proof of execution timestamp, inputs, and outcomesZero DiscretionToken-2022โautomaticallyCompliance decisions are algorithmic โ no analyst judgment, no selective enforcement, no regulatory arbitrageReal-Time Enforcementโ Non-compliant transfers blocked before execution, not flagged for review after the factCryptographic Proofโ Regulators can independently verify any historical compliance decision by replaying on-chain dataContinuous Operationโ 24/7/365 enforcement with no business hours, holidays, or staffing gaps
๐กSEC Alignment:invokes OTCM's Transfer HookarchitectureprogramdirectlyviaimplementsCross-ProgramtheInvocation.investorThisprotectionstepprinciplesisarticulated in the SEC's March 17, 2026 interpretation (Release No. 33-11412)mandatory andthecannotCryptobeTask Force's framework for blockchain-native compliance mechanisms.skippedโข
Step
๐3.24 โ All 42 controls execute โ The Transfer HookExecutionvalidatesFlowthe
transactioncontrols
๐นagainst3.2.1allHook42InvocationsecuritySequenceUserinInitiatesparallelST22andTransfersequentialโ Solana Runtime intercepts transfer โ Hook 1: Custody Verificationgroups. Oracle(100โ150ms)dataโfromPASSLayerHook62:isOFACconsumedSanctionsinScreeningreal-time(200โ500ms)โข
โStepPASS5Hookโ3:AtomicBlockchainresultAnalyticsโ/ AML (300โ400ms) โ PASS Hook 4: Redemption Eligibility (50โ100ms) โ PASS Hook 5: Price Impact Circuit Breaker (50โ100ms) โ PASS Hook 6: Liquidity Pool Sufficiency (50โ100ms) โ ALL PASS Transaction Executes & Settles on Solana โIf ANYFAILcontrolEntire Transaction Reverts Atomically
๐น 3.2.2 Sequential vs. Parallel Execution
OTCM implementssequentialhook execution for critical security reasons:
Mode
Advantage
Trade-off
Sequential (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 2โ6 never execute โ saving oracle costs and compute resources. Users always know which specific hook rejected their transaction.
๐น 3.2.3 Atomic Transaction Guarantees
Solana's account model provides atomic transaction guarantees: ifanyhook fails,fails: the entire transaction revertsasatomicallyifwithitaneverspecificoccurred.errorTherecode. If ALL controls pass: execution proceeds to Layer 1 settlementโข Step 6 โ Settlement and audit โ Passing transactions settle on Solana. An immutable audit record of all control results is
nowrittenintermediateon-chain for every transfer
3.2.2 Program Structure
The Transfer Hook program is implemented in Rust using the Anchor framework. The program structure follows strict separation of concerns, with each component having a well-defined responsibility:
programs/
โโโ transfer-hook/
โโโ src/
โโโ lib.rs // Program entrypoint
โโโ instructions/
โ โโโ mod.rs
โ โโโ initialize.rs // SecurityConfig initialization
โ โโโ transfer_hook.rs // Main hook logic (42 controls)
โโโ state/
โ โโโ mod.rs
โ โโโ security_config.rs // Security parameters per mint
โ โโโ circuit_breaker.rs // Circuit breaker state
โ โโโ holding_period.rs // Rule 144 / Reg S enforcement (V7)
โโโ errors.rs // Custom error codes (6001โ6042)
โโโ utils/
โโโ validation.rs // Validation helpers
โโโ math.rs // u128 overflow-safe arithmetic
3.2.3 Account Architecture
The Transfer Hook utilizes Program Derived Addresses (PDAs) to store security configuration and state for each token mint. One SecurityConfig account is created per ST22 Security Token at the time of minting, establishing the security parameters that govern all transfers of that token for its entire existence.
#[account]
pub struct SecurityConfig {
pub mint: Pubkey, // Associated token mint
pub authority: Pubkey, // 5-of-9 multi-sig admin
pub max_wallet_percent: u16, // 499 = 4.99% (basis points)
pub circuit_breaker_threshold: u16, // 3000 = 30% daily volume
pub circuit_breaker_cooldown: i64, // 86400 = 24 hours
pub circuit_breaker_triggered: bool, // Current CB state
pub circuit_breaker_triggered_at: i64, // CB trigger timestamp
pub reference_price: u64, // TWAP baseline
pub holding_period_config: HoldingPeriodConfig, // V7: Rule 144/Reg S
pub volume_tracker: VolumeTracker, // 24h rolling window
pub blacklisted_wallets: Vec<Pubkey>, // OFAC-blocked addresses
pub is_paused: bool, // Emergency pause
pub bump: u8, // PDA bump seed
}
3.2.4 V7 Architecture Change: HoldingPeriodConfig
In Version 7.0, the VestingConfig account structure used in V6 has been replaced by HoldingPeriodConfig. This reflects the change from the 5-tranche issuer vesting model (where 60% of tokens
haveweretransferredwithheldbutfrom issuers over 30 months) to the Reg D / Reg S issuance model (where 100% of tokens are distributed to accredited investors, who hold for the Rule 144 or Reg S complianceverificationperiodisbeforeincomplete.trading).
๐น 3.2.4 Execution Timing
Hook// V7 REPLACEMENT FOR VestingConfig
Min#[account]pub struct HoldingPeriodAccount {
pub version: u8, // Schema version โ always 7
pub beneficiary: Pubkey, // Investor wallet address
pub mint: Pubkey, // ST22 mint address
pub purchase_timestamp: i64, // Unix timestamp at token delivery
pub jurisdiction: Jurisdiction, // US or NonUS
pub holding_period_secs: i64, // 15_778_800 (
ms)
MaxUS) | 31_536_000 (ms)non-US)
Avg(ms)pub is_locked: bool, // True until holding period elapses
PrimaryBottleneckpub bump: u8, // PDA bump seed}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, PartialEq)]
pub enum Jurisdiction {
US, // Rule 144 โ 6-month holding period
NonUS, // Regulation S โ 12-month distribution compliance period
}
// Constants
pub const RULE_144_HOLDING_SECS: i64 = 15_778_800; // 6 months
pub const REG_S_COMPLIANCE_SECS: i64 = 31_536_000; // 12 months
1.CustodyOracle
100
150
125
Empire API latency
2. OFAC Screening
200
500
350
SDN list size ยท clustering
3. AML Analytics
300
400
350
ML inference time
4. Redemption Eligibility
50
100
75
KYC database lookup
5. Price Impact
50
100
75
TWAP calculation
6. LP Sufficiency
50
100
75
Pool state read
TOTAL
750
1,350
1,050
Sequential sum
๐3.3Hook1:TheCustody42VerificationSecurityOracleControlsThe 42 controls are organized into six categories. Every control executes on every transfer โ there are no exceptions, no bypass mechanisms, and no administrative overrides. The categories are not sequential phases; most controls execute in parallel. The sequential dependency exists only within the critical path (Controls 1โ2โ3โ4โ24).
Category 1: Custody & Asset Backing Verification
Oracleconfirmsยท 9 controls (1โ7, 38, 40) controlsVerify at every transfer that
allcirculatingST22tokenDigitalsupplySecuritiesnevertokensexceedsareSeriesbackedMby equivalent equitypreferred shares heldatin EmpireStockcustodyTransfer
#
Control Name
Trigger Condition
Enforcement Action
Error
1
Custody Oracle Check
Circulating supply would exceed Empire-custodied share count
Reject โ
theErrorSEC-registered6001 (CustodyDiscrepancy)6001
2
Oracle Availability
Empire custody feed unavailable or attestation > 400ms stale
Reject โ Error 6002 (CustodyOracleUnavailable)
6002
3
Supply Integrity
Total supply inconsistency detected across mint accounts
Reject โ atomic revert
6007
4
Locked Balance
Transfer would draw from locked (holding-period) balance
Reject โ Error 6024 per Control 24
6024
5
Zero Balance Guard
Transfer from zero-balance account or dust amount
Reject โ zero transfer
agentguardprovidingqualifiedcustody6014
services6
Precision Validation
Decimal precision exceeds mint-defined limit
Reject โ precision error
6016
7
Supply Integrity Cross-Check
Secondary oracle cross-reference disagrees with primary
Circuit breaker โ halt transfers for
OTCMaffectedProtocol.mint
๐น3.3.16038
38
Custody Discrepancy Halt
Token supply confirmed > custodied shares (oracle verified)
Halt all transfers for affected mint indefinitely
6038
40
Oracle
ArchitectureConsensuspubFailurestructCustodyOracleData{<
pub2issuer_cik:of[u8;310],oraclepubfeedscusip:available[u8;for9],>pub5share_class:minutesShareClass,pubcustodied_balance:Halt
u64,affectedpubhookcirculating_tokens:categoryu64,pubattestation_signature:6040
[u8;64],//Ed25519
Category 2: Sanctions & AML Compliance ยท 4 controls (8โ11) controls
OFAC/SDN real-time screening and AML risk scoring on every transfer โ
HSM-securednotpubjustregistry_hash:at[u8;onboarding32],pubattestation_timestamp:i64,pub
attestation_slot:u64,Controls
}8โ11
implementperforms
๐นcontinuous3.3.2sanctions and AML compliance. Empire Stock TransferIntegration
Component
Specification
APItheseEndpoint
https://api.empirestocktransfer.com/v1/custody/verify
Authentication
APIchecksKeyat+investorEd25519onboardingrequestโsigning
ResponseControlsSigning
HSM-secured8โ11Ed25519ensuresignaturethey are re-applied on everyattestationsubsequent transfer. A wallet that was clean at onboarding but later added to the OFAC SDN list is blocked immediately on its next transfer attempt.
Update Frequency#
EveryControlSolanaNameslotTrigger Condition
Enforcement Action
Error
8
OFAC Sender Screen
Sender wallet matches OFAC SDN list (
~400ms)updated hourly)
Failover
Multi-regionRejectdeployment with automatic failover(SenderSanctioned)
๐ Proof-of-Reservepermanently โSupplyErrorReconciliation6003Specification
Version:60036.1|AppliesTo:Layer9
6OFAC Receiver Screen
Receiver wallet matches OFAC SDN list
Reject permanently โ Error 6004 (ReceiverSanctioned)
6004
10
OFAC Oracle
NetworkStalenessOFAC SDN feed not updated within 90 minutes
Reject โ
Hookstale1oracle,CustodyErrorVerification6005
TheReconciliation Invariant
At600511
AML Risk Score
ML risk score for sender or receiver exceeds 70/100 threshold
Reject โ Error 6006 (SenderHighRisk). Score 31โ70: flag for compliance review
6006
// Control 11: AML Risk Scoring โ three-tier system
pub fn check_aml_risk(risk_score: u8) -> Result<AMLDecision> {
match risk_score {
0..=30 => Ok(AMLDecision::Approve),
31..=70 => Ok(AMLDecision::EnhancedReview), // flag, don't reject
71..=100 => Err(TransferHookError::SenderHighRisk.into()),
_ => Err(TransferHookError::InvalidRiskScore.into()),
}
}
Category 3: Investor Eligibility & Holding Period Enforcement ยท 8 controls (12โ19) controls
Accreditation verification, KYB entity checks, and Rule 144 / Reg S holding period enforcement on every
Solana slot, the following invariantMUSThold for every active ST22 mint:transfercirculating_supplyโคcustodied_shares
AnyCategorycondition where on-chain supplyexceedscustodied shares is an immediate critical alert (Error 6001 โ all transfers halted). The system is designed so that equality (1:1 backing)3 is thesteadymoststatesignificant change in the V7 Transfer Hook specification. In V6, this category was called 'Vesting Enforcement' and enforced the 5-tranche issuer vesting schedule over 30 months. In V7, the vesting schedule has been removed. Control 24 (formerly the vesting enforcement control) now enforces the Rule 144 and Regulation S mandatory holding periods for accredited investors. The control number is retained for error code continuity; the underlying logic is completely rewritten.
#
Control Name
Trigger Condition
Enforcement Action
Error
12
Accreditation Check
Buyer wallet not in Empire's verified accredited investor registry
Reject โ
aaccreditationcustodyrequired.deficitError 60046004
13
KYC Status Check
Buyer or seller KYC status expired or flagged in Empire system
Reject โ re-verification required
6004
14
KYB Entity Check
Entity investor UBO verification lapsed or flagged
Reject โ KYB re-verification required
6004
15
Wallet Registration
Destination wallet not registered in Empire Master Securityholder File
Reject โ unregistered wallet cannot receive ST22 tokens
6004
16
Redemption Eligibility
Redemption transaction: KYC completion and accreditation not current
Reject โ Error 6004 (KYCInvalid)
6004
17
Jurisdiction Flag
Wallet jurisdiction flag missing or invalid
Reject โ jurisdiction cannot be determined
6024
18
Reg S US Person Check
Non-US wallet attempting US market transaction during compliance period
Reject โ Reg S restriction
6024
24
Holding Period Lock
Purchase timestamp + holding_period_secs > current_timestamp
Reject โ Error 6024 (TokensLocked). US: 6-month Rule 144. Non-US: 12-month Reg S
6024
3.3.1 Control 24 Deep Dive โ Rule 144 / Reg S On-Chain Enforcement
Control 24 is
impossibletheundermechanismnormalthatoperationsmakesbecauseOTCMsharesProtocol'smustissuancebemodeldepositedlegallybeforecomplianttokenswithoutarerelyingminted.on investor self-discipline or post-hoc regulatory action. It is the on-chain expression of the mandatory holding periods that securities law imposes on restricted security holders.
Reconciliation
Algorithmโ
Hook1Execution// Control 24: Holding Period Enforcement
pub fn
verify_custody(check_holding_period(ctx: Context<
CustodyVerificationTransferHook>,transfer_amount: u64,
) -> Result<()> {
let holding = &ctx.accounts.holding_period_account;
let current_ts = Clock::get()?.unix_timestamp;
// Check if holding period has elapsed
let required_period = match holding.jurisdiction {
Jurisdiction::US => RULE_144_HOLDING_SECS, // 15_778_800s (6 months)
Jurisdiction::NonUS => REG_S_COMPLIANCE_SECS, // 31_536_000s (12 months)
};
let elapsed = current_ts - holding.purchase_timestamp;
require!(
elapsed >= required_period,
TransferHookError::TokensLocked //
1.ErrorVerify6024oracle
signature authenticity verify_ed25519_signature( &oracle_data.attestation_signature, &EMPIRE_PUBLIC_KEY, &oracle_data.serialize(), )?; // 2. Reject stale attestations (>10 minutes) require!( current_time - oracle_data.attestation_timestamp <= 600, CustodyError::StaleAttestation // 6001);//
3.Check
discrepancy within 0.01% tolerance require!( discrepancy_bps <= MAX_DISCREPANCY_BPS, CustodyError::CustodyDiscrepancy // 6001 ); // 4. Confirm sufficient custodied shares for transfer require!( oracle_data.custodied_balance >= transfer_amount, CustodyError::InsufficientCustody // 6001 );Ok(())}
pubconstMAX_DISCREPANCY_BPS:u64=
1;//Key
0.01%propertiesmaximumofdiscrepancyControl
Quarterly24PublicinProof-of-ReserveV7:Audit
Component
Frequency
PublishedโขAt
VerifiablePurchaseBy
Empiretimestampledgerisstateimmutablehash
Quarterly
otcm.io/proof-of-reserve
AnyoneโwithSet by EmpireledgerStockexport
On-chainTransfersupplyatsnapshot
Continuous
Solanatokenblockdeliveryexplorer
Anyone
Signedandcustodyrecordedattestationon-chain.archive
Quarterly
IPFSCannot+beArweave
AnyonealteredwithbyEmpireanypublic key
Third-partyattestationafter(auditor)it is set.
Annual
SEC EDGAR (8-K)
Anyone
๐โขRegulatoryJurisdictionReference:determines17holdingCFR Section 240.17a-1 et seq.period โTransferUSAgentinvestorsCustody(RegRequirementsD 506(c)) hold 6 months under Rule 144. Non-US investors (Reg S) hold 12 months under the Regulation S distribution compliance period. Determined by Empire's KYC/KYB determination at onboarding.
โโขErrorNoCodegrace6001: CUSTODY_VERIFICATION_FAILEDperiod โIndicates custody verification failure. Possible causes: stale attestation (>10 min), 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 ScreeningThe
OFACcheckSanctionsisScreening hook prevents transactionsexact toor from wallets associated withtheOfficesecond.ofAForeigntransferAssets Control'sSpecially Designated Nationals (SDN)list, implementing federal sanctions law requirementsattempt atthe6protocolmonthslevel.minus 1 second is rejected identically to a transfer attempt at day 1.
๐น 3.4.1 SDN List Integrationpub struct OfacOracleData { pub sdn_merkle_root: [u8; 32], pub sdn_entry_count: u32, pub crypto_sdn_addresses: Vec<Pubkey>, pub last_update: i64, pub publication_id: [u8; 16], }
๐น 3.4.2 Address Clustering Analysis
Beyond direct SDN address matching, OTCM implements sophisticatedโขaddressNoclusteringadministrativeanalysisto detect wallets associated with sanctioned entities:
Funding Source Analysisoverride โTraces wallet funding sources to identify indirect SDN connectionsCommon Ownership DetectionNoโwallet,Identifiesnowalletskey,controlledno multisig, and no DAO vote can override Control 24. The holding period is enforced by thesameimmutableentityTransferthroughHooktransactionprogram.patternโข
analysisMixer/TumblerAutomaticDetectionclearance โFlagsOncewalletsthe holding period elapses, Control 24 clears on the next transfer attempt withsignificantnoexposureaction required from any party.โข Volume limits still apply after clearance โ After Control 24 clears, the remaining 41 controls still apply. Investors can trade but are subject to
knownthemixing4.99%serviceswallet concentration limit, 1% daily sell limit, price impact circuit breaker, and all other protections.
High-RiskCategoryJurisdiction4:ExposureMarket Integrity & Position Limits ยท 9 controls (20โ28) controlsWallet concentration limits, circuit breakers, volume halts, and price impact controls
#
Control Name
Trigger Condition
Enforcement Action
Error
20
Max Wallet Limit
Post-transfer balance would exceed 4.99% of total supply for destination
Reject โ
Elevatedwhalescrutinyconcentration limit. Error: WalletLimitExceeded6020
21
Pre-Transfer Balance
Source wallet has insufficient transferable balance (excluding locked)
Reject โ insufficient balance
6008
22
Zero-Amount Guard
Transfer amount = 0
Reject โ zero transfer
6014
23
Self-Transfer Guard
Source wallet = destination wallet
Reject โ self transfer
6015
25
Price Impact Limit
Transaction would cause > 2% price deviation from TWAP
Reject โ Error 6006 circuit breaker trigger
6006
26
TWAP Oracle Integrity
TWAP feed stale or deviation > 10% from secondary price feed
Reject โ stale oracle, cannot enforce price impact
6019
27
Volume Halt
Single wallet attempts to sell > 30% of circulating supply in 24 hours
24-hour trading suspension for
walletsthatwithwalletconnectionstoOFAC-sanctioned6037
jurisdictions28
๐น3.Circuit Breaker
> 30% price movement in single Solana slot for affected ST22
Halt mint-specific transfers for 1 hour
6037
36
Global Circuit Breaker
Protocol-wide pause activated by 3-of-4 multisig
Reject all ST22 transfers platform-wide
6036
// Control 20: Max Wallet Limit (4.
399%)Screening Implementationpub fn
check_ofac_compliance(check_wallet_limit(sender:destination_balance: u64,
transfer_amount: u64,
total_supply: u64,
config: &
Pubkey,SecurityConfig,recipient: &Pubkey, oracle: &OfacOracleData,) -> Result<()> {
let new_balance = destination_balance
.checked_add(transfer_amount)
.ok_or(TransferHookError::ArithmeticOverflow)?;
let max_allowed = (total_supply as u128)
.checked_mul(config.max_wallet_percent as u128) //
Direct499SDNbpsaddress
match.ok_or(TransferHookError::ArithmeticOverflow)?if
sender_blocked.checked_div(10_000)||
recipient_blocked.ok_or(TransferHookError::ArithmeticOverflow)?{asreturnu64;Err(OfacError:
require!(new_balance <= max_allowed, TransferHookError::
SanctionedAddress.into())WalletLimitExceeded);//
6002 } // Cluster association scoring (threshold: 70) if sender_cluster.sdn_association_score > 70 { return Err(OfacError::ClusterAssociation { address: *sender, score: sender_cluster.sdn_association_score, reason: "High SDN cluster association".to_string(), }.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โ Wallet blocked due to OFAC sanctions. This is aPERMANENT 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 / AML Screening
The}BlockchainAnalyticsScreeninghookimplements
BankSecrecy
ActAMLrequirementsthroughCategory 5: CEI Pattern & Reentrancy Prevention
machineยทlearning-basedrisk9assessment, analyzing 200+ transaction features to identify money laundering patterns, sanctions evasion, theft proceeds, and coordinated suspicious activity.
๐น 3.5.1 ML Risk Assessment Data Modelpub struct AmlRiskAssessment { pub risk_score: u8, pub categories: AmlRiskCategories, pub triggered_flags: Vec<AmlFlag>, pub confidence: u8, pub model_version: [u8; 8], } pub struct AmlRiskCategories { pub sanctions_evasion: u8, // 0โ100 pub money_laundering: u8, // 0โ100 pub theft_proceeds: u8, // 0โ100 pub darknet_exposure: u8, // 0โ100 pub mixer_exposure: u8, // 0โ100 pub gambling_exposure: u8, // 0โ100 pub coordinated_activity: u8, // 0โ100 }
๐น 3.5.2 Risk Scoring Tiers
Score
Risk Level
Automated Action
Follow-up
0โ30
Low
Auto-approve
None required
31โ70
Medium
Enhanced review queue
Manual analyst review within 24h
71โ100
High
Auto-rejectcontrols (Error29โ35,6003)
SAR41,filing42)evaluation
๐น 3.5.3 Analytics Provider Integration
Chainalysis KYT (Know Your Transaction)โ Real-time transaction screening with 15-second SLATRM Labs Forensicsโ Deep historical analysis and entity resolutionElliptic Navigatorโ Cross-chain exposure analysis for multi-chain actors
๐น 3.5.4 Implementationpub 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> { match max_risk { 0..=30 => Ok(AmlScreeningResult::AutoApprove), 31..=70 => { queue_enhanced_review(sender, recipient, amount); Ok(AmlScreeningResult::ProceedWithFlag) }, 71..=100 => Err(AmlError::RiskThresholdExceeded { score: max_risk, threshold: HIGH_RISK_THRESHOLD, }.into()), // 6003 _ => unreachable!(), } }
๐Regulatory Reference:31 CFR ยง 1010 โ Bank Secrecy Act AML Requirementscontrols
โ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 hook implements a critical distinction in OTCM's compliance architecture: while permissionless trading allows any verified wallet to purchase and transfer ST22 tokens,redemption(conversion to underlying equity shares) requires full investor verification in accordance with federal securities law.
๐น 3.6.1 KYC/AML Requirements for Redemption
Requirement
Verification Method
Identity Verification
Government-issued photo ID + liveness check via Jumio/Onfido
Address Verification
Utility bill or bank statement within 90 days
SSN/TIN Verification
IRS W-9 form with SSN/TIN matching
Sanctions Screening
72-hour waiting period after initial OFAC/SDN clear
PEP Screening
Politically Exposed Person database check
๐น 3.6.2 Accredited Investor Verificationpub enum AccreditationStatus { NotVerified, Accredited { method: AccreditationMethod, verification_date: i64, expiration_date: i64, // Typically 90 days verifier: String, // e.g., "VerifyInvestor.com" }, NonAccreditedPermitted { regulation: OfferingRegulation, investment_limit: u64, }, } pub enum AccreditationMethod { Income, // $200K / $300K annual income NetWorth, // $1M+ net worth excluding primary residence Professional, // Series 7, 65, or 82 license Entity, // Qualified entity (bank, trust, etc.) KnowledgeTest, // SEC proposed "accreditation exam" }
๐น 3.6.3 Implementationpub fn verify_redemption_eligibility( wallet: &Pubkey, token_mint: &Pubkey, amount: u64, ) -> Result<()> { // KYC must be verified require!( investor.kyc_status == KycStatus::Verified, RedemptionError::KycIncomplete // 6004 ); // 72-hour sanctions cooling period require!( current_time - investor.sanctions_clear_timestamp >= cooling_period, RedemptionError::SanctionsCoolingPeriod // 6004 ); // Reg D 506(c): accreditation required 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 or missing for Reg D offerings.Note:Regular ST22 trading remains permitted โ only redemption to underlying shares is blocked.
๐ 3.7 Hook 5: Price Impact Circuit Breaker
The Price Impact Circuit Breaker prevents single transactions from causing excessive market movement, implementing regulatory objectives prohibiting manipulative trading devices. Any transaction causing greater than2% price movementagainst the Time-Weighted Average Price (TWAP) oracle is automatically rejected.
๐น 3.7.1 TWAP Oracle Integrationpub struct TwapOracle { pub token_mint: Pubkey, pub twap_1h: u64, pub twap_24h: u64, pub observation_count: u32, pub min_observations: u32, pub last_update_slot: u64, }
๐น 3.7.2 2% Threshold Enforcementpub const MAX_PRICE_IMPACT_BPS: u64 = 200; // 2.00% pub fn check_price_impact( pool: &LiquidityPool, trade_amount: u64, trade_direction: TradeDirection, ) -> Result<()> { let (post_sol_reserve, post_token_reserve) = 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 = post_sol_reserve * 1_000_000 / post_token_reserve; let deviation = if post_trade_price > twap { (post_trade_price - twap) * 10000 / twap } else { (twap - post_trade_price) * 10000 / twap }; require!( deviation <= MAX_PRICE_IMPACT_BPS, CircuitBreakerError::PriceImpactExceeded { expected_impact_bps: deviation, max_allowed_bps: MAX_PRICE_IMPACT_BPS, } // 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 protects all market participants from sudden price manipulation.
๐ 3.8 Hook 6: Liquidity Pool Sufficiency
The Liquidity Pool Sufficiency hook ensures the OTCM Liquidity Pool maintains adequate reserves to support all outstanding ST22 Digital Securities tokens. The hook confirms a minimum150% ratioof locked capital to circulating ST22 value before allowing redemption transactions.
๐น 3.8.1 150% Ratio Requirement
Component
Calculation
Locked Capital
Total SOL in unified LP (permanently locked)
Circulating Value
Sum of (ST22 supply ร current price) for all tokens
Sufficiency Ratio
Locked Capital รท Circulating Value ร 100%
Minimum Required
โฅ 150% โ redemptions pause if below
๐น 3.8.2 Implementationpub const MIN_SUFFICIENCY_RATIO_BPS: u64 = 15000; // 150.00% pub fn check_liquidity_sufficiency( pool: &UnifiedLiquidityPool, redemption_amount: u64, ) -> Result<()> { require!( post_redemption_ratio >= MIN_SUFFICIENCY_RATIO_BPS, LiquidityError::InsufficientLiquidity { current_ratio: post_redemption_ratio, required_ratio: MIN_SUFFICIENCY_RATIO_BPS, } // 6007 ); Ok(()) }
๐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.
๐ก๏ธ 3.9 Thirty-Six Supplementary Security Controls
Beyond the six primary Transfer Hooks, OTCM implementsthirty-six supplementary security controlsintegrated into the transfer hook logic โ creating a comprehensive42-point security framework.
๐น 3.9.1 Smart Contract Controls (1โ6)
#
Control
Description
1
Formal Verification
Certora Prover mathematical proof of contract correctness
2
Multi-Audit Requirement
Independent audits by Quantstamp, Halborn, and OtterSec
3
Immutable Bytecode
No proxy pattern โ code cannot be changed post-deployment
4
Bug Bounty Program
Up to $500K rewards for critical vulnerabilities
5
Reentrancy GuardsChecks-Effects-Interactions
patternenforcementenforcement
6
IntegerpreventingOverflowreentrancyProtection
Rust'sandcheckedCPIarithmeticprivilegeprevents overflowescalation attacks
๐น3.9.2Category
Access5ControlenforcesFrameworkthe Checks-Effects-Interactions (7โ12)
#
Control
Description
7
Multi-Sig Administration
4-of-7 threshold for administrative actions
8
Timelock Delays
48-hour delay on all parameter changes
9
Role-Based Access
Granular permission system (operator ยท compliance ยท admin)
10
Emergency Pause
2-of-7 emergency pause with 24hr auto-unpause
11
DAO Override
2/3 supermajority required for lock override
12
Key Rotation
Quarterly key rotation with HSM backing
๐น 3.9.3 Transaction Integrity Controls (13โ18)
Atomic Executionโ All-or-nothing transaction commitmentOrphan Preventionโ No partial execution states possibleReplay Protectionโ Unique transaction signatures prevent replayDeadline Enforcementโ Transactions expire after specified block heightSlippage Protectionโ User-configurable maximum price deviation
๐น 3.9.4 Oracle & Data Controls (19โ24)
Multi-Oracle Consensusโ Cross-reference multiple data sourcesStaleness Detectionโ Reject data older than threshold (10 min)Signature Verificationโ Ed25519 verification of all oracle dataRate Limitingโ Maximum oracle queries per block per mintFallback Oraclesโ Automatic failover to backup data sourcesData Freshness Proofsโ On-chain attestation of data recency
๐น 3.9.5 Monitoring & Alerting (25โ30)
Real-Time Monitoringโ 24/7 transactionCEI) patternanalysisAnomalyacrossDetectionโ ML-based unusual activity identificationSEC Notificationโ Automatic reporting of compliance failuresCompliance Dashboardโ Real-time visibility for regulatorsAudit Log Exportโ On-demand historical data retrievalAlert Escalationโ Tiered notification for severity levels
๐น 3.9.6 Governance & Recovery (31โ36)
Proposal Systemโ On-chain governance for parameter changesVoting Mechanismโ Token-weighted voting with delegationQuorum Requirementsโ Minimum participation thresholdsVeto Powerโ Compliance officer veto on security-relevant proposalsMigration Capabilityโ Controlled upgrade path for critical fixesDisaster Recoveryโ Documented procedures for catastrophic scenarios
โ 3.10 Error Handling and Recovery
Code
Hook
Condition
User Action
6001
Custody
Discrepancy >0.01%
Wait ยท retry ยท contact issuer
6002
OFAC
Sanctioned address
PERMANENT โ contact OFAC
6003
AML
Risk score 71โ100
Request compliance review
6004
Redemption
KYC / accreditation issue
Complete verification
6006
Price Impact
>2% TWAP deviation
Reduce size ยท split trade
6007
Liquidity
<150% pool ratio
Wait for ratio recovery
โก 3.11 Performance Specifications
Metric
Value
Notes
Total Hook Latency
750โ1,350ms
Sequential execution
Compute Units
~800,000 CU
Per complete transfer
Effective TPS
400โ600
Compliance overhead
Oracle Cost/Transfer
$2โ$5
Chainalysis ยท Empire APIs
๐all Cross-ProgramInvocation (CPI) Security Specification
CPI Boundary Map
Calling Program
Target Program
CPI Type
Accounts Passed
Privilege Check
TransferHook
TokenProgram (SPL Token-2022)
invoke_signed
mint ยท source ยท dest ยท authority
PDA authority verified โ no signer escalation
TransferHook
OracleRegistry
invoke
oracle_account ยท sequence_registry
Read-only โ no write authority passed
TransferHook
AuditLog
invoke_signed
audit_pda ยท system_program
PDA bump verified โ canonical bump enforced
CEDEX AMM
TransferHook
invoke
extra_account_metas
Hook invoked by token program โ not directly by AMM
IssuersPortal
TokenProgram
invoke_signed
mint_authority_pda
Mint authority is PDA โ program cannot overmint
Privilege Escalation Prevention:All OTCM programs useinvoke_signedonly when the signing PDA is owned by the calling program. No OTCM instruction passes a user-provided signer to a CPI target. Client-supplied accounts notInvocations intheExtraAccountMetaListPDA registry cause immediate instruction failure.
Account Discriminator Registry
Account Type
Discriminator (hex)
Program
Mutable
ComplianceState
a1 f3 07 2c 88 4e b1 d0
TransferHook
Yes
InvestorRecord
3b 9a c2 11 55 fe 07 44
TransferHook
Yes
OracleAttestation
c4 12 7a 38 f0 9d 22 b5
OracleRegistry
No
OracleSequenceRegistry
77 e8 01 4f 2d 6a b3 90
OracleRegistry
Yes
LpPoolState
58 3d aa 17 0c 84 f2 61
LiquidityPool
Yes
BondingCurveState
e9 04 b6 7c 13 2f 55 a8
BondingCurve
Yes
AuditLogEntry
2a 7f 03 c1 99 b4 8e d6
AuditLog
No
IssuanceRecord
6c 18 d5 40 aa 7b 33 f9
IssuersPortal
Yes
โ ๏ธ Discriminators above are specification targets. Actual deployed values are generated by Anchor at compile time fromsha256("account:")[..8]and must be verified against deployed program IDL before audit sign-off.
๐ก๏ธ Supplementary Security Controls โ Complete Technical Specification
Controls 7โ42 enforced atthe Transfer Hooklayerexecution chain. This prevents reentrancy attacks โ a class of exploit that has drained hundreds of millions of dollars from DeFi protocols by calling back into a contract before state updates complete. In OTCM's context, a reentrancy attack could theoretically allow an attacker to transfer tokens multiple times before balance state is updated.
#
Control
ClassificationName
Class
Controls
Description
Account Integrity
7โ13
Validate account ownership, sizes, and relationships
Transaction Integrity
14โ20
Enforce transaction-level constraints
Market Integrity
21โ27
Prevent manipulation and abnormal trading patterns
Operational Security
28โ35
Logging, rate limiting, and operational controls
Emergency Controls
36โ42
Circuit breakers and emergency response mechanisms
Controls 7โ13: Account Integrity
#
ControlTrigger Condition
Enforcement Action
Error
Code29
7Signer
VerificationValidation
TransferExpectedauthoritysigner(s)โnottokenpresentaccountinownertransactionorvaliddelegateReject โ invalid
signersigner. Error 60076007
830Account Owner Check
Any passed accountAccount not owned by expected programReject โ wrong
owneraccount owner. Error 60086008
931Mint Consistency
Source/
destdestination token accounts reference different mintsReject โ mint
mismatchmismatch. Error 60096009
1032Account Size Validation
Any accountAccount data length < minimum expected struct sizeReject โ corrupt
accountaccount. Error 60106010
1133Discriminator
ValidationCheckAccount discriminator โ expected 8-byte Anchor prefix
Reject โ type
confusionconfusion. Error 60116011
1234Token Account State
Source or
destdestination account in Frozen stateReject โ account
frozenfrozen. Error 60126012
1335Delegate Scope
CheckDelegated transfer amount > approved delegation amount
Reject โ delegation
exceededexceeded. Error 60136013
41
Controlled Migration
Emergency contract migration: 4-of-7 multisig + 48h timelock required
Allow migration only with full governance approval
6041
42
Regulatory Compliance Override
Law enforcement or SEC regulatory freeze order received
Comply per legal process โ targeted freeze only
6042
Controls14โ20:
Category 6: Transaction Integrity & Audit ยท 13 controls (43โ55 mapped as 3, 5, 6, 16โ19, 32โ35, 37, 39) controls
Arithmetic safety, atomic reversion guarantees, compute budget enforcement, and immutable audit log writes
Note on numbering: The Transfer Hook technical specification numbers controls 1โ42 with some controls mapped to operational sub-functions. The following table presents the transaction integrity and audit controls with their operational identifiers for reference. All execute on every transfer.
#
Control Name
Trigger Condition
Enforcement Action
Error
Code16
14
Zero-AmountArithmetic Overflow Guard
TransferAnyamountu64=arithmetic0would overflowReject โ
zerooverflowtransferdetected. All arithmetic uses u128 intermediate
60146016
1517
Self-TransferAtomicGuardRevert Guarantee
SourceAnywalletprior=controldestinationinwalletchain has failed
RejectFull atomic rollback โselfnotransferpartial state changes persist
60156017
1618
Overflow Guard
Amount arithmetic produces u64 overflow
Reject โ arithmetic overflow
6016
17
Atomic Execution
Any hook CPI fails mid-sequence
Full transaction revert
6017
18
Sequence IntegrityHook
executionOrderorderValidationviolated(mustrunControls
1โ6)not executing in defined sequenceReject โ hook order violation
6018
19
Timestamp Validity
Block timestamp > attestation expiry
Reject โ stale attestation
6019
20Duplicate
TransactionDetection
SameHighly(sourcesimilarยทtransactiondestsignatureยท amount ยท slot)seen within101slotsslotReject โ probable duplicate
60206019
Controls21โ27:32
MarketIntegrity
#
Control
Trigger Condition
Enforcement
Error Code
21
Wash Trade Detection
Source and destination wallets share verified KYC identity
Reject โ wash trade
6021
22
Wallet Concentration Limit
Post-transfer balance > 5% of circulating supply
Reject โ concentration limit
6022
23
Velocity Limit
Wallet transfers > 10 transactions within 100 slots
Reject โ velocity exceeded
6023
24
Graduated Token Lock
Transfer of pre-graduation tokens before vesting cliff
Reject โ locked tokens
6024
25
LP Drain Protection
Single transaction would reduce LP depth > 20%
Reject โ LP drain attack
6025
26
Price Oracle Deviation
Submitted price deviates > 5% from TWAP oracle
Reject โ price manipulation
6026
27
Coordinated Transfer Detection
>3 wallets with correlated transfer patterns in same slot
Flag + manual review
6027
Controls 28โ35: Operational Security
#
Control
Trigger Condition
Enforcement
Error Code
28
Immutable Audit Log
Every successful/failed transfer
Write audit PDA entry โ always
None (non-rejecting)
29
Rate Limit per Wallet
>50 transfer attempts per wallet per epoch (2.6 days)
Reject after threshold
6029
30
Rate Limit per Mint
>10,000 transfers per ST22 mint per slot
Reject until next slot
6030
31
Oracle Query Rate Limit
>22 oracle lookups per single transaction
Reject โ oracle abuse
6031
32Compute Budget Enforcement
Remaining CU < 50,000 before Hook 6
Reject โ insufficient
CUcompute budget6032
33
Account Rent Validation
Any account below rent-exempt minimum
Reject โ rent depleted
6033
34
Program Version Check
Caller program version < minimum compatible
versionReject โ version mismatch
6034
35
Key Rotation Compliance
Oracle signer key not in current oracle registry
Reject โ unrecognized signer
6035
Controls36โ42:37
EmergencyControls
#
Control
Trigger Condition
Enforcement
Error Code
36
Global Circuit Breaker
Protocol-wide pause activated by 3-of-4 multisig
Reject all transfers
6036
37Per-Mint Circuit Breaker
> 30% price movement in single slot
forspecificST22Halt mint-specific transfers
for1 hour6037
3839
Custody Discrepancy Halt
Token supply > custodied shares (oracle verified)
Halt all transfers for affected mint
6038
39OFAC Emergency Block
New OFAC SDN
listentry matching active walletImmediate freeze โ no grace period
6039
40
OracleConsensusFailure
<2 of 3 oracle feeds available for >5 minutes
Halt affected hook category
6040
41
Controlled Migration
Emergency contract migration โ 4-of-7 multisig + 48h timelock
Allow migration to new program
6041
42
Regulatory Compliance Override
Law enforcement or regulatory freeze order received
Comply per legal process
6042
๐จ3.4IncidentResponseCompleteandErrorOperationalCodeMonitoringRegistry
MonitoringEvery
Stackcontrol
Layer
Tool
MetricsfailureCollected
AlertproducesThreshold
SolanaaRPC
Helius Webhooks + custom indexer
Transaction success rate ยท block lag ยท RPC latency
Success rate <99% for 60s
Transfer Hook
On-chain event indexer (Geyser plugin)
Hook rejections byspecific error codeยทenablingCUpreciseconsumptiondiagnosisยทandexecutioncompliancetime
>5%reporting.rejectionTheratefollowingperis the authoritative error codeperregistryminutefor V7:
Oracle#[error_code]Networkpub enum TransferHookError {
Custom// Custody & Asset Backing#[msg("Custody oracle: token supply exceeds custodied shares")]
CustodyDiscrepancy = 6001,
#[msg("Custody oracle: attestation unavailable or stale (>400ms)")]
CustodyOracleUnavailable = 6002,
// Sanctions & AML
#[msg("OFAC: sender wallet matches SDN list")]
SenderSanctioned = 6003,
#[msg("OFAC: receiver wallet matches SDN list")]
ReceiverSanctioned = 6004,
#[msg("OFAC: oracle
monitordata stale โ cannot verify sanctions status")]
AttestationageOfacOracleStaleยท=sequence6005,gaps
ยท#[msg("AML:consensussenderfailuresor receiver risk score exceeds 70/100")]
AnyoracleSenderHighRisk>=staleness6006,threshold
CEDEXAMM// Investor Eligibility
Orderflow#[msg("KYC/Accreditation:metricsbuyer not verified accredited investor")]
FillrateKYCInvalidยท=slippage6004,ยท
LP#[msg("Holdingdepthperiod:ยทtokenscircuitlockedbreakerโfires
LPRuledepth drops >30% in 1 hour
API144 /PortalReg S not satisfied")]
DatadogAPMTokensLocked = 6024, // V7: replaces VestingLocked from V6
p95latencyยท
error//rateMarketยทIntegrityconcurrent
sessions#[msg("Wallet limit: destination would exceed 4.99% of supply")]
p95>500msWalletLimitExceededor=error6020,rate
>1%#[msg("Circuit breaker: price impact exceeds 2% TWAP deviation")]
SmartContractsCircuitBreakerTriggered = 6006,
Solanaprogram#[msg("Volumelog indexer
Error code frequency ยท account state anomalies
Any Error 6001 (custody) or 6036 (global halt)
Incident Severity Classification
Severity
Definition
Response Time
Escalation
P0 โ Critical
Trading halted ยท custody discrepancy ยท global circuit breaker ยท active exploit
15 minutes
Immediate โ all hands
P1 โ High
Oracle consensus failure ยท >10% hook rejection rate ยท CEDEX degraded
30 minutes
On-call engineer + CTO
P2 โ Medium
Single oracle feed down ยท elevated latency ยทhalt: singlehookwalletdegradedexceeds 30% daily sell limit")]DailySellLimitExceeded = 6037,
// CEI & Integrity
InvalidSigner = 6007,
WrongAccountOwner = 6008,
MintMismatch = 6009,
CorruptAccountSize = 6010,
AccountTypeConfusion = 6011,
AccountFrozen = 6012,
DelegationExceeded = 6013,
ZeroTransfer = 6014,
SelfTransfer = 6015,
ArithmeticOverflow = 6016,
AtomicRevert = 6017,
HookOrderViolation = 6018,
StaleAttestation = 6019,
// Emergency
GlobalCircuitBreaker = 6036,
PerMintCircuitBreaker = 6037,
CustodyDiscrepancyHalt = 6038,
OFACEmergencyBlock = 6039,
OracleConsensusFail = 6040,
ControlledMigration = 6041,
RegulatoryOverride = 6042,
}
2hours
On-callengineer
P3โ Low
Non-critical monitoring alert ยท performance degradation
Next business day
Ticket
Main
RTO/3.5
RPOTargets
Component
RTO
RPO
Degraded ModeTransfer Hook
enforcementEntry Point
TiedThe main Transfer Hook entry point coordinates all 42 controls through a structured validation sequence. Critical path controls (1, 8, 11, 12, 24) execute sequentially โ each must pass before the next runs. All other controls execute in parallel groups toSolanaminimizenetwork
N/Atotalโ on-chain, always consistent
No degraded mode โ transfers halt
CEDEX order matching
30 minutes
Zero โ orders queued, not lost
Read-only order book visible
Oracle network (primary)
5 minutes
Last confirmed attestation
Secondary oracle takes over
Investor portal
1 hour
5 minutes (session state)
Read-only mode
API (external)
2 hours
15 minutes
Cached responses
๐ Key Custodianship Register
Classification: Institutional Security Documentation | Review Cadence: Quarterly or upon any keyholder change
Privileged Key Inventory
Key
Holder
Custody Type
Rotation Schedule
Freeze Authority
Compliance Multisig (3-of-5)
AWS CloudHSM โ dedicated partition
Annual + upon regulatory event
Mint Authority
DISABLED โ burned post-mint
N/A
Cannot be re-enabled
Program Upgrade Authority
Admin Multisig (4-of-7)
Ledger hardware โ geographically distributed
Semi-annual
Oracle Signing Keys
Per-oracle HSM partitions
AWS CloudHSM (primary) ยท GCP CloudHSM (secondary)
Quarterly
Treasury SOL Multisig
Treasury Multisig (3-of-5)
Ledger hardware โ 5 keyholders
Annual
LP Emergency Override
Emergency Multisig (4-of-7)
Ledger hardware โ air-gapped signing
Used only in emergency
Freeze Authority Specification
Holder:Compliance Multisig โ 3-of-5 thresholdlatency.
PermittedUse Cases:
#[program]
pub mod transfer_hook {
use super::*;
pub fn transfer_hook(ctx: Context<TransferHook>, amount: u64) -> Result<()> {
let config = &ctx.accounts.security_config;
// โโ CRITICAL PATH: Sequential โโโโโโโโโโโโโโโโโโโโโโโโโ
// Control 1: Custody verification (Empire oracle)
verify_custody_oracle(&ctx.accounts.custody_oracle, amount, config)?;
// Controls 8-10: OFAC
SDNsanctionslist match โ mandatory freeze, no discretionActive law enforcement hold order โ mandatory freezeCourt-ordered asset freeze โ mandatory freeze- screening
SAR-trigger investigation hold โ discretionary, compliance officer approval required
ProhibitedUsecheck_ofac_sender(&ctx.accounts.sender,Cases:config)?;scoring
Competitive,
commercial,check_ofac_receiver(&ctx.accounts.receiver,orconfig)?;operational
reasonsRetaliationcheck_ofac_oracle_freshness(&ctx.accounts.ofac_oracle)?;or
disputeresolutionAny
use//notControlrelated11:toAMLregulatoryriskcompliancecheck_aml_risk(ctx.accounts.aml_oracle.sender_score)?;
// Controls 12-18: Investor eligibility & holding period
check_accreditation(&ctx.accounts.receiver, config)?;
check_holding_period(&ctx.accounts.holding_period_account)?; // Control 24
// โโ PARALLEL: Market integrity, CEI, Audit
Requirement:โโโโโโโโโโโ
Everycheck_wallet_limit(amount,freezeconfig)?;action//generatesControlan20check_price_impact(amount, config)?; // Control 25
check_volume_halt(amount, config)?; // Control 27
check_circuit_breaker(config)?; // Control 28
validate_cei_pattern(&ctx.accounts)?; // Controls 29-35
enforce_arithmetic_safety(amount)?; // Controls 16-19
// ... remaining controls 36-42 (emergency + audit) ...
// โโ AUDIT: Write immutable on-chain
auditcompliance record โemit!(
ControlTransferValidated28){mint: ctx.accounts.mint.key(),
from: ctx.accounts.source.key(),
to: ctx.accounts.destination.key(),
amount,
timestamp: Clock::get()?.unix_timestamp,
all_controls_passed: true,
});
Ok(())
}
}
3.6 Immutability Guarantee
The Transfer Hook cannot be removed or disabled after mint creation. This is a property of the SPL Token-2022 standard: once a token mint is created with a Transfer Hook extension, the hook program address is permanently stored in the mint account. The Token-2022 program will invoke that hook on every transfer for the entire existence of the token.
OTCM Protocol's Transfer Hook program upgrade authority is held by a 5-of-9 multi-signature wallet with geographically distributed key holders. All upgrades require a 24-hour timelock period during which the upgrade can be cancelled through DAO governance. Critically, even an upgrade cannot remove the 42 security controls โ the controls are defined in the program logic, and any upgrade that would materially weaken investor protections requires a
concurrentDAOoff-vote that passes the 66.67% supermajority threshold and satisfies the account schema compatibility attestation requirement.
Property
Mechanism
Who Controls It
Hook address permanence
SPL Token-2022 stores hook address in mint account permanently
No one โ Token-2022 program level, cannot be changed
Hook invocation
Token-2022 automatically calls hook via CPI on every transfer
No one โ mandatory at protocol level
Program upgrade authority
5-of-9 multi-sig with 24-hour timelock
5 of 9 designated key holders (geographically distributed)
Security control immutability
Controls in immutable on-chain
reportprogramtoโEmpireoutsideStockDAO governance scopeCannot be weakened by any party including OTCM Protocol
Parameter adjustments
DAO vote with 66.67% supermajority, 48-hour timelock, audit attestation
OTCM Security Token stakers
V7 Change Summary โ Transfer
withinHook ArchitectureThe only architectural change in V7 vs V6 for Section 3 is Control 24. In V6, Control 24
hours.enforced the 5-tranche issuer vesting schedule (20% unlocking at token minting, graduation, 6/12/18 months post-graduation). In V7, Control 24 enforces the Rule 144 holding period (6 months for US accredited investors) and the Regulation S distribution compliance period (12 months for non-US investors). The VestingConfig account structure is replaced by HoldingPeriodAccount. All other controls (1โ23, 25โ42) are unchanged from V6. Error code 6024 is retained for continuity with the Technical Specification document OTCM-TH-SPEC-001.
4-of-7AdminMultisigComposition
Requirements
Requirement
Specification
Geographic distribution
Minimum 4 distinct countries
Cloud provider distribution
No more than 2 keyholders on same cloud provider
Organizational distribution
Minimum 3 keyholders external toGroovy Company, Inc. dba OTCM Protocol
Hardwarewalletrequirement
All|keyholdersmustCIK:use1499275Ledgeror|equivalentFIPSVersion140-27.0certifieddevice
Key|ceremonyrequirement
InitialMarchkeyholder2026setupmust|occurvia documented key ceremony with legal witness
Replacement procedure
Lost keyholder: remaining 4-of-6 must authorize replacement via on-chain governance vote
๐งช Smart Contract Test Coverage Specification
Version: 6.1 | Status: Pre-Mainnet Requirements โ Must Be Met Before Launch CertificationConfidential
CoverageRequirements
Program
UnitTest Coverage
Integration Test Coverage
Fuzz Corpus Size
Status
TransferHook
โฅ 95% line coverage
All 42 controls tested
โฅ 10,000 inputs
Required pre-launch
CEDEX AMM
โฅ 92% line coverage
All order types + edge cases
โฅ 50,000 inputs
Required pre-launch
LiquidityPool (FLP)
โฅ 90% line coverage
Graduation + lock mechanics
โฅ 20,000 inputs
Required pre-launch
BondingCurve
โฅ 90% line coverage
Price invariant tests
โฅ 30,000 inputs
Required pre-launch
OracleRegistry
โฅ 95% line coverage
Consensus + replay tests
โฅ 5,000 inputs
Required pre-launch
IssuersPortal
โฅ 88% line coverage
KYC + accreditation flows
โฅ 5,000 inputs
Required pre-launch
๐ Transfer Hook Inter-Hook State Model
Version: 6.1 | Critical: Defines shared account access between hooks
Hook Isolation Guarantee
Each of the six Transfer Hooks isstateless with respect to the othersduring a single transaction execution. Hooks do NOT write shared mutable state that subsequent hooks read. This eliminates TOCTOU (time-of-check-time-of-use) vulnerabilities between hooks.HOOK
EXECUTION MODEL: Transaction Input Accounts (immutable snapshot for all hooks) โ โโโโบ Hook 1 reads: oracle_cache_pda (readonly) โ writes: audit_log_pda (append-only) โ โโโโบ Hook 2 reads: ofac_oracle_pda (readonly) ยท investor_record (readonly) โ writes: audit_log_pda (append-only) โ โโโโบ Hook 3 reads: aml_oracle_pda (readonly) ยท investor_record (readonly) โ writes: audit_log_pda (append-only) โ โโโโบ Hook 4 reads: investor_record (readonly) ยท compliance_state (readonly) โ writes: audit_log_pda (append-only) โ โโโโบ Hook 5 reads: price_oracle_pda (readonly) ยท lp_pool_state (readonly) โ writes: audit_log_pda (append-only) โ โโโโบ Hook 6 reads: lp_pool_state (readonly) writes: audit_log_pda (append-only) KEY PROPERTY: All cross-hook reads are from (readonly) accounts. No hook reads data that a prior hook has written. audit_log_pda is append-only โ no hook reads what another hook wrote.
Account Mutability Map Per Hook
Account
Hook 1
Hook 2
Hook 3
Hook 4
Hook 5
Hook 6
oracle_cache_pda (custody)
R
โ
โ
โ
โ
โ
ofac_oracle_pda
โ
R
โ
โ
โ
โ
aml_oracle_pda
โ
โ
R
โ
โ
โ
price_oracle_pda
โ
โ
โ
โ
R
โ
investor_record_pda
โ
R
R
R
โ
โ
compliance_state_pda
R
โ
โ
R
โ
โ
lp_pool_state_pda
โ
โ
โ
โ
R
R
audit_log_pda
W
W
W
W
W
W
sequence_registry_pda
W
โ
โ
โ
โ
โ
R = Read-only ยท W = Write ยท โ = Not accessed
โ๏ธ Compute Unit Budget Specification
Version: 6.1 | Pre-Mainnet Benchmarks Required Before Launch
Component
Operation
Measured CU (avg)
Worst-Case CU
Hook 1
Custody oracle balance read
~18,000
28,000
Hook 2
OFAC fuzzy name match
~95,000
140,000
Hook 3
AML risk score lookup
~22,000
35,000
Hook 4
KYC / accreditation PDA check
~14,000
20,000
Hook 5
TWAP + 2% impact calculation
~45,000
68,000
Hook 6
LP reserve sufficiency check
~12,000
18,000
Base AMM
CPMM swap logic
~180,000
220,000
Account validation
Discriminator + owner checks
~15,000
22,000
Audit logging
On-chain event emission
~8,000
12,000
TOTAL
~409,000
~563,000 (40% of cap)
Priority Fee Strategy:Dynamic fee computed asbase_fee ร clamp(recent_fee_p75 / base_fee, 1.0, 10.0). Transactions resubmitted with escalating fees at 5-second intervals, up to 3 retries before returningTRANSACTION_TIMEOUT.
โ ๏ธPre-Launch Requirement:All six Transfer Hook programs must complete CU profiling under worst-case conditions (500-entry OFAC list, minimum LP depth) before mainnet certification.
๐ก๏ธ 3.12 Security Audit Status
Audit Program โ Pre-Mainnet Certification Gates
All four audit engagements below arehard launch gates. Mainnet deployment is prohibited until every gate is cleared with zero open Critical or High severity findings.
Firm
Scope
Status
Gate Requirement
Quantstamp
TransferHook programs (all 42 controls) ยท CEDEX AMM ยท LiquidityPool
Engagement initiated Q1 2026
Final report โ 0 Critical/High open
Halborn
Oracle network ยท key management ยท infrastructure penetration test
Engagement in progress
Final report โ 0 Critical/High open
OtterSec
BondingCurve ยท IssuersPortal ยท staking contracts
Preliminary review complete โ full audit Q2 2026
Final report โ 0 Critical/High open
Certora
Formal verification of CPMM invariant (xรy=k) ยท Transfer Hook atomicity ยท LP lock permanence
Specification complete โ proof development Q1 2026
All specified invariants proved โ no counterexamples
Bug Bounty Program
Active bug bounty required minimum30 daysbefore mainnet launch.
Severity
Reward
Example Vulnerability
Critical
Up to $100,000
Transfer Hook bypass ยท LP fund extraction ยท mint authority exploit
High
Up to $25,000
Oracle replay attack ยท CPI privilege escalation ยท freeze authority bypass
Medium
Up to $5,000
Circuit breaker bypass ยท rate limit evasion ยท account spoofing
Low
Up to $500
Gas optimization issues ยท non-critical logic errors
Submissions:security@otcm.io โ PGP key published at otcm.io/security.txtScope:All on-chain programs ยท oracle infrastructure ยท CEDEX order matching engineOut of scope:Frontend UI ยท third-party dependencies ยท known issues in public tracker
Groovy Company, Inc. dba OTCM Protocol ยท Wyoming Corporation ยท invest@otcm.io ยท otcm.ioBack to top