Auditing EIP-2535 Diamond Escrow State Machines: Sponsored Hook Locks, Commitment Hashes & Allowlist Architecture

Modular smart-contract architectures built on EIP-2535 Diamonds solve the 24 KB Spurious Dragon bytecode ceiling by splitting business logic across selector-routed facets that share diamond storage structs via delegatecall. Yet that exact modularity introduces a subtle class of cross-facet invariant bugs: one facet mutates task lifecycle timestamps or reward balances while an external hook contract or sibling facet still trusts an earlier cryptographic commitment. In earlier posts we examined disassembling PUSH0 stake-trap bytecode and hardening TypeScript CLI signers; here we dissect the five core Solidity state-machine and pool-accounting findings (F-01 through F-05) uncovered during our line-by-line review of the TaskMarket EIP-2535 Diamond (0x001D206aD5b094303819272b8509B20c05C09616 on Base Mainnet and rev025–rev027 facets), along with the Solidity IHookAllowlist registry pattern submitted upstream in GitHub Issue #21.

EIP-2535 Diamond Escrow State Machine and Sponsored Hook Security Audit Architecture
Mapping selector routing across CoreFacet, ReviewFacet, FundingPool, and HookRouter inside an EIP-2535 Diamond escrow contract—highlighting cross-facet invariant drift across F-01 through F-05.

1. Why Cross-Facet State Machines Drift in EIP-2535 Diamonds

In a monolithic escrow contract, every state transition—deposit, claim, submission, review verdict, lapsed timeout, and cancellation—lives within a single file where internal helper modifiers enforce conservation of funds. Inside an EIP-2535 Diamond, however, responsibilities are partitioned across independent deployment units:

  • CoreFacet & LibTask: Owns task creation, reward updates (updateTask), expiry timestamps, and worker claim state inside diamond storage slot keccak256("taskmarket.storage.task").
  • ReviewFacet: Governs verifier verdicts (finalizeVerdict), dispute windows, and timeout fallbacks (settleLapsedReview).
  • FundingPool & LibProject: Manages crowdfunded ERC-20 liquidity shares, operator grant ceilings (GrantTerms.cap), and project horizon locks (latestExpiry).
  • HookRouter (0xddc6cc3e4d11c1f3527b867c7dad4ed9869c33f7): Dispatches lifecycle callbacks (onCreate, checkClaim, checkSubmit, onSettle, onCancel, onExpire, onForfeit) to external hook contracts under a fixed gas stipend.

Whenever a new terminal path is added to ReviewFacet without symmetrical reconciliation branches in external hooks, or when CoreFacet mutates a struct field that an external hook hashed during onCreate, funds either lock permanently or leak across accounting boundaries.

2. Finding F-01 (High): Stranded Sponsor Credits in SponsoredTaskHook.reconcile

Protocol-sponsored tasks allow gasless or subsidized task creation by reserving ERC-20 sponsor budget inside SponsoredTaskHook (and its cross-chain counterpart RemoteSponsoredTaskHook) when a task opens. Once the task reaches a terminal state, reconcile(bytes32 taskId) inspects the settled task view from the Diamond to release any unspent reservation back to the sponsor pool.

During our audit of SponsoredTaskHook.reconcile, we traced every terminal transition for non-auction task modes (CLAIM, PITCH, BOUNTY, and BENCHMARK). While standard payouts and explicit cancellations released unused sponsor reservations cleanly, two timeout-driven settlement paths left the reservation struct in an unreleasable state:

  1. Lapsed Verifier Reviews (settleLapsedReview): When a requester or designated verifier fails to grade a worker's submission before reviewDeadline, ReviewFacet.settleLapsedReview transitions the task to settled without setting the exact auction clearing flags expected by reconcile().
  2. Post-Expiry Verdict Finalization (finalizeVerdict after expiry): When a multi-submission BOUNTY or BENCHMARK task crosses its nominal submission expiry before final scoring completes, the reconciliation branch treats the reservation as still active while the Diamond marks the task closed.

Because neither party can re-open a closed task ID in LibTask, those reserved sponsor tokens remain permanently immobilized inside the hook contract. Fixing F-01 requires keying reconcile() strictly on the Diamond's authoritative terminal enum (TaskStatus.Completed | Cancelled | Expired) minus actual disbursed principal, independent of which facet triggered closure.

3. Finding F-02 (High): Post-Creation Reward Slashing Beyond taskTermsHash

Cryptographic term commitments are only as trustworthy as the immutability of the fields they cover. During task creation, SponsoredTaskHook computes a taskTermsHash over the initial reward, mode, and terms parameters to verify sponsor authorization. However, CoreFacet.updateTask subsequently permitted the task creator to modify mutable task parameters prior to final settlement—including reducing the escrowed reward amount all the way down to 1 wei—without re-validating taskTermsHash against SponsoredTaskHook or enforcing a monotonic floor once worker work-in-progress or pitch preparation had begun.

