4. Execution RoadmapPhase 2: Encrypted Security

4.2. Phase 2: Encrypted Security & Settlement

Quick Summary

Phase 2 transitions the protocol from architectural scaffolding to active cryptographic and economic logic. The core objective is to establish a trustless settlement layer that verifies bidder solvency without decryption, replaces vulnerable push-based payouts with a gas-safe Pull over Push pattern, and implements a Dynamic Dead Man's Switch for automatic capital recovery during network failures. Completion of this phase locks in the protocol’s fundamental security guarantees and unblocks off-chain integration (Phase 3).

Detailed Answer (Cited)

Phase Objective

  • Execute encrypted solvency validation via FHE.lte() on-chain.
  • Architect individual claimRefund() paths with hasWithdrawn state mapping.
  • Deploy DynamicTimeout using Moving Time Average of block.timestamp (× 1.5 factor).
  • Implement triggerFallbackVoid() for 100% liquidity recovery and NFT return.
  • Build SlashedPot.sol for pro-rata compensation during seller cancellations.

Target File Structure

packages/contracts/
├── core/FhenixFairMarket.sol # placeBid, claimRefund, triggerFallbackVoid, cancelAuction
├── settlement/
│ ├── SettlementEngine.sol # Async resolution queue management
│ └── SlashedPot.sol # Compensation pool & pro-rata distribution
├── interfaces/ISettlementEngine.sol # Unified resolution signatures
├── tasks/
│ ├── triggerFinalize.ts # CLI simulation for closure
│ └── emergencyHalt.ts # CLI simulation for void state
└── test/
 ├── unit/AsyncResolution.test.ts # Encrypted settlement & pull logic
 └── unit/DynamicTimeout.test.ts # Sequencer outage simulation

️ Execution Tasks & Audit Gates

TaskDescriptionAudit Gate Check
2.1 Encrypted SolvencyApply FHE.lte(encryptedBid, escrowBalances) to validate capacity without revealing plaintextInvalid bids revert instantly; zero plaintext leakage
2.2 Pull Refund PatternDesign claimRefund() with mapping hasWithdrawn; eliminate all for/while loops in payout logicZero loops in refund/compensation functions
2.3 Dynamic TimeoutBuild _getResolutionTimeout() using Moving Time Average of block.timestamp with ×1.5 bufferThreshold adapts to network volatility; no hardcoded values
2.4 Emergency VoidImplement triggerFallbackVoid() to recover 100% liquidity, return NFT, and disable FHE engineFull liquidity recovery; FHE engine disabled post-void
2.5 SlashedPot IntegrationDevelop SlashedPot.sol to distribute cancellation penalties pro-rata; platform takes 0% cutPenalties distributed fairly; zero platform extraction

️ Technical Implementation

1. Pull-Over-Push Refund (claimRefund)

State mutation precedes external transfer, neutralizing reentrancy and Out-of-Gas (OOG) risks.

function claimRefund(uint256 _auctionId) external {
 require(state == FINALIZED || state == CANCELLED || state == VOIDED, "Invalid state");
 require(!hasWithdrawn[msg.sender], "Already withdrawn");
 
 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, "Refund transfer failed");
}

2. Dynamic Dead Man’s Switch (_getResolutionTimeout)

Replaces fixed block counts with a network-volatility-aware calculation.

function _getResolutionTimeout() internal view returns (uint256) {
 uint256 lastTime = lastBlockTimestamp > 0 ? lastBlockTimestamp : block.timestamp - 12;
 uint256 avgBlockTime = block.timestamp - lastTime;
 return avgBlockTime * 1.5; // Self-compensating factor
}

3. Emergency Void & FHE Disable (triggerFallbackVoid)

Permissionless activation guarantees capital preservation during sequencer/AVS failures.

function triggerFallbackVoid(uint256 auctionId) external {
 Auction storage auction = auctions[auctionId];
 require(auction.state == RESOLVING, "Invalid state");
 require(block.timestamp > auction.endTime + _getResolutionTimeout(), "Timeout not exceeded");
 
 auction.state = AuctionState.VOIDED;
 auction.fheEngineActive = false; // Disables further decryption attempts
 emit AuctionVoided(auctionId, block.timestamp);
}

Confirmed Facts

  1. Zero Loop Policy: The README.md and Phase 2 Matrix explicitly ban for/while loops in any payout or compensation function to prevent OOG cascades.
  2. State-First Mutation: hasWithdrawn[msg.sender] = true executes before msg.sender.call, strictly adhering to the Checks-Effects-Interactions pattern.
  3. Dynamic Threshold Calculation: Timeout is derived exclusively from block.timestamp deltas with a 1.5x multiplier; static integers are prohibited.
  4. Platform Neutrality: SlashedPot.sol distributes 100% of seller cancellation deposits to participants. Administrative fees are strictly excluded from penalty pools.
  5. Test Coverage Requirement: All new settlement logic must achieve ≥90% P0 test coverage before merging.

Unresolved Points & Explicit Gaps

  • Gas Sponsorship for Refunds: While claimRefund() uses the Pull pattern, the documentation does not explicitly detail whether Phase 5’s ERC-4337 bundler will sponsor gas for these claims or if users must pay natively. Requires clarification in Phase 5 UX 2.0 specs.
  • Long-Tail Claim Window: No hard deadline (e.g., 90 days) is specified for unclaimed refunds. The current implementation implies perpetual availability, which may create minor long-term storage bloat. Classified as P2 optimization.
  • Cross-Chain Claim Routing: No architectural provision exists for migrating unclaimed refunds to alternate L2s if the primary Fhenix network experiences prolonged degradation.

Fact vs. Analysis Note: The Pull over Push pattern is a verified security standard (Fact). Its adoption here eliminates OOG/reentrancy risks (Analysis). The absence of an unclaimed refund sweep mechanism is a documented gap in the current P0/P1 matrix, not a flaw in the core pattern itself.

Sources (Internal Documentation References)

  1. Phase 2 Sub-Tasks Matrix.txt → Tasks 2.1–2.5, Audit Gate Criteria
  2. 6 مراحل تنفيذي.txt → Phase 2 Execution Roadmap & Duration (12–16 days)
  3. المرحلة 2.txt → Target folder structure & new file paths (settlement/, tasks/, test/unit/)
  4. وثيقة المواصفات التقنية الرسمية.txt → Section 4.2 (claimRefund & DynamicTimeout implementation)
  5. README.md → Security Model Table, Pull Refund Pattern, State Machine definitions

Next Steps