2. Security & Integrity
The Fhenix-FairMarket protocol operates on a foundational security philosophy: “Trust in cryptographic proof, not in intermediaries.” Every architectural decision prioritizes mathematical privacy, economic finality, and capital preservation. The system implements a defense-in-depth strategy across cryptographic, economic, and operational layers, ensuring resilience against MEV extraction, sequencer failures, oracle manipulation, and smart contract vulnerabilities.
Version 2.0 replaces traditional trust assumptions with verifiable, mathematically bounded mechanisms, enforced through strict audit gates and zero-tolerance security policies at the CI/CD level.
2.1. Fully Homomorphic Encryption (FHE)
FHE forms the cryptographic bedrock of the protocol, enabling bid comparisons and settlement logic without ever decrypting sensitive values on-chain.
Core Implementation
- Client-Side Encryption: Bids are encrypted locally using
@cofhe/sdk ^1.2.0before transmission. The plaintext value never traverses the network or enters the mempool. - Constant-Time Execution: Off-chain
FHEOScoprocessors utilizeFHE.selectmultiplexers, ensuring execution clocks remain identical regardless of input magnitude. This neutralizes timing side-channel attacks. - Solvency Pre-Validation: Before accepting a bid, the contract runs an encrypted solvency gate:
FHE.lte(encryptedBid, FHE.asEuint32(escrowBalances[msg.sender])). Invalid bids revert instantly without consuming coprocessor resources or leaking balance information.
Security Guarantees
| Threat | Mitigation |
|---|---|
| Mempool Sniping / MEV | Bids arrive as opaque ciphertexts; validators cannot reorder or front-run based on value |
| Plaintext Leakage | Zero bid values in Events, Storage, or console.log; enforced by CI lint rules |
| SDK Version Breakage | All FHE calls routed through CofheAdapter.sol, isolating core logic from external library updates |
2.2. O(1) On-chain Storage
Traditional FHE implementations store full ciphertext arrays on-chain, causing exponential gas growth and bloated state. Fhenix-FairMarket v2.0 enforces a strict O(1) storage model.
Technical Enforcement
- Hash-Only Persistence: Only a
bytes32keccak256 hash of the ciphertext is pushed tociphertextHashes[auctionId]. The full FHE object is never persisted. - State Decoupling: Heavy homomorphic operations (
FHE.gt,FHE.select) are executed off-chain viaDecryptionRequestedevents. The L2 chain acts solely as an immutable ledger and event broadcaster. - Gas Predictability: Each
placeBid()transaction consumes a flat~15k–25kgas, independent of auction size or bid count.
Architectural Impact
// Only hash stored. No FHE evaluation, no decryption, no loops.
ciphertextHashes[auctionId].push(keccak256(abi.encode(encryptedBid)));
emit BidPlaced(auctionId, msg.sender, keccak256(abi.encode(encryptedBid)));This design ensures linear scalability, prevents state bloat, and eliminates gas-based DoS vectors during high-volume settlement windows.
2.3. Pull over Push Refund Pattern
Automated distribution (Push) of refunds to non-winning bidders introduces severe risks: Out-of-Gas (OOG) failures, reentrancy vulnerabilities, and cascading state rollbacks. The protocol mandates a Pull-based Settlement model.
Implementation Logic
- State Update Precedence:
hasWithdrawn[msg.sender]is set totruebefore the externalcall{value: amount}executes. - Individual Claim Path: Each participant invokes
claimRefund()independently. The contract verifies eligibility, updates state, and releases funds. - Zero Loop Dependency: Refund distribution contains no
for/whileloops, ensuring transaction success is deterministic and immune to participant count.
function claimRefund(uint256 _auctionId) external {
require(state == FINALIZED || state == CANCELLED || state == VOIDED);
require(!hasWithdrawn[msg.sender]);
uint256 amount = escrowBalances[msg.sender];
escrowBalances[msg.sender] = 0;
hasWithdrawn[msg.sender] = true; // State updated BEFORE transfer
(bool success, ) = msg.sender.call{value: amount}("");
require(success);
}Security Benefits
- Reentrancy Immunity: State mutation precedes value transfer, breaking classic reentrancy attack vectors.
- OOG Elimination: No single transaction bears the gas burden of mass payouts. Failed claims do not block others.
- Idempotency:
hasWithdrawnmapping prevents double-claiming even under network retries or UI glitches.
2.4. Dynamic Dead Man’s Switch
Fixed timeouts are vulnerable to sequencer downtime, network congestion, and L2 rollup halts. The protocol replaces static deadlines with a Dynamic Dead Man’s Switch based on network volatility.
Technical Implementation
- Moving Time Average: The resolution timeout is calculated dynamically:
avgBlockTime = block.timestamp - lastBlockTimestamp. The threshold auto-adjusts using a1.5xself-compensating factor. - Automatic Void Transition: If
block.timestampexceedsendTime + _getResolutionTimeout()without a valid AVS resolution,triggerFallbackVoid()executes automatically. - Full Liquidity Recovery: The auction transitions to
VOIDED, the FHE engine is disabled, and 100% of escrowed funds are unlocked for immediate pull-refund.
function _getResolutionTimeout() internal view returns (uint256) {
uint256 avgBlockTime = block.timestamp - lastBlockTimestamp;
return avgBlockTime * 1.5; // Network volatility-aware threshold
}Resilience Guarantees
- Sequencer Failure Tolerance: Automatically activates during L2 outages, preventing indefinite fund lockup.
- No Manual Intervention: Void execution is deterministic and permissionless; no admin keys required.
- Funds Over Privacy: In extremis, capital recovery takes precedence over cryptographic settlement.
2.5. Fraud Proofs & Slashing
Replacing computationally expensive ZK-circuits, the protocol leverages EigenLayer Actively Validated Services (AVS) for decentralized, cryptoeconomic verification.
Verification Pipeline
- Threshold Consensus: Off-chain operators cryptographically sign the FHEOS result.
submitResolution()only accepts the output once a quorum (e.g.,3/5) is reached. - On-Chain Proof Verification: The smart contract cryptographically validates the aggregated
avsProofbefore transitioning state toFINALIZED. - Fraud Proof Challenge Window: Permissionless verifiers can submit a
Fraud Proofif the aggregated signature mismatches the actual FHE computation. - Automatic Slashing: Validated fraud triggers the EigenLayer slashing contract. Operator stake is deducted and routed to
SlashedPot.solfor pro-rata user compensation.
Economic Security Model
| Component | Role | Enforcement |
|---|---|---|
| AVS Operators | Provide decentralized verification | Must stake ETH/LSTs via EigenLayer |
| Fraud Proofs | Validate off-chain results | Permissionless challenge mechanism |
| Slashing | Penalize collusion/incorrectness | Automatic stake deduction to SlashedPot |
| On-Chain Verifier | Accepts only valid proofs | Reverts on cryptographic mismatch |
This model ensures fast finality, linear scalability, and robust economic alignment without heavy computational overhead.
2.6. Collateral-Pegged Escrow
The protocol enforces a Dummy Ceiling Deposit model to guarantee bid solvency and deter malicious spam without exposing actual bid values.
Mechanism
- Public Escrow Lock: Bidders invoke
lockEscrow()to deposit a publicly visible maximum ceiling (e.g.,5 ETH). - Encrypted Bid Validation:
placeBid()runsFHE.lte(encryptedBid, escrowBalances[msg.sender]). If the encrypted value exceeds the public deposit, the transaction reverts. - NFTGuard Integration: During
ACTIVEstate,NFTGuard.sollocks the seller’s asset. Transfer is blocked untilFINALIZED,CANCELLED, orVOIDED. - Cancellation Penalty: If a seller cancels an active auction (
cancelAuction()), their deposit is confiscated and distributed pro-rata to bidders viaSlashedPot.sol. The platform takes zero cut from penalties.
Security & Economic Alignment
- Spam Mitigation: Requires upfront capital, eliminating sybil bidding and gas-wasting spam.
- Seller Accountability: Financial penalty for withdrawal deters shill bidding and market manipulation.
- Capital Preservation: All escrowed funds remain under user control until settlement, with automatic recovery paths on failure.
️ Threat Matrix & Mitigations
| Threat | Attack Vector | Protocol Mitigation |
|---|---|---|
| Bid Value Leak | Event emitting plaintext or storage exposure | Only bytes32 ciphertext hashes in Events/Storage; enforced by CI linting |
| Reentrancy in Refund | claimRefund() called before state update | hasWithdrawn set to true before call{value: amount} |
| Session Key Theft | localStorage key caching | ERC-4337 Ephemeral Keys (24h TTL, memory/Web Crypto only) |
| Sequencer Manipulation | Exploiting fixed timeout windows | Moving Time Average × 1.5 dynamic threshold |
| Fake AVS Result | Corrupt operator output or collusion | EigenLayer Fraud Proof required before submitResolution() |
| Keeper Race Condition | Multiple keepers competing for closure | nonce/blockhash gating + Redis distributed locks |
| Gas Exhaustion (DoS) | Push-based payout loops | Batch queue max 10/block; all refunds are Pull-based |
| Upgrade Manipulation | Unauthorized proxy upgrade | UUPSUpgradeable + 48h Timelock + 5/9 Multisig |
Emergency Protocol: Funds Over Privacy
In case of critical @cofhe/sdk vulnerability, EigenLayer network failure, or prolonged coprocessor outage, EmergencyHalt activates automatically or via multisig:
- Freeze FHE Engine: New encryption and bid submissions are permanently blocked.
- Open Public Refund Path:
claimRefund()bypasses AVS verification, allowing immediate capital recovery. - Return NFT to Seller:
NFTGuardunlocks and transfers assets back to the original owner. - Emit
EmergencyHaltActivated: Full on-chain transparency for auditors and users.
Principle: Funds are protected before privacy in extreme emergency conditions.
Audit Readiness & P0 Checklist
The protocol enforces a strict Priority Classification for all security items. Progression to the next development phase is blocked until all P0 items pass.
| Priority | Description | Criteria |
|---|---|---|
| P0 | Security-critical | Must be complete before any deployment |
| P1 | High importance | Must be complete before Mainnet launch |
| P2 | Enhancement | Target for v2.1 optimization |
Mandatory P0 Verification Checklist
- []
UUPS Proxyisolation — zero logic in storage contract, unauthorized upgrades revert - []
CofheAdapterabstraction — zero direct FHE imports in core contracts - [] State machine exhaustive — all 6 states reachable, no unauthorized transitions
- []
FHE.ltesolvency check — encrypted bid never exceedsescrowBalances[msg.sender] - [] Pull refund pattern — zero
for/whileloops in any payout function - [] Dynamic timeout —
Moving Time Averagenot hardcoded; adapts to network conditions - []
triggerFallbackVoid()— 100% liquidity recovery on activation - [] No plaintext bids — zero bid values in Events or Storage (CI enforced)
- [] AVS Fraud Proof —
submitResolution()rejects without valid cryptographic proof - [] ERC-4337 session keys — no
localStorageor cookie storage (ESLint rule enforced) - [] Sequential deployment —
Adapters → Proxy → Factoryordering guaranteed - [] Environment secrets — zero keys in
hardhat.config.tsornext.config.js
Next Steps
- Proceed to 3. Market Mechanics to explore sealed-bid workflows, Vickrey pricing, and MEV protection.
- Review Technical Components for contract-level references, function signatures, and deployment architecture.
- Explore Developer Quickstart to run local security simulations and audit readiness tests.