// Vulnerable cross-facet assumption in CoreFacet.updateTask:
// Mutates LibTask.TaskStorage without re-verifying hook commitment invariants.
if (newReward == 0) revert ZeroReward();
task.reward = newReward; // Can drop from 100e6 USDC to 1 wei!
// Missing: require(newReward >= task.reward, "RewardReductionForbidden");
// Missing: HookRouter.notifyTermsUpdated(taskId, computeTaskTermsHash(task));

Enforcing newReward >= task.reward (reward-increase-only semantics) on live tasks eliminates bait-and-switch reward slashing while preserving a requester's ability to top up bounties when scope expands.

4. Findings F-03 & F-04 (High): FundingPool Cap Dilution and 136-Year Liquidity Locks

When multiple contributors back a shared R&D grant pool via FundingPool, operators are given bounded spending authority through GrantTerms.cap and a maximum time horizon via LibProject.latestExpiry. Two subtle interactions broke both guarantees:

Finding ID Affected Module Broken Conservation Invariant Recommended Solidity Fix
F-03 (High) LibProject._release & FundingPool When a staked claim forfeits with penalty routed back to the project, LibProject._release credits returned funds against spent grant accounting—allowing an operator to self-forfeit staked claims in a loop to inflate cumulative spending past GrantTerms.cap and dilute passive LP share value. Track cumulativeGrantAllocated separately from forfeited worker collateral; never decrement spent operator cap on stake inflows.
F-04 (High) CoreFacet & LibProject.latestExpiry While initial task creation checks task.expiry <= project.latestExpiry, five downstream extension paths (deadline extensions, reopen-on-forfeit, review grace windows, pitch extensions, and dispute timers) write updated uint40/uint32 timestamps without re-checking project.latestExpiry. Centralize all deadline writes inside LibTask._setExpiry(task, newExpiry) and revert with ExceedsProjectHorizon() whenever projectId != 0 && newExpiry > project.latestExpiry.

Without LibTask._setExpiry clamping every extension path, a compromised or adversarial project operator can push a single open task's expiry to type(uint32).max (year 2106, ~136 years from Unix epoch), keeping FundingPool.outstanding > 0 and blocking backers from withdrawing unspent pool principal.

5. Finding F-05 & F-06: Lapsed Multi-Submission Deadlocks, Gas-Stipend Griefing & IHookAllowlist

On Tempo Mainnet (0xF4f4...97e7, rev025) and Base Mainnet, we also audited what happens when external hooks behave maliciously or consume bounded gas during terminal cleanup:

  • Lapsed BOUNTY / BENCHMARK Decision Deadlock (F-05): When multiple workers submit entries to a BOUNTY or BENCHMARK pool and the requester disappears without selecting winners, single-claimant settleLapsedReview reverts because there is no singular active claimant, while expireTask reverts because valid unreviewed submissions exist—stranding escrowed rewards indefinitely unless deterministic pro-rata or refund-with-compensation fallback rules are implemented.
  • 1,000,000-Gas Stipend Exhaustion & Arbitrary Hook Injection (F-06): Allowing unverified user-supplied contracts inside hookConfig.contracts enabled an active Base Mainnet exploit across 46+ rotated contracts where checkSubmit(bytes32,address,string) (selector 0xb65065f4) returns false while onCancel / onExpire burn the full 1,000,000 gas stipend in a tight JUMPDEST loop whenever worker collateral (stakeBps > 0) is attached.

To remediate arbitrary hook traps at the protocol layer without breaking composable verification for zero-stake bounties, we authored and proposed a two-part Solidity guard inside HookRouter (PR #22):

interface IHookAllowlist {
    function isApprovedHook(address hook, bytes32 codehash) external view returns (bool);
}

function _validateTaskHooks(
    TaskTerms calldata terms,
    address[] calldata hooks,
    IHookAllowlist allowlist
) internal view {
    bool hasWorkerAtRisk = terms.stakeRequired || terms.stakeBps > 0 || !terms.releaseAllowed;
    for (uint256 i = 0; i < hooks.length; ++i) {
        address h = hooks[i];
        bytes32 hash = h.codehash;
        if (hash == bytes32(0) || hash == EMPTY_CODEHASH) revert HookNotAContract(h);
        if (hasWorkerAtRisk && !allowlist.isApprovedHook(h, hash)) {
            revert UnapprovedHookOnStakedTask(h, hash);
        }
    }
}

Notice why checking both address hook and h.codehash (EXTCODEHASH) is mandatory: an attacker who deploys a hook behind a minimal transparent proxy or SELFDESTRUCT/CREATE2 metamorphosis pattern could otherwise swap benign logic for revert-trap bytecode after allowlisting. Binding approval to the immutable runtime codehash—paired with try/catch gas-bounded post-settlement notifications that never revert core principal recovery—eliminates stake confiscation by construction.

"In an EIP-2535 Diamond, storage is shared across every facet, which means every facet inherits the weakest invariant of its neighbors. Treat commitment hashes, project expiry ceilings, and external hook codehashes as non-bypassable storage-layer invariants rather than entry-point suggestions."