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 withhasWithdrawnstate mapping. - Deploy
DynamicTimeoutusingMoving Time Averageofblock.timestamp(× 1.5factor). - Implement
triggerFallbackVoid()for 100% liquidity recovery and NFT return. - Build
SlashedPot.solfor 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
| Task | Description | Audit Gate Check |
|---|---|---|
| 2.1 Encrypted Solvency | Apply FHE.lte(encryptedBid, escrowBalances) to validate capacity without revealing plaintext | Invalid bids revert instantly; zero plaintext leakage |
| 2.2 Pull Refund Pattern | Design claimRefund() with mapping hasWithdrawn; eliminate all for/while loops in payout logic | Zero loops in refund/compensation functions |
| 2.3 Dynamic Timeout | Build _getResolutionTimeout() using Moving Time Average of block.timestamp with ×1.5 buffer | Threshold adapts to network volatility; no hardcoded values |
| 2.4 Emergency Void | Implement triggerFallbackVoid() to recover 100% liquidity, return NFT, and disable FHE engine | Full liquidity recovery; FHE engine disabled post-void |
| 2.5 SlashedPot Integration | Develop SlashedPot.sol to distribute cancellation penalties pro-rata; platform takes 0% cut | Penalties 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
- Zero Loop Policy: The
README.mdandPhase 2 Matrixexplicitly banfor/whileloops in any payout or compensation function to prevent OOG cascades. - State-First Mutation:
hasWithdrawn[msg.sender] = trueexecutes beforemsg.sender.call, strictly adhering to the Checks-Effects-Interactions pattern. - Dynamic Threshold Calculation: Timeout is derived exclusively from
block.timestampdeltas with a1.5xmultiplier; static integers are prohibited. - Platform Neutrality:
SlashedPot.soldistributes 100% of seller cancellation deposits to participants. Administrative fees are strictly excluded from penalty pools. - 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 inPhase 5 UX 2.0specs. - 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
P2optimization. - 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 Pushpattern 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 currentP0/P1matrix, not a flaw in the core pattern itself.
Sources (Internal Documentation References)
Phase 2 Sub-Tasks Matrix.txt→ Tasks 2.1–2.5, Audit Gate Criteria6 مراحل تنفيذي.txt→ Phase 2 Execution Roadmap & Duration (12–16 days)المرحلة 2.txt→ Target folder structure & new file paths (settlement/,tasks/,test/unit/)وثيقة المواصفات التقنية الرسمية.txt→ Section 4.2 (claimRefund&DynamicTimeoutimplementation)README.md→ Security Model Table, Pull Refund Pattern, State Machine definitions
Next Steps
- Proceed to 4.3. Phase 3: CoFHE & AVS Integration to implement asynchronous event dispatching and EigenLayer verification.
- Review Security Model → Pull Refund Pattern for detailed reentrancy mitigation analysis.
- Explore Developer Quickstart → Settlement Tests to run local
claimRefundandDynamicTimeoutsimulations.