Перейти к содержимому
Проверенный контрактТочноеMIT

ValidationModuleVoting

Адрес0x04af6f94c7f74933beee4f6d39cec4b2d9f7a42a
Баланс

0 ETH

 

Транзакций

2

 

Компилятор

solc 0.8.25

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.25+commit.b61c2a91
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Через IR
да
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 171 778
Транзакция создания
0x60a493db51…e33f838f11

contracts/v2/implementation/ValidationModuleVoting.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IJobRegistry} from "../interfaces/IJobRegistry.sol";
import {IJobRegistryTax} from "../interfaces/IJobRegistryTax.sol";
import {IStakeManager} from "../interfaces/IStakeManager.sol";
import {IReputationEngine} from "../interfaces/IReputationEngine.sol";
import {IValidationModule} from "../interfaces/IValidationModule.sol";
import {IIdentityRegistry} from "../interfaces/IIdentityRegistry.sol";
import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";
import {IRandaoCoordinator} from "../interfaces/IRandaoCoordinator.sol";
import {TaxAcknowledgement} from "../libraries/TaxAcknowledgement.sol";

import "./ValidationModuleBase.sol";
import "./FixedDelegate.sol";

/// @notice Fixed voting implementation for ValidationModule. Deploy via the modular deployment helper.
contract ValidationModuleVoting is ValidationModuleBase, DelegateOnly {
    constructor() ValidationModuleBase() {}

    function moduleId() external pure returns (bytes32) {
        return keccak256("ValidationModuleVoting:v1");
    }

    /// @notice Trigger a circuit-breaker style failover for an in-flight validation round.
    /// @param jobId Identifier of the job whose validation flow is being adjusted.
    /// @param action Failover action to execute (reveal extension or dispute escalation).
    /// @param extension Additional seconds to append to the reveal window when extending.
    /// @param reason Human-readable context for observability purposes.
    function triggerFailover(
        uint256 jobId,
        IValidationModule.FailoverAction action,
        uint64 extension,
        string calldata reason
    ) external override onlyDelegateCall {
        return _entry_triggerFailover(jobId, action, extension, reason);
    }

    /// @notice Commit a validation hash for a job.
    function commitValidation(uint256 jobId, bytes32 commitHash, string calldata subdomain, bytes32[] calldata proof)
        public
        override
        onlyDelegateCall
    {
        return _entry_commitValidation(jobId, commitHash, subdomain, proof);
    }

    /// @notice Reveal a previously committed validation vote.
    function revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) public override onlyDelegateCall {
        return _entry_revealValidation(jobId, approve, burnTxHash, salt, subdomain, proof);
    }

    /// @notice Backwards-compatible wrapper for commitValidation.
    function commitVote(uint256 jobId, bytes32 commitHash, string calldata subdomain, bytes32[] calldata proof)
        external
        override
        onlyDelegateCall
    {
        return _entry_commitVote(jobId, commitHash, subdomain, proof);
    }

    /// @notice Backwards-compatible wrapper for revealValidation.
    function revealVote(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external override onlyDelegateCall {
        return _entry_revealVote(jobId, approve, burnTxHash, salt, subdomain, proof);
    }

    /// @notice Tally revealed votes, apply slashing/rewards, and push result to JobRegistry.
    function finalize(uint256 jobId) external override onlyDelegateCall returns (bool success) {
        return _entry_finalize(jobId);
    }

    function finalizeValidation(uint256 jobId) external override onlyDelegateCall returns (bool success) {
        return _entry_finalizeValidation(jobId);
    }

    /// @notice Force finalize a job after the reveal deadline plus grace period.
    /// @dev If quorum was not met, no result is recorded and the employer/agent are refunded.
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function forceFinalize(uint256 jobId) external override onlyDelegateCall returns (bool success) {
        return _entry_forceFinalize(jobId);
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

@openzeppelin/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

@openzeppelin/contracts/utils/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/utils/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

contracts/v2/implementation/FixedDelegate.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

interface IFixedImplementation {
    function moduleId() external pure returns (bytes32);
}

/// @dev Contains no storage. Controllers keep their implementation addresses immutable.
abstract contract FixedDelegate {
    error InvalidImplementation(address implementation, bytes32 expectedId);

    function _checkedImplementation(address implementation, bytes32 expectedId) internal view returns (address) {
        if (implementation.code.length == 0) {
            revert InvalidImplementation(implementation, expectedId);
        }
        if (IFixedImplementation(implementation).moduleId() != expectedId) {
            revert InvalidImplementation(implementation, expectedId);
        }
        return implementation;
    }

    function _delegate(address implementation) internal {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, 0, calldatasize())
            let success := delegatecall(gas(), implementation, ptr, calldatasize(), 0, 0)
            returndatacopy(ptr, 0, returndatasize())
            switch success
            case 0 { revert(ptr, returndatasize()) }
            default { return(ptr, returndatasize()) }
        }
    }
}

/// @dev Prevents direct calls to implementation entry points; no storage slot is consumed.
abstract contract DelegateOnly {
    address private immutable _self = address(this);
    error DirectImplementationCall();

    function _checkDelegateCall() internal view {
        if (address(this) == _self) revert DirectImplementationCall();
    }

    modifier onlyDelegateCall() {
        _checkDelegateCall();
        _;
    }
}

contracts/v2/implementation/ValidationModuleBase.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IJobRegistry} from "../interfaces/IJobRegistry.sol";
import {IJobRegistryTax} from "../interfaces/IJobRegistryTax.sol";
import {IStakeManager} from "../interfaces/IStakeManager.sol";
import {IReputationEngine} from "../interfaces/IReputationEngine.sol";
import {IValidationModule} from "../interfaces/IValidationModule.sol";
import {IIdentityRegistry} from "../interfaces/IIdentityRegistry.sol";
import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";
import {IRandaoCoordinator} from "../interfaces/IRandaoCoordinator.sol";
import {TaxAcknowledgement} from "../libraries/TaxAcknowledgement.sol";

error InvalidJobRegistry();
error InvalidStakeManager();
error InvalidValidatorBounds();
error InvalidWindows();
error PoolLimitExceeded();
error ZeroValidatorAddress();
error ZeroIdentityRegistry();
error InvalidIdentityRegistry();
error InvalidSampleSize();
error SampleSizeTooSmall();
error InvalidApprovalThreshold();
error InvalidSlashingPercentage();
error InvalidArrayLength();
error InvalidCommitWindow();
error InvalidRevealWindow();
error InvalidPercentage();
error InvalidApprovals();
error ValidatorsAlreadySelected();
error InsufficientValidators();
error StakeManagerNotSet();
error OnlyJobRegistry();
error JobNotSubmitted();
error ValidatorPoolTooSmall();
error BlacklistedValidator();
error NotValidator();
error UnauthorizedValidator();
error NoStake();
error AlreadyCommitted();
error CommitPhaseActive();
error RevealPhaseClosed();
error CommitPhaseClosed();
error CommitMissing();
error AlreadyRevealed();
error InvalidReveal();
error InvalidBurnReceipt();
error BurnEvidenceIncomplete();
error AlreadyTallied();
error RevealPending();
error UnauthorizedCaller();
error NotOwnerOrPauserManager();
error ValidatorBanned();
error InvalidPenalty();
error InvalidForceFinalizeGrace();
error InvalidFailoverAction();
error RevealExtensionRequired();
error FailoverEscalated();
error NoActiveRound();

/// @title ValidationModule
/// @notice Handles validator selection and commit–reveal voting for jobs.
/// @dev Holds no ether and keeps the owner and contract tax neutral; only
///      participating validators and job parties bear tax obligations. Validator
///      selection mixes entropy from multiple participants: callers may
///      contribute random values which are XORed together and later combined
///      with recent block data to mitigate miner bias.
abstract contract ValidationModuleBase is IValidationModule, Ownable, TaxAcknowledgement, Pausable, ReentrancyGuard {
    /// @notice Module version for compatibility checks.
    uint256 public constant version = 2;

    /// @notice Domain separator used for typed commit hashes.
    // Appended storage field below preserves all existing storage offsets.

    IJobRegistry public jobRegistry;
    IStakeManager public stakeManager;
    IReputationEngine public reputationEngine;
    IIdentityRegistry public identityRegistry;
    IRandaoCoordinator public randaoCoordinator;
    address public pauser;
    address public pauserManager;

    // timing configuration
    uint256 public commitWindow;
    uint256 public revealWindow;

    // validator bounds per job
    uint256 public minValidators;
    uint256 public maxValidators;
    uint256 public validatorsPerJob;

    /// @notice Hard limit on the number of validators any single job may use.
    uint256 public maxValidatorsPerJob = 100;

    uint256 public constant DEFAULT_COMMIT_WINDOW = 30 minutes;
    uint256 public constant DEFAULT_REVEAL_WINDOW = 30 minutes;
    uint256 public constant DEFAULT_MIN_VALIDATORS = 3;
    uint256 public constant DEFAULT_MAX_VALIDATORS = 5;
    uint256 public constant DEFAULT_APPROVAL_THRESHOLD = 66;
    uint256 public constant DEFAULT_REVEAL_QUORUM_PCT = 67;
    uint256 public constant DEFAULT_FORCE_FINALIZE_GRACE = 1 hours;
    uint256 public forceFinalizeGrace = DEFAULT_FORCE_FINALIZE_GRACE;

    // slashing percentage applied to validator stake for incorrect votes
    uint256 public validatorSlashingPercentage = 50;
    // percentage of total stake required for approval
    uint256 public approvalThreshold = DEFAULT_APPROVAL_THRESHOLD;
    // absolute number of validator approvals required
    uint256 public requiredValidatorApprovals;

    /// @notice Whether the approval count should auto-track the configured
    ///         supermajority percentage.
    bool public autoApprovalTarget = true;

    /// @notice Minimum percentage of the committee that must reveal for quorum.
    uint256 public revealQuorumPct = DEFAULT_REVEAL_QUORUM_PCT;

    /// @notice Absolute floor on the number of reveals required for quorum.
    uint256 public minRevealValidators = DEFAULT_MIN_VALIDATORS;

    // pool of validators
    address[] public validatorPool;
    // maximum number of pool entries to sample on-chain
    uint256 public validatorPoolSampleSize = 100;
    // hard cap on validator pool size; default chosen to keep on-chain
    // iteration within practical gas limits while allowing governance to
    // raise or lower it via the existing setter.
    uint256 public maxValidatorPoolSize = 1000;

    /// @notice Current strategy used for validator sampling.
    IValidationModule.SelectionStrategy public selectionStrategy;

    /// @notice Starting index for the rotating window strategy.
    uint256 public validatorPoolRotation;

    // optional override for validators without ENS identity
    mapping(address => string) public validatorSubdomains;

    // cache successful validator authorizations
    mapping(address => bool) public validatorAuthCache;
    mapping(address => uint256) public validatorAuthExpiry;
    mapping(address => uint256) public validatorAuthVersion;
    uint256 public validatorAuthCacheVersion;
    uint256 public validatorAuthCacheDuration;

    struct Round {
        address[] validators;
        address[] participants;
        uint256 commitDeadline;
        uint256 revealDeadline;
        uint256 approvals;
        uint256 rejections;
        uint256 revealedCount;
        bool tallied;
        uint256 committeeSize;
        uint64 earlyFinalizeEligibleAt;
        bool earlyFinalized;
    }

    struct FailoverState {
        IValidationModule.FailoverAction lastAction;
        uint64 extensions;
        uint64 lastExtendedTo;
        uint64 lastTriggeredAt;
        bool escalated;
    }

    mapping(uint256 => Round) public rounds;
    mapping(uint256 => FailoverState) public failoverStates;
    mapping(uint256 => mapping(address => mapping(uint256 => bytes32))) public commitments;
    mapping(uint256 => mapping(address => bool)) public revealed;
    mapping(uint256 => mapping(address => bool)) public votes;
    mapping(uint256 => mapping(address => uint256)) public validatorStakes;
    mapping(uint256 => mapping(address => uint256)) public validatorStakeLocks;
    mapping(uint256 => mapping(address => bool)) internal _validatorLookup;
    mapping(uint256 => uint256) public jobNonce;
    // Aggregated entropy contributed by job parties prior to final selection.
    // Each call to `selectValidators` while the target block has not yet been
    // mined XORs a caller-supplied value (mixed with the caller address) into
    // this pool.
    mapping(uint256 => uint256) public pendingEntropy;
    // Block number whose hash will be used to finalize committee selection.
    mapping(uint256 => uint256) public selectionBlock;

    // Track unique entropy contributors for each job and round
    mapping(uint256 => uint256) public entropyContributorCount;
    mapping(uint256 => uint256) public entropyRound;
    mapping(uint256 => mapping(uint256 => mapping(address => bool))) internal entropyContributed;
    uint256 public constant MIN_ENTROPY_CONTRIBUTORS = 2;

    /// @notice Selection seed captured for each job to prevent post-selection manipulation.
    mapping(uint256 => bytes32) public selectionSeeds;

    /// @notice Basis points slashed from validator stake when they fail to reveal.
    uint256 public nonRevealPenaltyBps = 50; // 0.5%

    /// @notice Number of blocks a validator is banned from new committees after failing to reveal.
    uint256 public nonRevealBanBlocks = 7_200; // ~1 day assuming 12s blocks

    /// @notice Cool-off delay before an early finalize may be triggered once quorum is met.
    uint256 public earlyFinalizeDelay = 5 minutes;

    /// @notice Block number until which a validator is banned from committee selection.
    mapping(address => uint256) public validatorBanUntil;

    event ValidatorsUpdated(address[] validators);
    event ReputationEngineUpdated(address engine);
    event TimingUpdated(uint256 commitWindow, uint256 revealWindow);
    event ValidatorBoundsUpdated(uint256 minValidators, uint256 maxValidators);
    event ValidatorSlashingPctUpdated(uint256 pct);
    event ApprovalThresholdUpdated(uint256 pct);
    event ValidatorsPerJobUpdated(uint256 count);
    event CommitWindowUpdated(uint256 window);
    event RevealWindowUpdated(uint256 window);
    event RequiredValidatorApprovalsUpdated(uint256 count);
    event JobRegistryUpdated(address registry);
    event StakeManagerUpdated(address manager);
    event ModulesUpdated(address indexed jobRegistry, address indexed stakeManager);
    event IdentityRegistryUpdated(address registry);
    event JobNonceReset(uint256 indexed jobId);
    event ValidatorPoolSampleSizeUpdated(uint256 size);
    event MaxValidatorPoolSizeUpdated(uint256 size);
    event ValidatorAuthCacheDurationUpdated(uint256 duration);
    event RevealQuorumUpdated(uint256 pct, uint256 minValidators);
    event ValidatorAuthCacheVersionBumped(uint256 version);
    event SelectionReset(uint256 indexed jobId);
    event PauserUpdated(address indexed pauser);
    event PauserManagerUpdated(address indexed pauserManager);
    event NonRevealPenaltyUpdated(uint256 penaltyBps, uint256 banBlocks);
    event EarlyFinalizeDelayUpdated(uint256 delay);
    event ForceFinalizeGraceUpdated(uint256 grace);
    event AutoApprovalTargetUpdated(bool enabled);
    event ValidatorBanApplied(address indexed validator, uint256 untilBlock);
    event SelectionSeedRecorded(uint256 indexed jobId, bytes32 seed);
    /// @notice Emitted when a validator's ENS identity is verified.
    event ValidatorIdentityVerified(
        address indexed validator, bytes32 indexed node, string label, bool viaWrapper, bool viaMerkle
    );

    modifier onlyOwnerOrPauser() {
        require(msg.sender == owner() || msg.sender == pauser, "owner or pauser only");
        _;
    }

    function _entry_setPauser(address _pauser) internal {
        if (msg.sender != owner() && msg.sender != pauserManager) {
            revert NotOwnerOrPauserManager();
        }
        pauser = _pauser;
        emit PauserUpdated(_pauser);
    }

    function _entry_setPauserManager(address manager) internal onlyOwner {
        pauserManager = manager;
        emit PauserManagerUpdated(manager);
    }

    /// @notice Update non-reveal penalty parameters.
    /// @param penaltyBps Slash applied in basis points of validator stake.
    /// @param banBlocks Number of blocks a validator is banned from new committees.
    function _entry_setNonRevealPenalty(uint256 penaltyBps, uint256 banBlocks) internal onlyOwner {
        if (penaltyBps > 1_000) revert InvalidPenalty();
        nonRevealPenaltyBps = penaltyBps;
        nonRevealBanBlocks = banBlocks;
        emit NonRevealPenaltyUpdated(penaltyBps, banBlocks);
    }

    /// @notice Update the reveal quorum requirements.
    /// @param pct Percentage of the committee that must reveal (0-100).
    /// @param minValidators_ Absolute minimum number of reveals required.
    function _entry_setRevealQuorum(uint256 pct, uint256 minValidators_) internal onlyOwner {
        if (pct > 100) revert InvalidPercentage();
        if (minValidators_ == 0) revert InvalidValidatorBounds();
        revealQuorumPct = pct;
        minRevealValidators = minValidators_;
        emit RevealQuorumUpdated(pct, minValidators_);
    }

    /// @notice Update the cool-off delay before early finalization is permitted.
    /// @param delay Seconds to wait after quorum is met before allowing finalize.
    function _entry_setEarlyFinalizeDelay(uint256 delay) internal onlyOwner {
        earlyFinalizeDelay = delay;
        emit EarlyFinalizeDelayUpdated(delay);
    }

    /// @notice Update the grace period before force finalize can be triggered.
    /// @param grace Additional seconds allowed after the reveal window closes.
    function _entry_setForceFinalizeGrace(uint256 grace) internal onlyOwner {
        if (grace == 0) revert InvalidForceFinalizeGrace();
        forceFinalizeGrace = grace;
        emit ForceFinalizeGraceUpdated(grace);
    }

    /// @notice Trigger a circuit-breaker style failover for an in-flight validation round.
    /// @param jobId Identifier of the job whose validation flow is being adjusted.
    /// @param action Failover action to execute (reveal extension or dispute escalation).
    /// @param extension Additional seconds to append to the reveal window when extending.
    /// @param reason Human-readable context for observability purposes.
    function _entry_triggerFailover(
        uint256 jobId,
        IValidationModule.FailoverAction action,
        uint64 extension,
        string calldata reason
    ) internal onlyOwner whenNotPaused {
        if (action == IValidationModule.FailoverAction.None) {
            revert InvalidFailoverAction();
        }
        FailoverState storage state = failoverStates[jobId];
        string memory rationale = bytes(reason).length == 0 ? "validation-failover" : reason;

        if (action == IValidationModule.FailoverAction.EscalateDispute) {
            if (state.escalated) revert FailoverEscalated();
        }

        Round storage r = rounds[jobId];
        if (r.commitDeadline == 0) revert NoActiveRound();
        if (r.tallied) revert AlreadyTallied();

        if (action == IValidationModule.FailoverAction.ExtendReveal) {
            if (extension == 0) revert RevealExtensionRequired();
            uint256 newDeadline = r.revealDeadline + extension;
            r.revealDeadline = newDeadline;
            state.lastAction = IValidationModule.FailoverAction.ExtendReveal;
            state.extensions += 1;
            state.lastExtendedTo = uint64(newDeadline);
            state.lastTriggeredAt = uint64(block.timestamp);
            emit ValidationFailover(jobId, action, newDeadline, rationale);
            return;
        }

        if (action == IValidationModule.FailoverAction.EscalateDispute) {
            state.escalated = true;
            state.lastAction = IValidationModule.FailoverAction.EscalateDispute;
            state.lastTriggeredAt = uint64(block.timestamp);
            uint256 deadline = r.revealDeadline;
            jobRegistry.escalateToDispute(jobId, rationale);
            _cleanup(jobId);
            emit ValidationFailover(jobId, action, deadline, rationale);
            return;
        }

        revert InvalidFailoverAction();
    }
    event ValidatorPoolRotationUpdated(uint256 newRotation);
    event RandaoCoordinatorUpdated(address coordinator);
    event MaxValidatorsPerJobUpdated(uint256 maxValidators);
    /// @notice Emitted when an additional validator is added or removed.
    /// @param validator Address being updated.
    /// @param allowed True if the validator is whitelisted, false if removed.

    /// @dev Shared storage initialization.
    constructor() Ownable(msg.sender) {}

    // ---------------------------------------------------------------------
    // Owner setters (use Etherscan's "Write Contract" tab)
    // ---------------------------------------------------------------------

    /// @notice Update the list of eligible validators.
    /// @param newPool Addresses of validators.
    function _entry_setValidatorPool(address[] calldata newPool) internal onlyOwner {
        if (newPool.length > maxValidatorPoolSize) revert PoolLimitExceeded();
        for (uint256 i = 0; i < newPool.length; i++) {
            if (newPool[i] == address(0)) revert ZeroValidatorAddress();
        }
        validatorPool = newPool;
        _entry_bumpValidatorAuthCacheVersion();
        emit ValidatorsUpdated(newPool);
    }

    /// @notice Update the reputation engine used for validator feedback.
    function _entry_setReputationEngine(IReputationEngine engine) internal onlyOwner {
        reputationEngine = engine;
        emit ReputationEngineUpdated(address(engine));
    }

    /// @notice Update the JobRegistry reference.
    function _entry_setJobRegistry(IJobRegistry registry) internal onlyOwner {
        if (address(registry) == address(0) || registry.version() != 2) {
            revert InvalidJobRegistry();
        }
        jobRegistry = registry;
        emit JobRegistryUpdated(address(registry));
        emit ModulesUpdated(address(registry), address(stakeManager));
    }

    /// @notice Update the StakeManager reference.
    function _entry_setStakeManager(IStakeManager manager) internal onlyOwner {
        if (address(manager) == address(0) || manager.version() != 2) {
            revert InvalidStakeManager();
        }
        stakeManager = manager;
        emit StakeManagerUpdated(address(manager));
        emit ModulesUpdated(address(jobRegistry), address(manager));
    }

    /// @notice Update the identity registry used for validator verification.
    function _entry_setIdentityRegistry(IIdentityRegistry registry) internal onlyOwner {
        if (address(registry) == address(0)) revert ZeroIdentityRegistry();
        if (registry.version() != 2) revert InvalidIdentityRegistry();
        identityRegistry = registry;
        emit IdentityRegistryUpdated(address(registry));
    }

    /// @notice Set the Randao coordinator used for randomness.
    /// @param coordinator Address of the RandaoCoordinator contract.
    function _entry_setRandaoCoordinator(IRandaoCoordinator coordinator) internal onlyOwner {
        randaoCoordinator = coordinator;
        emit RandaoCoordinatorUpdated(address(coordinator));
    }

    /// @notice Pause validation operations
    function _entry_pause() internal onlyOwnerOrPauser {
        _pause();
    }

    /// @notice Resume validation operations
    function _entry_unpause() internal onlyOwnerOrPauser {
        _unpause();
    }

    /// @notice Update the maximum number of pool entries sampled during selection.
    /// @param size Maximum number of validators examined on-chain.
    function _entry_setValidatorPoolSampleSize(uint256 size) internal onlyOwner {
        if (size == 0) revert InvalidSampleSize();
        if (size > maxValidatorPoolSize) revert PoolLimitExceeded();
        if (size < validatorsPerJob) revert SampleSizeTooSmall();
        validatorPoolSampleSize = size;
        emit ValidatorPoolSampleSizeUpdated(size);
    }

    /// @notice Update the maximum allowable size of the validator pool.
    /// @param size Maximum number of validators permitted in the pool.
    function _entry_setMaxValidatorPoolSize(uint256 size) internal onlyOwner {
        if (size == 0) revert InvalidSampleSize();
        if (size < validatorsPerJob) revert InvalidValidatorBounds();
        if (size < validatorPoolSampleSize) revert InvalidSampleSize();
        maxValidatorPoolSize = size;
        emit MaxValidatorPoolSizeUpdated(size);
    }

    /// @notice Update the maximum number of validators allowed per job.
    /// @param max Maximum validators permitted for any job.
    function _entry_setMaxValidatorsPerJob(uint256 max) internal onlyOwner {
        if (max < minValidators) revert InvalidValidatorBounds();
        maxValidatorsPerJob = max;
        if (validatorsPerJob > max) {
            validatorsPerJob = max;
            emit ValidatorsPerJobUpdated(max);
        }
        if (maxValidators > max) {
            maxValidators = max;
            emit ValidatorBoundsUpdated(minValidators, max);
        }
        emit MaxValidatorsPerJobUpdated(max);
    }

    /// @notice Configure the validator sampling strategy.
    /// @param strategy Sampling algorithm to employ when selecting validators.
    function _entry_setSelectionStrategy(IValidationModule.SelectionStrategy strategy) internal onlyOwner {
        selectionStrategy = strategy;
        emit SelectionStrategyUpdated(strategy);
    }

    /// @notice Update the duration for cached validator authorizations.
    /// @param duration Seconds an authorization remains valid in cache.
    function _entry_setValidatorAuthCacheDuration(uint256 duration) internal onlyOwner {
        validatorAuthCacheDuration = duration;
        emit ValidatorAuthCacheDurationUpdated(duration);
    }

    /// @notice Increment the validator authorization cache version,
    /// invalidating all existing cache entries.
    function _entry_bumpValidatorAuthCacheVersion() internal onlyOwner {
        unchecked {
            ++validatorAuthCacheVersion;
        }
        emit ValidatorAuthCacheVersionBumped(validatorAuthCacheVersion);
    }

    /// @notice Batch update core validation parameters.
    /// @param committeeSize Number of validators selected per job.
    /// @param commitDur Duration of the commit phase in seconds.
    /// @param revealDur Duration of the reveal phase in seconds.
    /// @param approvalPct Percentage of stake required for approval.
    /// @param slashPct Percentage of stake slashed for incorrect votes.
    function _entry_setParameters(
        uint256 committeeSize,
        uint256 commitDur,
        uint256 revealDur,
        uint256 approvalPct,
        uint256 slashPct
    ) internal onlyOwner {
        _entry_setParameters(committeeSize, commitDur, revealDur);
        if (approvalPct == 0 || approvalPct > 100) revert InvalidApprovalThreshold();
        if (slashPct > 100) revert InvalidSlashingPercentage();
        approvalThreshold = approvalPct;
        validatorSlashingPercentage = slashPct;
        emit ApprovalThresholdUpdated(approvalPct);
        emit ValidatorSlashingPctUpdated(slashPct);
        emit ParametersUpdated(committeeSize, commitDur, revealDur, approvalPct, slashPct);
    }

    /// @notice Update validator count and phase windows.
    /// @param validatorCount Number of validators per job.
    /// @param commitDur Duration of the commit phase in seconds.
    /// @param revealDur Duration of the reveal phase in seconds.
    function _entry_setParameters(uint256 validatorCount, uint256 commitDur, uint256 revealDur) internal onlyOwner {
        if (validatorCount < 3 || validatorCount > maxValidatorsPerJob) {
            revert InvalidValidatorBounds();
        }
        if (commitDur == 0 || revealDur == 0) revert InvalidWindows();
        validatorsPerJob = validatorCount;
        minValidators = validatorCount;
        maxValidators = validatorCount;
        commitWindow = commitDur;
        revealWindow = revealDur;
        _syncRequiredValidatorApprovals();
        emit ValidatorBoundsUpdated(validatorCount, validatorCount);
        emit ValidatorsPerJobUpdated(validatorCount);
        emit TimingUpdated(commitDur, revealDur);
    }

    /// @notice Return validators selected for a job
    /// @param jobId Identifier of the job
    /// @return validators_ Array of validator addresses
    function validators(uint256 jobId) external view override returns (address[] memory validators_) {
        Round storage r = rounds[jobId];
        validators_ = r.tallied ? r.participants : r.validators;
    }

    /// @notice Retrieve the reveal deadline for a job
    /// @param jobId Identifier of the job
    /// @return deadline Timestamp when the reveal phase ends
    function revealDeadline(uint256 jobId) external view returns (uint256 deadline) {
        deadline = rounds[jobId].revealDeadline;
    }

    /// @notice Map validators to their ENS subdomains for selection-time checks.
    /// @param accounts Validator addresses to configure.
    /// @param subdomains ENS labels owned by each validator.
    function _entry_setValidatorSubdomains(address[] calldata accounts, string[] calldata subdomains)
        internal
        onlyOwner
    {
        if (accounts.length != subdomains.length) revert InvalidArrayLength();
        for (uint256 i; i < accounts.length;) {
            validatorSubdomains[accounts[i]] = subdomains[i];
            emit ValidatorSubdomainUpdated(accounts[i], subdomains[i]);
            unchecked {
                ++i;
            }
        }
    }

    /// @notice Map the caller to an ENS subdomain for selection checks.
    /// @param subdomain ENS label owned by the caller.
    function _entry_setMySubdomain(string calldata subdomain) internal {
        validatorSubdomains[msg.sender] = subdomain;
        emit ValidatorSubdomainUpdated(msg.sender, subdomain);
    }

    /// @notice Update the commit and reveal windows.
    function _entry_setCommitRevealWindows(uint256 commitDur, uint256 revealDur) internal onlyOwner {
        if (commitDur == 0 || revealDur == 0) revert InvalidWindows();
        commitWindow = commitDur;
        revealWindow = revealDur;
        emit TimingUpdated(commitDur, revealDur);
        emit CommitWindowUpdated(commitDur);
        emit RevealWindowUpdated(revealDur);
    }

    /// @notice Convenience wrapper matching original API naming.
    /// @dev Alias for {setCommitRevealWindows}.
    function _entry_setTiming(uint256 commitDur, uint256 revealDur) internal onlyOwner {
        if (commitDur == 0 || revealDur == 0) revert InvalidWindows();
        commitWindow = commitDur;
        revealWindow = revealDur;
        emit TimingUpdated(commitDur, revealDur);
        emit CommitWindowUpdated(commitDur);
        emit RevealWindowUpdated(revealDur);
    }

    /// @notice Set minimum and maximum validators per round.
    function _entry_setValidatorBounds(uint256 minVals, uint256 maxVals) internal onlyOwner {
        if (minVals < 3 || maxVals < minVals || maxVals > maxValidatorsPerJob) {
            revert InvalidValidatorBounds();
        }
        minValidators = minVals;
        maxValidators = maxVals;
        if (minVals == maxVals) {
            validatorsPerJob = minVals;
            emit ValidatorsPerJobUpdated(minVals);
        } else if (validatorsPerJob < minVals) {
            validatorsPerJob = minVals;
            emit ValidatorsPerJobUpdated(minVals);
        } else if (validatorsPerJob > maxVals) {
            validatorsPerJob = maxVals;
            emit ValidatorsPerJobUpdated(maxVals);
        }
        _syncRequiredValidatorApprovals();
        emit ValidatorBoundsUpdated(minVals, maxVals);
    }

    /// @notice Set number of validators selected per job.
    function _entry_setValidatorsPerJob(uint256 count) internal onlyOwner {
        if (count < 3 || count < minValidators || count > maxValidators || count > maxValidatorsPerJob) {
            revert InvalidValidatorBounds();
        }
        validatorsPerJob = count;
        _syncRequiredValidatorApprovals();
        emit ValidatorsPerJobUpdated(count);
    }

    /// @dev Clamp required approvals to current committee size.
    function _clampRequiredValidatorApprovals() internal {
        if (requiredValidatorApprovals > validatorsPerJob) {
            requiredValidatorApprovals = validatorsPerJob;
            emit RequiredValidatorApprovalsUpdated(validatorsPerJob);
        }
    }

    function _approvalTarget(uint256 committee, uint256 pct) internal pure returns (uint256) {
        if (committee == 0 || pct == 0) {
            return 0;
        }
        uint256 numerator = committee * pct;
        uint256 target = numerator / 100;
        if (numerator % 100 != 0) {
            unchecked {
                ++target;
            }
        }
        return target;
    }

    function _syncRequiredValidatorApprovals() internal {
        if (autoApprovalTarget) {
            uint256 target = _approvalTarget(validatorsPerJob, approvalThreshold);
            if (requiredValidatorApprovals != target) {
                requiredValidatorApprovals = target;
                emit RequiredValidatorApprovalsUpdated(target);
            }
        } else {
            _clampRequiredValidatorApprovals();
        }
    }

    /// @notice Individually update commit window duration.
    function _entry_setCommitWindow(uint256 commitDur) internal onlyOwner {
        if (commitDur == 0) revert InvalidCommitWindow();
        commitWindow = commitDur;
        emit TimingUpdated(commitDur, revealWindow);
        emit CommitWindowUpdated(commitDur);
    }

    /// @notice Individually update reveal window duration.
    function _entry_setRevealWindow(uint256 revealDur) internal onlyOwner {
        if (revealDur == 0) revert InvalidRevealWindow();
        revealWindow = revealDur;
        emit TimingUpdated(commitWindow, revealDur);
        emit RevealWindowUpdated(revealDur);
    }

    /// @notice Individually update minimum validators.
    function _entry_setMinValidators(uint256 minVals) internal onlyOwner {
        if (minVals == 0 || minVals > maxValidators) revert InvalidValidatorBounds();
        minValidators = minVals;
        emit ValidatorBoundsUpdated(minVals, maxValidators);
    }

    /// @notice Individually update maximum validators.
    function _entry_setMaxValidators(uint256 maxVals) internal onlyOwner {
        if (maxVals < minValidators || maxVals == 0) revert InvalidValidatorBounds();
        maxValidators = maxVals;
        emit ValidatorBoundsUpdated(minValidators, maxVals);
    }

    function _entry_setValidatorSlashingPct(uint256 pct) internal onlyOwner {
        if (pct > 100) revert InvalidPercentage();
        validatorSlashingPercentage = pct;
        emit ValidatorSlashingPctUpdated(pct);
    }

    /// @notice Update approval threshold percentage.
    function _entry_setApprovalThreshold(uint256 pct) internal onlyOwner {
        if (pct == 0 || pct > 100) revert InvalidPercentage();
        approvalThreshold = pct;
        emit ApprovalThresholdUpdated(pct);
        _syncRequiredValidatorApprovals();
    }

    /// @notice Set the required number of validator approvals.
    function _entry_setRequiredValidatorApprovals(uint256 count) internal onlyOwner {
        if (count == 0 || count > maxValidators) revert InvalidApprovals();
        if (count > validatorsPerJob) count = validatorsPerJob;
        if (autoApprovalTarget) {
            autoApprovalTarget = false;
            emit AutoApprovalTargetUpdated(false);
        }
        requiredValidatorApprovals = count;
        emit RequiredValidatorApprovalsUpdated(count);
    }

    /// @notice Toggle automatic supermajority targeting for required approvals.
    /// @param enabled When true, the approval count tracks the configured threshold.
    function _entry_setAutoApprovalTarget(bool enabled) internal onlyOwner {
        if (autoApprovalTarget == enabled) {
            return;
        }
        autoApprovalTarget = enabled;
        emit AutoApprovalTargetUpdated(enabled);
        if (enabled) {
            _syncRequiredValidatorApprovals();
        } else {
            _clampRequiredValidatorApprovals();
        }
    }

    /// @dev Internal implementation of IValidationModule.
    /// @dev Randomness draws from aggregated caller-provided entropy and on-chain data.
    ///      Callers may submit additional entropy prior to finalization; each
    ///      contribution is XORed into an entropy pool. The pool is then mixed with
    ///      a future blockhash and `block.prevrandao` (or historical hashes and
    ///      `msg.sender` as fallback) to avoid external randomness providers and
    ///      minimize miner influence.
    function _entry_selectValidators(uint256 jobId, uint256 entropy)
        internal
        whenNotPaused
        returns (address[] memory selected)
    {
        Round storage r = rounds[jobId];
        IJobRegistry registry = jobRegistry;
        address registryAddr = address(registry);
        if (registryAddr != address(0)) {
            (bool burnRequired, bool burnSatisfied) = registry.burnEvidenceStatus(jobId);
            if (burnRequired && !burnSatisfied) revert BurnEvidenceIncomplete();
        }
        // Ensure validators are only chosen once per round to prevent
        // re-selection or commit replay.
        if (r.validators.length != 0) revert ValidatorsAlreadySelected();
        // Identity registry must be configured so candidates can be
        // verified on-chain via ENS ownership.
        if (address(identityRegistry) == address(0)) revert ZeroIdentityRegistry();

        // Reset any failover history when starting a fresh round.
        if (selectionBlock[jobId] == 0 && r.commitDeadline == 0) {
            delete failoverStates[jobId];
        }
        // If selection has not been initiated, seed the entropy pool and set the
        // target block whose hash will anchor the final randomness.
        if (selectionBlock[jobId] == 0) {
            pendingEntropy[jobId] = uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
            selectionBlock[jobId] = block.number + 1;
            entropyRound[jobId] += 1;
            entropyContributorCount[jobId] = 1;
            entropyContributed[jobId][entropyRound[jobId]][msg.sender] = true;
            return selected;
        }

        // Before the target block is mined, allow additional parties to
        // contribute entropy. Each contribution is mixed into the pool via XOR.
        uint256 round = entropyRound[jobId];
        uint256 targetBlock = selectionBlock[jobId];

        if (block.number <= targetBlock) {
            pendingEntropy[jobId] ^= uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
            if (!entropyContributed[jobId][round][msg.sender]) {
                entropyContributed[jobId][round][msg.sender] = true;
                unchecked {
                    entropyContributorCount[jobId] += 1;
                }
            }
            return selected;
        }

        // Finalization path using the stored entropy and future blockhash.
        if (entropyContributorCount[jobId] < MIN_ENTROPY_CONTRIBUTORS && !entropyContributed[jobId][round][msg.sender])
        {
            pendingEntropy[jobId] ^= uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
            entropyContributed[jobId][round][msg.sender] = true;
            unchecked {
                entropyContributorCount[jobId] += 1;
            }
        }
        if (entropyContributorCount[jobId] < MIN_ENTROPY_CONTRIBUTORS) {
            round += 1;
            entropyRound[jobId] = round;
            pendingEntropy[jobId] = uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
            entropyContributorCount[jobId] = 1;
            entropyContributed[jobId][round][msg.sender] = true;
            selectionBlock[jobId] = block.number + 1;
            emit SelectionReset(jobId);
            return selected;
        }
        bytes32 bhash = blockhash(targetBlock);
        if (bhash == bytes32(0)) {
            round += 1;
            entropyRound[jobId] = round;
            pendingEntropy[jobId] = uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
            entropyContributorCount[jobId] = 1;
            entropyContributed[jobId][round][msg.sender] = true;
            selectionBlock[jobId] = block.number + 1;
            emit SelectionReset(jobId);
            return selected;
        }

        uint256 randaoValue = uint256(block.prevrandao);
        if (randaoValue == 0) {
            randaoValue = uint256(
                keccak256(abi.encodePacked(blockhash(block.number - 1), blockhash(block.number - 2), msg.sender))
            );
        }

        unchecked {
            jobNonce[jobId] += 1;
        }

        uint256 rcRand;
        if (address(randaoCoordinator) != address(0)) {
            // RandaoCoordinator.random already mixes its seed with `block.prevrandao`
            rcRand = randaoCoordinator.random(bytes32(jobId));
        }

        bytes32 seed = keccak256(
            abi.encode(jobId, jobNonce[jobId], pendingEntropy[jobId], randaoValue, bhash, address(this), rcRand)
        );
        selectionSeeds[jobId] = seed;
        emit SelectionSeedRecorded(jobId, seed);
        uint256 randomSeed = uint256(seed);

        uint256 n = validatorPool.length;
        if (n == 0) revert InsufficientValidators();
        if (n > maxValidatorPoolSize) revert PoolLimitExceeded();
        if (address(stakeManager) == address(0)) revert StakeManagerNotSet();

        uint256 sample = validatorPoolSampleSize;
        if (sample > n) sample = n;

        uint256 size = r.committeeSize;
        if (size == 0) {
            size = validatorsPerJob;
            r.committeeSize = size;
        }
        if (size > maxValidatorsPerJob) size = maxValidatorsPerJob;
        if (sample < size) revert SampleSizeTooSmall();

        selected = new address[](size);
        uint256[] memory stakes = new uint256[](size);

        address[] memory candidates = new address[](sample);
        uint256[] memory candidateStakes = new uint256[](sample);
        uint256 candidateCount;
        uint256 totalStake;

        if (selectionStrategy == IValidationModule.SelectionStrategy.Rotating) {
            uint256 rotationStart = validatorPoolRotation;
            uint256 offset = uint256(keccak256(abi.encodePacked(randaoValue, bhash))) % n;
            rotationStart = (rotationStart + offset) % n;
            uint256 i;
            for (; i < n && candidateCount < sample;) {
                uint256 idx = (rotationStart + i) % n;
                address candidate = validatorPool[idx];

                if (validatorBanUntil[candidate] > block.number) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                uint256 stake = stakeManager.stakeOf(candidate, IStakeManager.Role.Validator);
                if (stake == 0) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                if (address(reputationEngine) != address(0)) {
                    if (reputationEngine.isBlacklisted(candidate)) {
                        unchecked {
                            ++i;
                        }
                        continue;
                    }
                }

                bool authorized = validatorAuthCache[candidate]
                    && validatorAuthVersion[candidate] == validatorAuthCacheVersion
                    && validatorAuthExpiry[candidate] > block.timestamp;
                if (!authorized) {
                    string memory subdomain = validatorSubdomains[candidate];
                    bool skipVerification;
                    if (bytes(subdomain).length == 0) {
                        if (!identityRegistry.additionalValidators(candidate)) {
                            unchecked {
                                ++i;
                            }
                            continue;
                        }
                        authorized = true;
                        skipVerification = true;
                    }
                    if (!skipVerification) {
                        bytes32[] memory proof;
                        (authorized,,,) = identityRegistry.verifyValidator(candidate, subdomain, proof);
                    }
                    if (authorized) {
                        validatorAuthCache[candidate] = true;
                        validatorAuthExpiry[candidate] = block.timestamp + validatorAuthCacheDuration;
                        validatorAuthVersion[candidate] = validatorAuthCacheVersion;
                    }
                }
                if (!authorized) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                candidates[candidateCount] = candidate;
                candidateStakes[candidateCount] = stake;
                totalStake += stake;
                unchecked {
                    ++candidateCount;
                    ++i;
                }
            }
            validatorPoolRotation = (rotationStart + i) % n;
            emit ValidatorPoolRotationUpdated(validatorPoolRotation);
        } else {
            uint256 eligible;
            for (uint256 i; i < n;) {
                address candidate = validatorPool[i];

                if (validatorBanUntil[candidate] > block.number) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                uint256 stake = stakeManager.stakeOf(candidate, IStakeManager.Role.Validator);
                if (stake == 0) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                if (address(reputationEngine) != address(0)) {
                    if (reputationEngine.isBlacklisted(candidate)) {
                        unchecked {
                            ++i;
                        }
                        continue;
                    }
                }

                bool authorized = validatorAuthCache[candidate]
                    && validatorAuthVersion[candidate] == validatorAuthCacheVersion
                    && validatorAuthExpiry[candidate] > block.timestamp;
                if (!authorized) {
                    string memory subdomain = validatorSubdomains[candidate];
                    bool skipVerification;
                    if (bytes(subdomain).length == 0) {
                        if (!identityRegistry.additionalValidators(candidate)) {
                            unchecked {
                                ++i;
                            }
                            continue;
                        }
                        authorized = true;
                        skipVerification = true;
                    }
                    if (!skipVerification) {
                        bytes32[] memory proof;
                        (authorized,,,) = identityRegistry.verifyValidator(candidate, subdomain, proof);
                    }
                    if (authorized) {
                        validatorAuthCache[candidate] = true;
                        validatorAuthExpiry[candidate] = block.timestamp + validatorAuthCacheDuration;
                        validatorAuthVersion[candidate] = validatorAuthCacheVersion;
                    }
                }
                if (!authorized) {
                    unchecked {
                        ++i;
                    }
                    continue;
                }

                unchecked {
                    ++eligible;
                }

                if (candidateCount < sample) {
                    candidates[candidateCount] = candidate;
                    candidateStakes[candidateCount] = stake;
                    totalStake += stake;
                    unchecked {
                        ++candidateCount;
                    }
                } else {
                    randomSeed = uint256(keccak256(abi.encode(randomSeed, i)));
                    uint256 j = randomSeed % eligible;
                    if (j < sample) {
                        totalStake = totalStake - candidateStakes[j] + stake;
                        candidates[j] = candidate;
                        candidateStakes[j] = stake;
                    }
                }

                unchecked {
                    ++i;
                }
            }
        }

        if (candidateCount < size) revert InsufficientValidators();

        for (uint256 i; i < size;) {
            randomSeed = uint256(keccak256(abi.encode(randomSeed, i)));
            uint256 pick = randomSeed % totalStake;
            uint256 cumulative;
            uint256 chosen;
            for (uint256 j; j < candidateCount;) {
                cumulative += candidateStakes[j];
                if (pick < cumulative) {
                    chosen = j;
                    break;
                }
                unchecked {
                    ++j;
                }
            }

            address val = candidates[chosen];
            selected[i] = val;
            stakes[i] = candidateStakes[chosen];

            totalStake -= candidateStakes[chosen];
            candidateCount -= 1;
            candidates[chosen] = candidates[candidateCount];
            candidateStakes[chosen] = candidateStakes[candidateCount];

            unchecked {
                ++i;
            }
        }

        for (uint256 i; i < size;) {
            address val = selected[i];
            uint256 stakeAmount = stakes[i];
            validatorStakes[jobId][val] = stakeAmount;
            validatorStakeLocks[jobId][val] = stakeAmount;
            _validatorLookup[jobId][val] = true;
            unchecked {
                ++i;
            }
        }

        r.validators = selected;
        r.commitDeadline = block.timestamp + commitWindow;
        r.revealDeadline = r.commitDeadline + revealWindow;

        uint256 lockDuration = commitWindow + revealWindow + forceFinalizeGrace;
        if (lockDuration > type(uint64).max) revert InvalidWindows();
        uint64 lockTime = uint64(lockDuration);

        for (uint256 i; i < size;) {
            address val = selected[i];
            uint256 stakeAmount = validatorStakeLocks[jobId][val];
            stakeManager.lockValidatorStake(jobId, val, stakeAmount, lockTime);
            unchecked {
                ++i;
            }
        }

        // Clear stored entropy and target block after finalization.
        delete pendingEntropy[jobId];
        delete selectionBlock[jobId];

        emit ValidatorsSelected(jobId, selected);
        return selected;
    }

    /// @dev Internal implementation of IValidationModule.
    function _entry_start(uint256 jobId, uint256 entropy)
        internal
        whenNotPaused
        nonReentrant
        returns (address[] memory)
    {
        if (msg.sender != address(jobRegistry)) revert OnlyJobRegistry();
        IJobRegistry.Job memory jobSnapshot = jobRegistry.jobs(jobId);
        IJobRegistry.JobMetadata memory meta = jobRegistry.decodeJobMetadata(jobSnapshot.packedMetadata);
        if (meta.status != IJobRegistry.Status.Submitted) revert JobNotSubmitted();
        Round storage r = rounds[jobId];
        uint256 n = validatorPool.length;
        if (n < minValidators) revert ValidatorPoolTooSmall();
        uint256 size = validatorsPerJob;
        if (size < minValidators) size = minValidators;
        if (size > maxValidators) size = maxValidators;
        if (size > maxValidatorsPerJob) size = maxValidatorsPerJob;
        if (size > n) size = n;
        r.committeeSize = size;

        // Initialize entropy and schedule finalization using a future blockhash.
        uint256 round = ++entropyRound[jobId];
        pendingEntropy[jobId] = uint256(keccak256(abi.encodePacked(msg.sender, entropy)));
        entropyContributorCount[jobId] = 1;
        entropyContributed[jobId][round][msg.sender] = true;
        selectionBlock[jobId] = block.number + 1;

        return new address[](0);
    }

    /// @notice Internal commit logic shared by overloads.
    function _commitValidation(uint256 jobId, bytes32 commitHash, string memory subdomain, bytes32[] memory proof)
        internal
        whenNotPaused
    {
        Round storage r = rounds[jobId];
        IJobRegistry.Job memory jobSnapshot = jobRegistry.jobs(jobId);
        IJobRegistry.JobMetadata memory meta = jobRegistry.decodeJobMetadata(jobSnapshot.packedMetadata);
        if (meta.status != IJobRegistry.Status.Submitted) revert JobNotSubmitted();
        if (r.commitDeadline == 0 || block.timestamp > r.commitDeadline) {
            revert CommitPhaseClosed();
        }
        if (validatorBanUntil[msg.sender] > block.number) revert ValidatorBanned();
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) {
                revert BlacklistedValidator();
            }
        }
        if (address(identityRegistry) == address(0)) revert ZeroIdentityRegistry();
        if (!_isValidator(jobId, msg.sender)) revert NotValidator();
        (bool authorized, bytes32 node, bool viaWrapper, bool viaMerkle) =
            identityRegistry.verifyValidator(msg.sender, subdomain, proof);
        if (!authorized) revert UnauthorizedValidator();
        emit ValidatorIdentityVerified(msg.sender, node, subdomain, viaWrapper, viaMerkle);
        validatorAuthCache[msg.sender] = true;
        validatorAuthVersion[msg.sender] = validatorAuthCacheVersion;
        validatorAuthExpiry[msg.sender] = block.timestamp + validatorAuthCacheDuration;
        if (validatorStakes[jobId][msg.sender] == 0) revert NoStake();
        uint256 nonce = jobNonce[jobId];
        if (commitments[jobId][msg.sender][nonce] != bytes32(0)) {
            revert AlreadyCommitted();
        }

        commitments[jobId][msg.sender][nonce] = commitHash;
        emit ValidationCommitted(jobId, msg.sender, commitHash, subdomain);
    }

    function _policy() internal view returns (ITaxPolicy) {
        address registry = address(jobRegistry);
        if (registry == address(0)) revert InvalidJobRegistry();
        return IJobRegistryTax(registry).taxPolicy();
    }

    /// @notice Commit a validation hash for a job.
    function _entry_commitValidation(
        uint256 jobId,
        bytes32 commitHash,
        string calldata subdomain,
        bytes32[] calldata proof
    )
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(_policy(), msg.sender, owner(), address(0), address(0))
    {
        _commitValidation(jobId, commitHash, subdomain, proof);
    }

    /// @notice Internal reveal logic shared by overloads.
    function _revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string memory subdomain,
        bytes32[] memory proof
    ) internal whenNotPaused {
        Round storage r = rounds[jobId];
        if (block.timestamp <= r.commitDeadline) revert CommitPhaseActive();
        if (block.timestamp > r.revealDeadline) revert RevealPhaseClosed();
        if (!_isValidator(jobId, msg.sender)) revert NotValidator();
        if (validatorBanUntil[msg.sender] > block.number) revert ValidatorBanned();
        if (address(reputationEngine) != address(0)) {
            if (reputationEngine.isBlacklisted(msg.sender)) {
                revert BlacklistedValidator();
            }
        }
        if (address(identityRegistry) == address(0)) revert ZeroIdentityRegistry();
        (bool authorized, bytes32 node, bool viaWrapper, bool viaMerkle) =
            identityRegistry.verifyValidator(msg.sender, subdomain, proof);
        if (!authorized) revert UnauthorizedValidator();
        emit ValidatorIdentityVerified(msg.sender, node, subdomain, viaWrapper, viaMerkle);
        validatorAuthCache[msg.sender] = true;
        validatorAuthVersion[msg.sender] = validatorAuthCacheVersion;
        validatorAuthExpiry[msg.sender] = block.timestamp + validatorAuthCacheDuration;
        uint256 nonce = jobNonce[jobId];
        bytes32 commitHash = commitments[jobId][msg.sender][nonce];
        if (commitHash == bytes32(0)) revert CommitMissing();
        if (revealed[jobId][msg.sender]) revert AlreadyRevealed();
        IJobRegistry registry = jobRegistry;
        address registryAddr = address(registry);
        if (registryAddr == address(0)) revert InvalidJobRegistry();
        (bool burnRequired, bool burnSatisfied) = registry.burnEvidenceStatus(jobId);
        if (burnRequired) {
            if (burnSatisfied) {
                if (burnTxHash == bytes32(0)) revert InvalidBurnReceipt();
                if (!registry.hasBurnReceipt(jobId, burnTxHash)) {
                    revert InvalidBurnReceipt();
                }
            } else if (burnTxHash != bytes32(0)) {
                if (!registry.hasBurnReceipt(jobId, burnTxHash)) {
                    revert InvalidBurnReceipt();
                }
            }
        } else if (burnTxHash != bytes32(0)) {
            if (!registry.hasBurnReceipt(jobId, burnTxHash)) {
                revert InvalidBurnReceipt();
            }
        }
        bytes32 specHash = registry.getSpecHash(jobId);
        bytes32 outcomeHash = keccak256(abi.encode(nonce, specHash, approve, burnTxHash));
        bytes32 expected = keccak256(abi.encode(jobId, outcomeHash, salt, msg.sender, block.chainid, DOMAIN_SEPARATOR));
        if (commitHash != expected) {
            bytes32 legacy = keccak256(abi.encodePacked(jobId, nonce, approve, burnTxHash, salt, specHash));
            if (commitHash != legacy) revert InvalidReveal();
        }

        uint256 stake = validatorStakes[jobId][msg.sender];
        if (stake == 0) revert NoStake();
        revealed[jobId][msg.sender] = true;
        votes[jobId][msg.sender] = approve;
        r.participants.push(msg.sender);
        r.revealedCount += 1;
        if (approve) r.approvals += stake;
        else r.rejections += stake;
        uint256 committee = r.committeeSize == 0 ? validatorsPerJob : r.committeeSize;
        if (committee > maxValidatorsPerJob) committee = maxValidatorsPerJob;
        uint256 quorumTarget = _quorumTarget(committee);
        if (quorumTarget > 0 && r.earlyFinalizeEligibleAt == 0 && r.revealedCount >= quorumTarget) {
            r.earlyFinalizeEligibleAt = uint64(block.timestamp + earlyFinalizeDelay);
        }

        emit ValidationRevealed(jobId, msg.sender, approve, burnTxHash, subdomain);
    }

    /// @notice Reveal a previously committed validation vote.
    function _entry_revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    )
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(_policy(), msg.sender, owner(), address(0), address(0))
    {
        _revealValidation(jobId, approve, burnTxHash, salt, subdomain, proof);
    }

    /// @notice Backwards-compatible wrapper for commitValidation.
    function _entry_commitVote(uint256 jobId, bytes32 commitHash, string calldata subdomain, bytes32[] calldata proof)
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(_policy(), msg.sender, owner(), address(0), address(0))
    {
        _entry_commitValidation(jobId, commitHash, subdomain, proof);
    }

    /// @notice Backwards-compatible wrapper for revealValidation.
    function _entry_revealVote(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    )
        internal
        whenNotPaused
        nonReentrant
        requiresTaxAcknowledgement(_policy(), msg.sender, owner(), address(0), address(0))
    {
        _entry_revealValidation(jobId, approve, burnTxHash, salt, subdomain, proof);
    }

    /// @notice Tally revealed votes, apply slashing/rewards, and push result to JobRegistry.
    function _entry_finalize(uint256 jobId) internal whenNotPaused nonReentrant returns (bool success) {
        return _finalize(jobId);
    }

    function _entry_finalizeValidation(uint256 jobId) internal whenNotPaused nonReentrant returns (bool success) {
        return _finalize(jobId);
    }

    /// @notice Force finalize a job after the reveal deadline plus grace period.
    /// @dev If quorum was not met, no result is recorded and the employer/agent are refunded.
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function _entry_forceFinalize(uint256 jobId) internal whenNotPaused nonReentrant returns (bool success) {
        Round storage r = rounds[jobId];
        if (r.tallied) revert AlreadyTallied();
        if (block.timestamp <= r.revealDeadline + forceFinalizeGrace) {
            revert RevealPending();
        }
        uint256 size = r.committeeSize == 0 ? validatorsPerJob : r.committeeSize;
        if (size > maxValidatorsPerJob) size = maxValidatorsPerJob;
        uint256 quorumTarget = _quorumTarget(size);
        if (quorumTarget == 0 || r.revealedCount >= quorumTarget) {
            return _finalize(jobId);
        }
        emit ValidationQuorumFailed(jobId, r.revealedCount, quorumTarget);
        r.earlyFinalizeEligibleAt = 0;

        IJobRegistry.Job memory job = jobRegistry.jobs(jobId);
        uint256 vlen = r.validators.length;
        if (vlen > maxValidatorsPerJob) vlen = maxValidatorsPerJob;
        (bool burnRequired, bool burnSatisfied) = jobRegistry.burnEvidenceStatus(jobId);
        bool skipPenalties = burnRequired && !burnSatisfied;
        for (uint256 i; i < vlen;) {
            address val = r.validators[i];
            if (!revealed[jobId][val] && !skipPenalties) {
                uint256 stake = validatorStakes[jobId][val];
                uint256 penalty = (stake * nonRevealPenaltyBps) / 10_000;
                if (penalty > 0) {
                    stakeManager.slash(val, IStakeManager.Role.Validator, penalty, job.employer);
                    _reduceValidatorLock(jobId, val, penalty);
                }
                if (nonRevealBanBlocks != 0) {
                    uint256 untilBlock = block.number + nonRevealBanBlocks;
                    validatorBanUntil[val] = untilBlock;
                    emit ValidatorBanApplied(val, untilBlock);
                }
                if (address(reputationEngine) != address(0)) {
                    reputationEngine.subtract(val, 1);
                }
            }
            unchecked {
                ++i;
            }
        }
        r.tallied = true;
        emit ValidationTallied(jobId, false, r.approvals, r.rejections);
        emit ValidationResult(jobId, false);
        jobRegistry.forceFinalize(jobId);
        _cleanup(jobId);
        return false;
    }

    function _quorumTarget(uint256 committee) internal view returns (uint256) {
        if (committee == 0) {
            return 0;
        }
        uint256 pct = revealQuorumPct;
        uint256 pctCount;
        if (pct == 0) {
            pctCount = 0;
        } else {
            uint256 numerator = committee * pct;
            pctCount = numerator / 100;
            if (numerator % 100 != 0) {
                unchecked {
                    pctCount += 1;
                }
            }
        }
        uint256 minCount = minRevealValidators;
        if (minCount > committee) {
            minCount = committee;
        }
        if (pctCount < minCount) {
            return minCount;
        }
        return pctCount;
    }

    function _finalize(uint256 jobId) internal returns (bool success) {
        Round storage r = rounds[jobId];
        if (r.tallied) revert AlreadyTallied();
        bool earlyWindowReached = r.earlyFinalizeEligibleAt != 0 && block.timestamp >= r.earlyFinalizeEligibleAt;
        if (r.revealedCount != r.validators.length) {
            if (!earlyWindowReached && block.timestamp <= r.revealDeadline) {
                revert RevealPending();
            }
        }

        uint256 total = r.approvals + r.rejections;
        uint256 size = r.committeeSize == 0 ? validatorsPerJob : r.committeeSize;
        if (size > maxValidatorsPerJob) size = maxValidatorsPerJob;
        uint256 quorumTarget = _quorumTarget(size);
        bool quorum = quorumTarget == 0 || r.revealedCount >= quorumTarget;
        uint256 approvalCount;
        uint256 vlen = r.validators.length;
        if (vlen > maxValidatorsPerJob) vlen = maxValidatorsPerJob;
        for (uint256 i; i < vlen;) {
            address v = r.validators[i];
            if (revealed[jobId][v] && votes[jobId][v]) {
                unchecked {
                    ++approvalCount;
                }
            }
            unchecked {
                ++i;
            }
        }
        if (!quorum && quorumTarget > 0) {
            emit ValidationQuorumFailed(jobId, r.revealedCount, quorumTarget);
        }
        if (quorum && total > 0) {
            bool thresholdMet = (r.approvals * 100) >= (total * approvalThreshold);
            bool countMet = approvalCount >= requiredValidatorApprovals;
            success = thresholdMet && countMet;
        } else {
            success = false;
        }
        IJobRegistry.Job memory job = jobRegistry.jobs(jobId);
        address[] memory committee = new address[](vlen);
        bool[] memory revealedStates = new bool[](vlen);
        bool[] memory voteStates = new bool[](vlen);
        for (uint256 i; i < vlen;) {
            address validator = r.validators[i];
            committee[i] = validator;
            revealedStates[i] = revealed[jobId][validator];
            voteStates[i] = votes[jobId][validator];
            unchecked {
                ++i;
            }
        }

        if (address(reputationEngine) != address(0)) {
            uint256 payout;
            uint256 duration;
            if (success) {
                IJobRegistry.JobMetadata memory metadata = jobRegistry.decodeJobMetadata(job.packedMetadata);
                uint256 validatorPct = jobRegistry.validatorRewardPct();
                uint256 rewardAfterValidator = uint256(job.reward);
                if (committee.length > 0 && validatorPct > 0) {
                    uint256 validatorReward = (uint256(job.reward) * validatorPct) / 100;
                    rewardAfterValidator -= validatorReward;
                }
                uint256 agentPctRaw = metadata.agentPct;
                uint256 agentPct = agentPctRaw == 0 ? 100 : agentPctRaw;
                uint256 agentAmount = (rewardAfterValidator * agentPct) / 100;
                payout = agentAmount * 1e12;
                if (metadata.assignedAt != 0 && block.timestamp > metadata.assignedAt) {
                    duration = block.timestamp - uint256(metadata.assignedAt);
                }
            }

            reputationEngine.updateScores(
                jobId, job.agent, committee, success, revealedStates, voteStates, payout, duration
            );
            jobRegistry.markReputationProcessed(jobId);
        }

        for (uint256 i; i < vlen;) {
            address val = r.validators[i];
            uint256 stake = validatorStakes[jobId][val];
            uint256 slashAmount = (stake * validatorSlashingPercentage) / 100;
            if (!revealed[jobId][val]) {
                uint256 penalty = (stake * nonRevealPenaltyBps) / 10_000;
                if (penalty > 0) {
                    stakeManager.slash(val, IStakeManager.Role.Validator, penalty, job.employer);
                    _reduceValidatorLock(jobId, val, penalty);
                }
                if (nonRevealBanBlocks != 0) {
                    uint256 untilBlock = block.number + nonRevealBanBlocks;
                    validatorBanUntil[val] = untilBlock;
                    emit ValidatorBanApplied(val, untilBlock);
                }
            } else if (votes[jobId][val] != success) {
                if (slashAmount > 0) {
                    stakeManager.slash(val, IStakeManager.Role.Validator, slashAmount, job.employer);
                    _reduceValidatorLock(jobId, val, slashAmount);
                }
            }
            unchecked {
                ++i;
            }
        }

        r.tallied = true;
        emit ValidationTallied(jobId, success, r.approvals, r.rejections);
        emit ValidationResult(jobId, success);

        jobRegistry.onValidationResult(jobId, success, r.validators);
        _cleanup(jobId);
        return success;
    }

    function _reduceValidatorLock(uint256 jobId, address val, uint256 amount) internal {
        if (amount == 0) {
            return;
        }
        uint256 locked = validatorStakeLocks[jobId][val];
        if (locked == 0) {
            return;
        }
        if (amount >= locked) {
            validatorStakeLocks[jobId][val] = 0;
        } else {
            validatorStakeLocks[jobId][val] = locked - amount;
        }
    }

    function _cleanup(uint256 jobId) internal {
        uint256 nonce = jobNonce[jobId];
        Round storage r = rounds[jobId];
        address[] storage vals = r.validators;
        uint256 vlen = vals.length;
        if (vlen > maxValidatorsPerJob) vlen = maxValidatorsPerJob;
        for (uint256 i; i < vlen;) {
            address val = vals[i];
            delete commitments[jobId][val][nonce];
            delete revealed[jobId][val];
            delete votes[jobId][val];
            uint256 lockAmount = validatorStakeLocks[jobId][val];
            if (lockAmount != 0) {
                stakeManager.unlockValidatorStake(jobId, val, lockAmount);
            }
            delete validatorStakeLocks[jobId][val];
            delete validatorStakes[jobId][val];
            delete _validatorLookup[jobId][val];
            unchecked {
                ++i;
            }
        }
        r.revealedCount = 0;
        delete rounds[jobId];
        delete jobNonce[jobId];
        delete selectionSeeds[jobId];
    }

    /// @notice Reset the validation nonce for a job after finalization or dispute resolution.
    /// @param jobId Identifier of the job
    function _entry_resetJobNonce(uint256 jobId) internal {
        if (msg.sender != owner() && msg.sender != address(jobRegistry)) {
            revert UnauthorizedCaller();
        }
        _cleanup(jobId);
        emit JobNonceReset(jobId);
    }

    /// @notice Reset pending entropy and selection block for a job to allow reselection.
    /// @param jobId Identifier of the job.
    function _entry_resetSelection(uint256 jobId) internal onlyOwner {
        delete pendingEntropy[jobId];
        delete selectionBlock[jobId];
        emit SelectionReset(jobId);
    }

    /// @dev Check whether an address is a selected validator for a job.
    /// @param jobId Identifier of the job.
    /// @param val Validator address to check.
    /// @return True if the address is a validator for the job.
    function _isValidator(uint256 jobId, address val) internal view returns (bool) {
        return _validatorLookup[jobId][val];
    }

    /// @notice Confirms the contract and its owner can never accrue tax obligations.
    /// @return Always true to signal perpetual tax exemption.
    function isTaxExempt() external pure returns (bool) {
        return true;
    }

    // ---------------------------------------------------------------
    // Ether rejection
    // ---------------------------------------------------------------

    /// @dev Prevent accidental ETH deposits; the module never holds funds.
    receive() external payable {
        revert("ValidationModule: no ether");
    }

    /// @dev Reject calls with unexpected calldata or funds.
    fallback() external payable {
        revert("ValidationModule: no ether");
    }

    bytes32 public DOMAIN_SEPARATOR;

    error UnsupportedImplementationSelector();

    function setPauser(address _pauser) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setPauserManager(address manager) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setNonRevealPenalty(uint256 penaltyBps, uint256 banBlocks) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setRevealQuorum(uint256 pct, uint256 minValidators_) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setEarlyFinalizeDelay(uint256 delay) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setForceFinalizeGrace(uint256 grace) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function triggerFailover(
        uint256 jobId,
        IValidationModule.FailoverAction action,
        uint64 extension,
        string calldata reason
    ) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorPool(address[] calldata newPool) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setReputationEngine(IReputationEngine engine) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setJobRegistry(IJobRegistry registry) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setStakeManager(IStakeManager manager) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setIdentityRegistry(IIdentityRegistry registry) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setRandaoCoordinator(IRandaoCoordinator coordinator) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function pause() external virtual {
        revert UnsupportedImplementationSelector();
    }

    function unpause() external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorPoolSampleSize(uint256 size) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setMaxValidatorPoolSize(uint256 size) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setMaxValidatorsPerJob(uint256 max) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setSelectionStrategy(IValidationModule.SelectionStrategy strategy) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorAuthCacheDuration(uint256 duration) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function bumpValidatorAuthCacheVersion() public virtual {
        revert UnsupportedImplementationSelector();
    }

    function setParameters(
        uint256 committeeSize,
        uint256 commitDur,
        uint256 revealDur,
        uint256 approvalPct,
        uint256 slashPct
    ) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function setParameters(uint256 validatorCount, uint256 commitDur, uint256 revealDur) public virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorSubdomains(address[] calldata accounts, string[] calldata subdomains) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setMySubdomain(string calldata subdomain) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setCommitRevealWindows(uint256 commitDur, uint256 revealDur) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function setTiming(uint256 commitDur, uint256 revealDur) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorBounds(uint256 minVals, uint256 maxVals) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorsPerJob(uint256 count) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function setCommitWindow(uint256 commitDur) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setRevealWindow(uint256 revealDur) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setMinValidators(uint256 minVals) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setMaxValidators(uint256 maxVals) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setValidatorSlashingPct(uint256 pct) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setApprovalThreshold(uint256 pct) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function setRequiredValidatorApprovals(uint256 count) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function setAutoApprovalTarget(bool enabled) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function selectValidators(uint256 jobId, uint256 entropy)
        public
        virtual
        override
        returns (address[] memory selected)
    {
        revert UnsupportedImplementationSelector();
    }

    function start(uint256 jobId, uint256 entropy) external virtual override returns (address[] memory) {
        revert UnsupportedImplementationSelector();
    }

    function commitValidation(uint256 jobId, bytes32 commitHash, string calldata subdomain, bytes32[] calldata proof)
        public
        virtual
        override
    {
        revert UnsupportedImplementationSelector();
    }

    function revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) public virtual override {
        revert UnsupportedImplementationSelector();
    }

    function commitVote(uint256 jobId, bytes32 commitHash, string calldata subdomain, bytes32[] calldata proof)
        external
        virtual
    {
        revert UnsupportedImplementationSelector();
    }

    function revealVote(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external virtual {
        revert UnsupportedImplementationSelector();
    }

    function finalize(uint256 jobId) external virtual override returns (bool success) {
        revert UnsupportedImplementationSelector();
    }

    function finalizeValidation(uint256 jobId) external virtual override returns (bool success) {
        revert UnsupportedImplementationSelector();
    }

    function forceFinalize(uint256 jobId) external virtual override returns (bool success) {
        revert UnsupportedImplementationSelector();
    }

    function resetJobNonce(uint256 jobId) external virtual override {
        revert UnsupportedImplementationSelector();
    }

    function resetSelection(uint256 jobId) external virtual {
        revert UnsupportedImplementationSelector();
    }
}

contracts/v2/interfaces/IFeePool.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/// @title IFeePool
/// @notice Minimal interface for depositing job fees
interface IFeePool {
    /// @notice contract version for compatibility checks
    function version() external view returns (uint256);

    /// @notice notify the pool about newly received fees
    /// @dev The pool burns the configured percentage and escrows the remainder for stakers.
    /// @param amount amount of tokens transferred to the pool scaled to 18 decimals
    function depositFee(uint256 amount) external;

    /// @notice distribute pending fees to stakers
    /// @dev All fee amounts use 18 decimal units.
    function distributeFees() external;

    /// @notice claim accumulated rewards for caller
    /// @dev Rewards use 18 decimal units.
    function claimRewards() external;

    /// @notice governance-controlled emergency withdrawal of tokens from the pool
    /// @dev Amount uses 18 decimal units.
    /// @param to address receiving the tokens
    /// @param amount token amount with 18 decimals
    function governanceWithdraw(address to, uint256 amount) external;

    /// @notice Transfer reward tokens to a recipient.
    /// @param to address receiving the reward
    /// @param amount token amount with 18 decimals
    function reward(address to, uint256 amount) external;
}

contracts/v2/interfaces/IIdentityRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

interface IIdentityRegistry {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    enum AgentType {
        Human,
        AI
    }
    function isAuthorizedAgent(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external view returns (bool);

    function isAuthorizedValidator(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external view returns (bool);

    function verifyAgent(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    function verifyValidator(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    function verifyNode(
        address claimant,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external returns (bool ok, bytes32 node, bool viaWrapper, bool viaMerkle);

    // owner configuration
    function setENS(address ensAddr) external;
    function setNameWrapper(address wrapper) external;
    function setReputationEngine(address engine) external;
    function setAgentRootNode(bytes32 root) external;
    function setClubRootNode(bytes32 root) external;
    function setNodeRootNode(bytes32 root) external;
    function setAgentMerkleRoot(bytes32 root) external;
    function setValidatorMerkleRoot(bytes32 root) external;

    // manual allowlists
    function addAdditionalAgent(address agent) external;
    function removeAdditionalAgent(address agent) external;
    function addAdditionalValidator(address validator) external;
    function removeAdditionalValidator(address validator) external;
    function addAdditionalNodeOperator(address nodeOperator) external;
    function removeAdditionalNodeOperator(address nodeOperator) external;

    function setAgentType(address agent, AgentType agentType) external;

    // views
    function additionalAgents(address account) external view returns (bool);
    function additionalValidators(address account) external view returns (bool);
    function additionalNodeOperators(address account) external view returns (bool);
    function getAgentType(address agent) external view returns (AgentType);

    // profile metadata
    function setAgentProfileURI(address agent, string calldata uri) external;
    function updateAgentProfile(
        string calldata subdomain,
        bytes32[] calldata proof,
        string calldata uri
    ) external;
    function agentProfileURI(address agent) external view returns (string memory);
}

contracts/v2/interfaces/IJobRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/// @title IJobRegistry
/// @notice Interface for orchestrating job lifecycles and module coordination
interface IJobRegistry {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    enum Status {
        None,
        Created,
        Applied,
        Submitted,
        Completed,
        Disputed,
        Finalized,
        Cancelled
    }

    struct Job {
        address employer;
        address agent;
        uint128 reward;
        uint96 stake;
        uint128 burnReceiptAmount;
        bytes32 uriHash;
        bytes32 resultHash;
        bytes32 specHash;
        uint256 packedMetadata;
    }

    struct JobMetadata {
        Status status;
        bool success;
        bool burnConfirmed;
        uint8 agentTypes;
        uint32 feePct;
        uint32 agentPct;
        uint64 deadline;
        uint64 assignedAt;
    }

    /// @dev Reverts when job creation parameters have not been configured
    error JobParametersUnset();

    /// @dev Reverts when referencing a job that does not exist
    error InvalidJob(uint256 jobId);

    /// @dev Reverts when an operation is invoked by a non-employer
    error OnlyEmployer(address caller);

    /// @dev Reverts when an operation is invoked by a non-agent
    error OnlyAgent(address caller);

    /// @dev Reverts when a job is in an unexpected status
    error InvalidStatus(Status expected, Status actual);

    error BurnReceiptMissing();
    error BurnNotConfirmed();

    // module configuration
    event ModuleUpdated(string module, address indexed newAddress);
    event ValidationModuleUpdated(address module);
    event ReputationEngineUpdated(address engine);
    event StakeManagerUpdated(address manager);
    event CertificateNFTUpdated(address nft);
    event DisputeModuleUpdated(address module);
    event IdentityRegistryUpdated(address identityRegistry);
    event AgentRootNodeUpdated(bytes32 node);
    event AgentMerkleRootUpdated(bytes32 root);
    event JobParametersUpdated(
        uint256 reward,
        uint256 stake,
        uint256 maxJobReward,
        uint256 maxJobDuration,
        uint256 minAgentStake
    );

    // job lifecycle
    event JobCreated(
        uint256 indexed jobId,
        address indexed employer,
        address indexed agent,
        uint256 reward,
        uint256 stake,
        uint256 fee,
        bytes32 specHash,
        string uri
    );
    event ApplicationSubmitted(
        uint256 indexed jobId,
        address indexed applicant,
        string subdomain
    );
    event AgentAssigned(
        uint256 indexed jobId,
        address indexed agent,
        string subdomain
    );
    event ResultSubmitted(
        uint256 indexed jobId,
        address indexed worker,
        bytes32 resultHash,
        string resultURI,
        string subdomain
    );
    /// @dev Legacy alias for {AgentAssigned}. Kept for backwards compatibility.
    event JobApplied(
        uint256 indexed jobId,
        address indexed agent,
        string subdomain
    );
    /// @dev Legacy alias for {ResultSubmitted}. Kept for backwards compatibility.
    event JobSubmitted(
        uint256 indexed jobId,
        address indexed worker,
        bytes32 resultHash,
        string resultURI,
        string subdomain
    );
    event JobCompleted(uint256 indexed jobId, bool success);
    /// @notice Emitted when job funds are disbursed
    /// @param jobId Identifier of the job
    /// @param worker Agent who performed the job
    /// @param netPaid Amount paid to the agent after burn
    /// @param fee Protocol fee amount
    event JobPayout(
        uint256 indexed jobId,
        address indexed worker,
        uint256 netPaid,
        uint256 fee
    );
    /// @notice Emitted when a job is finalized
    /// @param jobId Identifier of the job
    /// @param worker Agent who performed the job
    event JobFinalized(uint256 indexed jobId, address indexed worker);
    event JobDisputed(uint256 indexed jobId, address indexed caller);
    event JobCancelled(uint256 indexed jobId);
    event DisputeResolved(uint256 indexed jobId, bool employerWins);
    event BurnReceiptSubmitted(
        uint256 indexed jobId,
        bytes32 indexed burnTxHash,
        uint256 amount,
        uint256 blockNumber
    );
    event BurnConfirmed(uint256 indexed jobId, bytes32 indexed burnTxHash);
    event BurnDiscrepancy(
        uint256 indexed jobId,
        uint256 receiptAmount,
        uint256 expectedAmount
    );
    event ValidationStartPending(uint256 indexed jobId);
    event ValidationStartTriggered(uint256 indexed jobId);

    // owner wiring of modules

    /// @notice Set the validation module responsible for job verification
    /// @param module Address of the validation module contract
    function setValidationModule(address module) external;

    /// @notice Set the reputation engine used to track participant scores
    /// @param engine Address of the reputation engine contract
    function setReputationEngine(address engine) external;

    /// @notice Set the stake manager contract used for collateral accounting
    /// @param manager Address of the stake manager contract
    function setStakeManager(address manager) external;

    /// @notice Set the certificate NFT contract used to mint completion tokens
    /// @param nft Address of the certificate NFT contract
    function setCertificateNFT(address nft) external;

    /// @notice Set the dispute module contract handling appeals
    /// @param module Address of the dispute module contract
    function setDisputeModule(address module) external;

    /// @notice Set the identity registry used for agent verification
    /// @param registry Address of the identity registry contract
    function setIdentityRegistry(address registry) external;

    /// @notice Update the ENS root node used for agent verification
    function setAgentRootNode(bytes32 node) external;

    /// @notice Update the agent allowlist Merkle root
    function setAgentMerkleRoot(bytes32 root) external;

    /// @notice Retrieve the StakeManager contract handling collateral
    /// @return Address of the StakeManager
    function stakeManager() external view returns (address);

    /// @notice Decode packed job metadata into individual fields.
    function decodeJobMetadata(uint256 packed)
        external
        pure
        returns (JobMetadata memory);

    /// @notice Retrieve validator reward percentage used for reputation context.
    function validatorRewardPct() external view returns (uint256);

    /// @notice Mark that reputation for a job has been processed externally.
    function markReputationProcessed(uint256 jobId) external;

    /// @notice Check whether reputation updates for a job were already applied.
    function reputationProcessed(uint256 jobId) external view returns (bool);

    /// @notice Retrieve the ValidationModule managing validator sets
    /// @return Address of the ValidationModule
    function validationModule() external view returns (address);

    /// @notice Retrieve the validator committee cached for a job.
    function getJobValidators(uint256 jobId) external view returns (address[] memory);

    /// @notice Retrieve the cached approval vote for a validator on a job.
    function getJobValidatorVote(uint256 jobId, address validator) external view returns (bool);

    /// @notice Retrieve the validator roster and approval votes cached for a job.
    function validatorCommittee(uint256 jobId)
        external
        view
        returns (address[] memory validators, bool[] memory approvals);

    /// @notice Owner configuration of job limits
    /// @param maxReward Maximum allowed reward for a job
    /// @param stake Stake required from the agent to accept a job
    function setJobParameters(uint256 maxReward, uint256 stake) external;

    /// @notice set the required agent stake for each job
    function setJobStake(uint96 stake) external;

    /// @notice set the minimum unstaked balance agents must maintain to apply
    function setMinAgentStake(uint256 stake) external;

    /// @notice set the maximum allowed job reward
    function setMaxJobReward(uint256 maxReward) external;

    /// @notice set the maximum allowed job duration in seconds
    function setJobDurationLimit(uint256 limit) external;

    /// @notice update the percentage of each job reward taken as a protocol fee
    function setFeePct(uint256 feePct) external;

    /// @notice update validator reward percentage of job reward
    function setValidatorRewardPct(uint256 pct) external;

    // core job flow

    /// @notice Create a new job specifying reward, deadline and metadata URI
    /// @param reward Amount escrowed as payment for the job
    /// @param deadline Timestamp after which the job expires
    /// @param uri Metadata describing the job
    /// @return jobId Identifier of the newly created job
    function createJob(
        uint256 reward,
        uint64 deadline,
        bytes32 specHash,
        string calldata uri
    ) external returns (uint256 jobId);

    /// @notice Agent expresses interest in a job
    /// @param jobId Identifier of the job to apply for
    /// @param subdomain ENS subdomain label
    /// @param proof Merkle proof for ENS ownership verification
    /// @dev Reverts with {InvalidStatus} if job is not open for applications
    function applyForJob(
        uint256 jobId,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;

    function getSpecHash(uint256 jobId) external view returns (bytes32);

    function burnEvidenceStatus(uint256 jobId)
        external
        view
        returns (bool burnRequired, bool burnSatisfied);

    function submitBurnReceipt(
        uint256 jobId,
        bytes32 burnTxHash,
        uint256 amount,
        uint256 blockNumber
    ) external;

    function hasBurnReceipt(uint256 jobId, bytes32 burnTxHash)
        external
        view
        returns (bool);

    function confirmEmployerBurn(uint256 jobId, bytes32 burnTxHash) external;

    /// @notice Deposit stake and apply for a job in one call
    /// @param jobId Identifier of the job
    /// @param amount Stake amount in $AGIALPHA with 18 decimals
    /// @param subdomain ENS subdomain label
    /// @param proof Merkle proof for ENS ownership verification
    function stakeAndApply(
        uint256 jobId,
        uint256 amount,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;

    /// @notice Acknowledge the tax policy and apply for a job in one call
    /// @param jobId Identifier of the job to apply for
    /// @param subdomain ENS subdomain label
    /// @param proof Merkle proof for ENS ownership verification
    function acknowledgeAndApply(
        uint256 jobId,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;

    /// @notice Agent submits completed work for validation.
    /// @param jobId Identifier of the job being submitted
    /// @param resultHash Hash of the submission
    /// @param resultURI Metadata URI of the submission
    /// @param subdomain ENS subdomain label
    /// @param proof Merkle proof for ENS ownership verification
    function submit(
        uint256 jobId,
        bytes32 resultHash,
        string calldata resultURI,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;

    /// @notice Acknowledge tax policy and submit work in one call
    /// @param jobId Identifier of the job being submitted
    /// @param resultHash Hash of the submission
    /// @param resultURI Metadata URI of the submission
    /// @param subdomain ENS subdomain label
    /// @param proof Merkle proof for ENS ownership verification
    function acknowledgeAndSubmit(
        uint256 jobId,
        bytes32 resultHash,
        string calldata resultURI,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;

    /// @notice Record validation outcome and update job state
    /// @param jobId Identifier of the job being finalised
    /// @param success True if validators approved the job
    function finalizeAfterValidation(uint256 jobId, bool success) external;

    /// @notice Alias for {finalizeAfterValidation} for backwards compatibility
    function validationComplete(uint256 jobId, bool success) external;

    /// @notice Receive validation outcome from the ValidationModule
    /// @param jobId Identifier of the job being validated
    /// @param success True if validators approved the job
    /// @param validators Validators that participated in the round
    function onValidationResult(
        uint256 jobId,
        bool success,
        address[] calldata validators
    ) external;

    /// @notice Force finalize a job when validation quorum is not met
    /// @param jobId Identifier of the job to finalize
    function forceFinalize(uint256 jobId) external;

    /// @notice Raise a dispute for a completed job
    /// @param jobId Identifier of the disputed job
    /// @param evidenceHash Keccak256 hash of off-chain evidence (optional)
    /// @param reason Plain-text description or URI with additional context
    /// @dev Reverts with {InvalidStatus} or {OnlyAgent}
    function dispute(
        uint256 jobId,
        bytes32 evidenceHash,
        string calldata reason
    ) external;

    /// @notice Convenience overload forwarding a hashed evidence payload.
    function raiseDispute(uint256 jobId, bytes32 evidenceHash) external;

    /// @notice Convenience overload for providing a plain-text reason only.
    function raiseDispute(uint256 jobId, string calldata reason) external;

    /// @notice Governance-only escalation helper to move a job into dispute flow.
    function escalateToDispute(uint256 jobId, string calldata reason) external;

    /// @notice Acknowledge tax policy if needed and raise a dispute with evidence
    /// @param jobId Identifier of the disputed job
    /// @param evidenceHash Keccak256 hash of the evidence (optional)
    /// @param reason Plain-text description or URI with supporting details
    function acknowledgeAndDispute(
        uint256 jobId,
        bytes32 evidenceHash,
        string calldata reason
    ) external;

    /// @notice Backwards-compatible helper without a reason parameter.
    function acknowledgeAndDispute(uint256 jobId, bytes32 evidenceHash) external;

    /// @notice Resolve a dispute and record the final outcome
    /// @param jobId Identifier of the disputed job
    /// @param employerWins True if the employer wins the dispute
    /// @dev Reverts with {InvalidJob} if the job does not exist
    function resolveDispute(uint256 jobId, bool employerWins) external;

    /// @notice Finalise a job after dispute resolution or successful validation
    /// @param jobId Identifier of the job to finalise
    /// @dev Reverts with {InvalidStatus} if job is not ready for finalisation
    function finalize(uint256 jobId) external;

    /// @notice Acknowledge tax policy and finalise the job in one call
    /// @param jobId Identifier of the job to finalise
    function acknowledgeAndFinalize(uint256 jobId) external;

    /// @notice Employer cancels a job before an agent is selected
    /// @param jobId Identifier of the job to cancel
    /// @dev Reverts with {OnlyEmployer} or {InvalidStatus}
    function cancelJob(uint256 jobId) external;

    /// @notice Owner can force-cancel an unassigned job
    /// @param jobId Identifier of the job to cancel
    function forceCancel(uint256 jobId) external;

    // view helper

    /// @notice Retrieve information for a given job
    /// @param jobId Identifier of the job to query
    /// @return Job The job struct containing all job details
    function jobs(uint256 jobId) external view returns (Job memory);

    /// @notice Retrieve reputation statistics for an employer.
    /// @param employer Address of the employer.
    /// @return successful Number of successfully finalised jobs.
    /// @return failed Number of failed or disputed jobs.
    function getEmployerReputation(address employer)
        external
        view
        returns (uint256 successful, uint256 failed);

    /// @notice Compute normalized employer score scaled by 1e18.
    function getEmployerScore(address employer) external view returns (uint256 score);
}

contracts/v2/interfaces/IJobRegistryTax.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

import {ITaxPolicy} from "./ITaxPolicy.sol";

/// @title IJobRegistryTax
/// @notice Minimal interface exposing the TaxPolicy reference from JobRegistry
interface IJobRegistryTax {
    /// @notice Returns the TaxPolicy contract storing canonical acknowledgements
    function taxPolicy() external view returns (ITaxPolicy);
}

contracts/v2/interfaces/IRandaoCoordinator.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

interface IRandaoCoordinator {
    /// @notice Commit a hash of the sender address, tag and secret.
    /// @dev Requires prior approval and transfers the $AGIALPHA deposit.
    function commit(bytes32 tag, bytes32 commitment) external;

    /// @notice Reveal the secret for a given tag.
    function reveal(bytes32 tag, uint256 secret) external;

    /// @notice Retrieve aggregated randomness for a tag after reveal window.
    /// @dev The returned value mixes the XORed seed with `block.prevrandao`.
    function random(bytes32 tag) external view returns (uint256);
}

contracts/v2/interfaces/IReputationEngine.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/// @title IReputationEngine
/// @notice Interface for tracking and updating participant reputation scores
interface IReputationEngine {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    /// @dev Reverts when a caller is not authorised to update reputation
    error UnauthorizedCaller(address caller);

    /// @dev Reverts when attempting to act on a blacklisted user
    error BlacklistedUser(address user);
    /// @dev Reverts when array lengths for validator context mismatch
    error ArrayLengthMismatch();

    event ReputationUpdated(address indexed user, int256 delta, uint256 newScore);
    event BlacklistUpdated(address indexed user, bool status);
    event StakeManagerUpdated(address stakeManager);
    event ScoringWeightsUpdated(uint256 stakeWeight, uint256 reputationWeight);

    /// @notice Increase a user's reputation score
    /// @param user Address whose reputation is increased
    /// @param amount Amount to add to the user's score
    /// @dev Reverts with {UnauthorizedCaller} if caller is not permitted
    ///      or {BlacklistedUser} if the user is blacklisted
    function add(address user, uint256 amount) external;

    /// @notice Decrease a user's reputation score
    /// @param user Address whose reputation is decreased
    /// @param amount Amount to subtract from the user's score
    /// @dev Reverts with {UnauthorizedCaller} if caller is not permitted
    ///      or {BlacklistedUser} if the user is blacklisted
    function subtract(address user, uint256 amount) external;

    /// @notice Retrieve a user's reputation score
    /// @param user Address to query
    /// @return The current reputation score of the user
    function reputation(address user) external view returns (uint256);

    /// @notice Alias for {reputation} for backwards compatibility
    function getReputation(address user) external view returns (uint256);

    /// @notice Alternate view to mirror v1 naming
    function reputationOf(address user) external view returns (uint256);

    /// @notice Retrieve accumulated entropy penalties for a user
    /// @param user Address to query
    /// @return The current entropy score of the user
    function entropy(address user) external view returns (uint256);

    /// @notice Alias for {entropy}
    function getEntropy(address user) external view returns (uint256);

    /// @notice Alternate view for legacy naming
    function entropyOf(address user) external view returns (uint256);

    /// @notice Check if a user is blacklisted
    /// @param user Address to query
    /// @return True if the user is blacklisted
    function isBlacklisted(address user) external view returns (bool);

    /// @notice Determine whether a user meets the premium access threshold
    /// @param user Address to query
    /// @return True if the user's reputation meets or exceeds the threshold
    function meetsThreshold(address user) external view returns (bool);

    /// @notice Owner functions

    /// @notice Allow or disallow a caller to update reputation
    /// @param caller Address of the caller to configure
    /// @param allowed True to authorise the caller, false to revoke
    function setCaller(address caller, bool allowed) external;

    /// @notice Backwards compatible alias for {setCaller}
    function setAuthorizedCaller(address caller, bool allowed) external;

    /// @notice Set the minimum score threshold for certain actions
    function setThreshold(uint256 newThreshold) external;

    /// @notice Set premium reputation threshold
    function setPremiumThreshold(uint256 newThreshold) external;

    /// @notice Add or remove a user from the blacklist
    /// @param user Address to update
    /// @param status True to blacklist the user, false to remove
    function setBlacklist(address user, bool status) external;

    /// @notice Job lifecycle hooks
    function onApply(address user) external view;

    function onFinalize(address user, bool success, uint256 payout, uint256 duration) external;

    function rewardValidator(address validator, uint256 agentGain) external;

    /// @notice Update agent and validator reputation for a completed job.
    /// @param jobId Identifier of the job being settled.
    /// @param agent Address of the agent that executed the job.
    /// @param validators Validator committee that assessed the job.
    /// @param success True if the job was approved by validators.
    /// @param validatorRevealed Flags indicating whether each validator revealed their vote.
    /// @param validatorVotes Recorded vote for each validator (true = approval).
    /// @param payout Agent payout expressed with 18 decimals.
    /// @param duration Time elapsed between assignment and completion in seconds.
    function updateScores(
        uint256 jobId,
        address agent,
        address[] calldata validators,
        bool success,
        bool[] calldata validatorRevealed,
        bool[] calldata validatorVotes,
        uint256 payout,
        uint256 duration
    ) external;

    /// @notice Compute reputation gain for an agent based on payout and duration.
    /// @param payout Amount paid to the agent (18-decimal).
    /// @param duration Job duration in seconds.
    /// @return Reputation points awarded to the agent.
    function calculateReputationPoints(uint256 payout, uint256 duration)
        external
        view
        returns (uint256);

    /// @notice Retrieve combined operator score using stake and reputation
    /// @param operator Address to query
    /// @return Weighted score used for ranking
    function getOperatorScore(address operator) external view returns (uint256);

    /// @notice Set the StakeManager used for stake lookups
    /// @param manager Address of the StakeManager contract
    function setStakeManager(address manager) external;

    /// @notice Update weighting factors for stake and reputation contributions
    /// @param stakeWeight Weight applied to stake (scaled by TOKEN_SCALE)
    /// @param reputationWeight Weight applied to reputation (scaled by TOKEN_SCALE)
    function setScoringWeights(uint256 stakeWeight, uint256 reputationWeight) external;
}

contracts/v2/interfaces/IStakeManager.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

import {IFeePool} from "./IFeePool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

/// @title IStakeManager
/// @notice Interface for staking balances, job escrows and slashing logic
interface IStakeManager {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);
    /// @notice participant roles
    enum Role {
        Agent,
        Validator,
        Platform
    }

    event StakeDeposited(address indexed user, Role indexed role, uint256 amount);
    event StakeWithdrawn(address indexed user, Role indexed role, uint256 amount);
    event StakeEscrowLocked(bytes32 indexed jobId, address indexed from, uint256 amount);
    event StakeReleased(bytes32 indexed jobId, address indexed to, uint256 amount);
    event RewardPaid(bytes32 indexed jobId, address indexed to, uint256 amount);
    event TokensBurned(bytes32 indexed jobId, uint256 amount);
    /// @notice Emitted when an employer finalizes a job's funds.
    /// @dev Signals that any subsequent burn events stem from employer action.
    event JobFundsFinalized(bytes32 indexed jobId, address indexed employer);
    /// @notice Emitted when the operator reward pool balance changes.
    event RewardPoolUpdated(uint256 balance);
    event StakeTimeLocked(address indexed user, uint256 amount, uint64 unlockTime);
    event StakeUnlocked(address indexed user, uint256 amount);
    event StakeSlashed(
        address indexed user,
        Role role,
        address indexed employer,
        address indexed treasury,
        uint256 employerShare,
        uint256 treasuryShare,
        uint256 operatorShare,
        uint256 validatorShare,
        uint256 burnShare
    );
    event EscrowPenaltyApplied(
        bytes32 indexed jobId,
        address indexed recipient,
        uint256 amount,
        uint256 employerShare,
        uint256 treasuryShare,
        uint256 operatorShare,
        uint256 validatorShare,
        uint256 burnShare
    );
    /// @notice Emitted when stake is slashed from a participant.
    /// @param agent Address whose stake was reduced.
    /// @param amount Total amount slashed from the agent.
    /// @param validator Address of the validator or recipient that triggered the slash.
    event Slash(address indexed agent, uint256 amount, address indexed validator);

    /// @notice Emitted when a validator receives a reward from slashing.
    /// @param validator Address of the validator being rewarded.
    /// @param amount Amount of tokens transferred to the validator.
    /// @param jobId Optional job identifier associated with the reward.
    event RewardValidator(address indexed validator, uint256 amount, bytes32 indexed jobId);
    event DisputeFeeLocked(address indexed payer, uint256 amount);
    event DisputeFeePaid(address indexed to, uint256 amount);
    event DisputeModuleUpdated(address module);
    event ValidationModuleUpdated(address module);
    event ValidatorLockManagerUpdated(address indexed manager, bool allowed);
    event ValidatorStakeLocked(uint256 indexed jobId, address indexed validator, uint256 amount, uint64 unlockTime);
    event ValidatorStakeUnlocked(uint256 indexed jobId, address indexed validator, uint256 amount);
    event ModulesUpdated(address jobRegistry, address disputeModule);
    event MinStakeUpdated(uint256 minStake);
    event RoleMinimumUpdated(Role indexed role, uint256 minStake);
    event SlashingPercentagesUpdated(uint256 employerSlashPct, uint256 treasurySlashPct);
    event OperatorSlashPctUpdated(uint256 operatorSlashPct);
    event ValidatorSlashRewardPctUpdated(uint256 validatorSlashRewardPct);
    event SlashDistributionUpdated(
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 operatorSlashPct,
        uint256 validatorSlashRewardPct
    );
    event SlashPercentsUpdated(
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 validatorSlashRewardPct,
        uint256 operatorSlashPct,
        uint256 burnSlashPct
    );
    event OperatorSlashShareAllocated(address indexed user, Role indexed role, uint256 amount);
    event TreasuryUpdated(address indexed treasury);
    event TreasuryAllowlistUpdated(address indexed treasury, bool allowed);
    event MaxStakePerAddressUpdated(uint256 maxStake);
    event MaxAGITypesUpdated(uint256 oldMax, uint256 newMax);
    event AGITypeUpdated(address indexed nft, uint256 payoutPct);
    event AGITypeRemoved(address indexed nft);
    event MaxTotalPayoutPctUpdated(uint256 oldMax, uint256 newMax);
    event ParametersUpdated(
        uint256 minStake,
        uint256 employerSlashPct,
        uint256 treasurySlashPct,
        uint256 operatorSlashPct,
        uint256 validatorSlashRewardPct,
        uint256 burnSlashPct,
        uint256 feePct,
        uint256 burnPct,
        uint256 validatorRewardPct
    );
    event AutoStakeTuningEnabled(bool enabled);
    event AutoStakeConfigUpdated(
        uint256 threshold,
        uint256 upPct,
        uint256 downPct,
        uint256 window,
        uint256 floor,
        uint256 ceil,
        int256 tempThreshold,
        int256 hThreshold,
        uint256 disputeWeight,
        uint256 tempWeight,
        uint256 hamWeight
    );
    event ThermostatUpdated(address indexed thermostat);
    event HamiltonianFeedUpdated(address indexed feed);
    event FeePctUpdated(uint256 pct);
    event BurnPctUpdated(uint256 pct);
    event ValidatorRewardPctUpdated(uint256 pct);
    event FeePoolUpdated(address indexed feePool);

    /// @notice deposit stake for caller for a specific role
    /// @param role participant role receiving credit
    /// @param amount token amount with 18 decimals to deposit
    function depositStake(Role role, uint256 amount) external;

    /// @notice acknowledge the tax policy and deposit stake in one call
    function acknowledgeAndDeposit(Role role, uint256 amount) external;

    /// @notice deposit stake on behalf of a user for a specific role
    function depositStakeFor(address user, Role role, uint256 amount) external;

    /// @notice withdraw available stake for a specific role
    /// @param role participant role of the stake being withdrawn
    /// @param amount token amount with 18 decimals to withdraw
    function withdrawStake(Role role, uint256 amount) external;

    /// @notice acknowledge the tax policy and withdraw stake in one call
    function acknowledgeAndWithdraw(Role role, uint256 amount) external;

    /// @notice view the minimum stake override for a role (0 => fallback to global min)
    function roleMinimumStake(Role role) external view returns (uint256);

    /// @notice update minimum stake overrides for all roles
    function setRoleMinimums(uint256 agent, uint256 validator, uint256 platform) external;

    /// @notice update the minimum stake override for a single role
    function setRoleMinimum(Role role, uint256 amount) external;

    /// @notice lock a portion of a user's stake for a period of time
    /// @param user address whose stake is being locked
    /// @param amount token amount with 18 decimals
    /// @param lockTime seconds until the stake unlocks
    function lockStake(address user, uint256 amount, uint64 lockTime) external;

    /// @notice update the allowlist of addresses permitted to manage validator locks
    function setValidatorLockManager(address manager, bool allowed) external;

    /// @notice lock validator stake for a validation round
    /// @param jobId identifier of the job requesting validation
    /// @param user validator address whose stake is being locked
    /// @param amount token amount with 18 decimals
    /// @param lockTime seconds until the stake unlocks
    function lockValidatorStake(uint256 jobId, address user, uint256 amount, uint64 lockTime) external;

    /// @notice lock job reward from an employer
    function lockReward(bytes32 jobId, address from, uint256 amount) external;

    /// @notice generic escrow lock when job ID is managed externally
    function lock(address from, uint256 amount) external;

    /// @notice release locked job reward to recipient
    /// @param jobId unique job identifier
    /// @param employer employer responsible for burns
    /// @param to recipient of the reward
    /// @param amount base token amount with 18 decimals before bonuses
    function releaseReward(
        bytes32 jobId,
        address employer,
        address to,
        uint256 amount,
        bool applyBoost
    ) external;

    /// @notice refund escrowed funds without fees or burns
    function refundEscrow(bytes32 jobId, address to, uint256 amount) external;

    /// @notice redistribute escrowed funds according to the configured slash distribution
    function redistributeEscrow(bytes32 jobId, address recipient, uint256 amount) external;

    /// @notice redistribute escrowed funds with validator weighting
    function redistributeEscrow(
        bytes32 jobId,
        address recipient,
        uint256 amount,
        address[] calldata validators
    ) external;

    /// @notice release previously locked stake for a user
    function releaseStake(address user, uint256 amount) external;

    /// @notice release stake locked for validation
    function unlockValidatorStake(uint256 jobId, address user, uint256 amount) external;

    /// @notice release funds locked via {lock}
    /// @param employer employer responsible for burns
    /// @param to recipient of the tokens
    /// @param amount base token amount with 18 decimals before bonuses
    function release(address employer, address to, uint256 amount, bool applyBoost) external;

    /// @notice finalize job funds by paying agent and forwarding fees
    function finalizeJobFunds(
        bytes32 jobId,
        address employer,
        address agent,
        uint256 reward,
        uint256 validatorReward,
        uint256 fee,
        IFeePool feePool,
        bool byGovernance
    ) external;

    /// @notice finalize job funds with a precomputed payout percentage
    function finalizeJobFundsWithPct(
        bytes32 jobId,
        address employer,
        address agent,
        uint256 agentPct,
        uint256 reward,
        uint256 validatorReward,
        uint256 fee,
        IFeePool feePool,
        bool byGovernance
    ) external;

    /// @notice fund the operator reward pool
    function fundOperatorRewardPool(uint256 amount) external;

    /// @notice withdraw tokens from the operator reward pool
    function withdrawOperatorRewardPool(address to, uint256 amount) external;

    /// @notice distribute validator rewards among selected validators
    ///         weighted by their NFT multipliers
    function distributeValidatorRewards(bytes32 jobId, uint256 amount) external;

    /// @notice Current burn percentage applied to rewards
    function burnPct() external view returns (uint256);

    /// @notice Validator share of slashed stakes
    function validatorSlashRewardPct() external view returns (uint256);

    /// @notice Cap on total payout percentage across AGI types
    function maxTotalPayoutPct() external view returns (uint256);

    /// @notice ERC20 token used for staking operations
    function token() external view returns (IERC20);

    /// @notice current balance of the operator reward pool
    function operatorRewardPool() external view returns (uint256);

    /// @notice set the dispute module authorized to manage dispute fees
    function setDisputeModule(address module) external;

    /// @notice set the validation module used for validator lookups
    function setValidationModule(address module) external;

    /// @notice update job registry and dispute module in one call
    /// @dev Staking is disabled until `jobRegistry` is configured.
    function setModules(address _jobRegistry, address _disputeModule) external;

    /// @notice lock a dispute fee from the payer
    function lockDisputeFee(address payer, uint256 amount) external;

    /// @notice pay out a locked dispute fee to the recipient
    function payDisputeFee(address to, uint256 amount) external;

    /// @notice slash stake from a user for a specific role
    /// @param user address whose stake will be reduced
    /// @param role participant role of the slashed stake
    /// @param amount token amount with 18 decimals to slash
    /// @param employer recipient of the employer share
    function slash(address user, Role role, uint256 amount, address employer) external;
    function slash(
        address user,
        Role role,
        uint256 amount,
        address employer,
        address[] calldata validators
    ) external;

    /// @notice slash validator stake during dispute resolution
    /// @param user address whose stake will be reduced
    /// @param amount token amount with 18 decimals to slash
    /// @param recipient address receiving the slashed share
    function slash(address user, uint256 amount, address recipient) external;
    function slash(
        address user,
        uint256 amount,
        address recipient,
        address[] calldata validators
    ) external;

    function governanceSlash(
        address user,
        Role role,
        uint256 pctBps,
        address beneficiary
    ) external returns (uint256 amount);

    /// @notice owner configuration helpers
    function setMinStake(uint256 _minStake) external;
    function setSlashPercents(
        uint16 employerSlashPct,
        uint16 treasurySlashPct,
        uint16 validatorSlashPct,
        uint16 operatorSlashPct,
        uint16 burnSlashPct
    ) external;

    function setSlashingPercentages(uint256 _employerSlashPct, uint256 _treasurySlashPct) external;
    function setSlashingParameters(uint256 _employerSlashPct, uint256 _treasurySlashPct) external;
    function setValidatorSlashRewardPct(uint256 _validatorSlashPct) external;
    function setSlashingDistribution(
        uint256 _employerSlashPct,
        uint256 _treasurySlashPct,
        uint256 _validatorSlashPct
    ) external;

    function setOperatorSlashPct(uint256 _operatorSlashPct) external;

    function setSlashDistribution(
        uint256 _employerSlashPct,
        uint256 _treasurySlashPct,
        uint256 _operatorSlashPct,
        uint256 _validatorSlashPct
    ) external;
    function setTreasury(address _treasury) external;
    function setTreasuryAllowlist(address _treasury, bool allowed) external;
    function setMaxStakePerAddress(uint256 maxStake) external;
    function setMaxAGITypes(uint256 newMax) external;
    function setMaxTotalPayoutPct(uint256 newMax) external;
    function addAGIType(address nft, uint256 payoutPct) external;
    function removeAGIType(address nft) external;
    function setFeePct(uint256 pct) external;
    function setFeePool(IFeePool pool) external;
    function setBurnPct(uint256 pct) external;
    function setValidatorRewardPct(uint256 pct) external;
    function autoTuneStakes(bool enabled) external;
    function configureAutoStake(
        uint256 threshold,
        uint256 upPct,
        uint256 downPct,
        uint256 window,
        uint256 floor,
        uint256 ceil,
        int256 tempThreshold,
        int256 hThreshold,
        uint256 disputeWeight,
        uint256 tempWeight,
        uint256 hamWeight
    ) external;
    function setThermostat(address thermostat) external;
    function setHamiltonianFeed(address feed) external;
    function recordDispute() external;
    function checkpointStake() external;

    /// @notice return total stake deposited by a user for a role
    function stakeOf(address user, Role role) external view returns (uint256);

    /// @notice return aggregate stake for a role
    function totalStake(Role role) external view returns (uint256);

    /// @notice return aggregate stake weighted by NFT multipliers for a role
    function totalBoostedStake(Role role) external view returns (uint256);

    /// @notice Recalculate boosted stake for a user when NFT holdings change
    /// @param user address whose boosted stake is being updated
    /// @param role participant role of the stake
    function syncBoostedStake(address user, Role role) external;

    /// @notice address of the JobRegistry authorized to deposit fees
    function jobRegistry() external view returns (address);

    /// @notice Total payout percentage for a participant based on AGI type NFTs
    /// @dev Returns 100 when the user holds no approved NFTs.
    function getTotalPayoutPct(address user) external view returns (uint256);
}

contracts/v2/interfaces/ITaxPolicy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/// @title ITaxPolicy
/// @notice Interface for retrieving tax policy details.
interface ITaxPolicy {
    /// @notice Record that the caller has acknowledged the current policy.
    /// @return disclaimer Confirmation text stating the caller bears all tax liability.
    function acknowledge() external returns (string memory disclaimer);

    /// @notice Record that `user` has acknowledged the current policy.
    /// @param user Address of the participant.
    /// @return disclaimer Confirmation text stating the participant bears all tax liability.
    function acknowledgeFor(address user) external returns (string memory disclaimer);

    /// @notice Allow or revoke an acknowledger address.
    /// @dev Only callable by the policy owner.
    /// @param acknowledger Address granted permission to acknowledge for users.
    /// @param allowed True to allow the address, false to revoke.
    function setAcknowledger(address acknowledger, bool allowed) external;

    /// @notice Batch update acknowledger permissions with per-address flags.
    /// @param acknowledgers Array of addresses to update.
    /// @param allowed Boolean flags matching `acknowledgers` by index.
    function setAcknowledgers(address[] calldata acknowledgers, bool[] calldata allowed) external;

    /// @notice Clears the acknowledgement record for a user.
    /// @param user Address whose acknowledgement should be revoked.
    function revokeAcknowledgement(address user) external;

    /// @notice Clears acknowledgement records for multiple users.
    /// @param users Addresses whose acknowledgements should be revoked.
    function revokeAcknowledgements(address[] calldata users) external;

    /// @notice Check if a user has acknowledged the policy.
    /// @param user Address of the participant.
    function hasAcknowledged(address user) external view returns (bool);

    /// @notice Check if an address is authorised to call {acknowledgeFor}.
    /// @param acknowledger Address of the delegate.
    function acknowledgerAllowed(address acknowledger) external view returns (bool);

    /// @notice Returns the policy version a user has acknowledged.
    /// @param user Address of the participant.
    /// @return version Policy version acknowledged by `user`.
    function acknowledgedVersion(address user) external view returns (uint256 version);

    /// @notice Returns the acknowledgement text without recording acceptance.
    /// @return disclaimer Confirms all taxes fall on employers, agents, and validators.
    function acknowledgement() external view returns (string memory disclaimer);

    /// @notice Returns the URI pointing to the canonical policy document.
    /// @return uri Off-chain document location (e.g., IPFS hash).
    function policyURI() external view returns (string memory uri);

    /// @notice Convenience helper returning both acknowledgement and policy URI.
    /// @return ack Plain-text disclaimer confirming participant tax duties.
    /// @return uri Off-chain document location.
    function policyDetails()
        external
        view
        returns (string memory ack, string memory uri);

    /// @notice Current version number of the policy text.
    function policyVersion() external view returns (uint256);

    /// @notice Increments the policy version without changing text or URI.
    function bumpPolicyVersion() external;

    /// @notice Indicates that the contract and its owner hold no tax liability.
    /// @return Always true; the infrastructure is perpetually tax‑exempt.
    function isTaxExempt() external pure returns (bool);
}

contracts/v2/interfaces/IValidationModule.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

/// @title IValidationModule
/// @notice Interface for validator selection and commit-reveal voting
interface IValidationModule {
    /// @notice Module version for compatibility checks.
    function version() external view returns (uint256);

    enum SelectionStrategy {
        Rotating,
        Reservoir
    }

    enum FailoverAction {
        None,
        ExtendReveal,
        EscalateDispute
    }
    event ValidatorsSelected(uint256 indexed jobId, address[] validators);
    event ValidationCommitted(
        uint256 indexed jobId,
        address indexed validator,
        bytes32 commitHash,
        string subdomain
    );
    event ValidationRevealed(
        uint256 indexed jobId,
        address indexed validator,
        bool approve,
        bytes32 burnTxHash,
        string subdomain
    );
    event ValidationTallied(
        uint256 indexed jobId,
        bool success,
        uint256 approvals,
        uint256 rejections
    );
    event ValidationResult(uint256 indexed jobId, bool success);
    event ValidationQuorumFailed(
        uint256 indexed jobId,
        uint256 revealed,
        uint256 quorumTarget
    );
    event ValidationFailover(
        uint256 indexed jobId,
        FailoverAction action,
        uint256 newRevealDeadline,
        string reason
    );
    event ValidatorSubdomainUpdated(address indexed validator, string subdomain);
    event SelectionStrategyUpdated(SelectionStrategy strategy);
    event ParametersUpdated(
        uint256 committeeSize,
        uint256 commitWindow,
        uint256 revealWindow,
        uint256 approvalThreshold,
        uint256 slashingPct
    );

    /// @notice Select validators for a given job.
    /// @param jobId Identifier of the job.
    /// @param entropy Optional caller-provided entropy mixed with on-chain data.
    /// @return Array of selected validator addresses.
    function selectValidators(uint256 jobId, uint256 entropy)
        external
        returns (address[] memory);

    /// @notice Start validation for a job and select validators
    /// @param jobId Identifier of the job
    /// @param entropy Caller-provided entropy mixed with on-chain sources
    /// @return validators Array of selected validator addresses
    function start(
        uint256 jobId,
        uint256 entropy
    ) external returns (address[] memory validators);

    /// @notice Commit a validation hash for a job
    /// @param jobId Identifier of the job being voted on
    /// @param commitHash Hash of the vote and salt
    /// @param subdomain ENS subdomain label used for ownership verification
    /// @param proof Merkle proof validating the subdomain
    function commitValidation(
        uint256 jobId,
        bytes32 commitHash,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;


    /// @notice Reveal a previously committed validation vote
    /// @param jobId Identifier of the job
    /// @param approve True to approve, false to reject
    /// @param salt Salt used in the original commitment
    /// @param subdomain ENS subdomain label used for ownership verification
    /// @param proof Merkle proof validating the subdomain
    function revealValidation(
        uint256 jobId,
        bool approve,
        bytes32 burnTxHash,
        bytes32 salt,
        string calldata subdomain,
        bytes32[] calldata proof
    ) external;


    /// @notice Finalize validation round and slash incorrect validators
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function finalize(uint256 jobId) external returns (bool success);

    /// @notice Alias for finalize using legacy naming.
    function finalizeValidation(uint256 jobId) external returns (bool success);

    /// @notice Force finalize after the reveal deadline plus grace period
    /// @param jobId Identifier of the job
    /// @return success True if validators approved the job
    function forceFinalize(uint256 jobId) external returns (bool success);


    /// @notice Execute a circuit-breaker style failover for an in-flight validation round.
    /// @param jobId Identifier of the job in question.
    /// @param action Failover action (extend the reveal window or escalate to dispute).
    /// @param extension Additional seconds added to the reveal window when extending.
    /// @param reason Human readable reason emitted for transparency.
    function triggerFailover(
        uint256 jobId,
        FailoverAction action,
        uint64 extension,
        string calldata reason
    ) external;


    /// @notice Batch update core validation parameters
    /// @param committeeSize Number of validators selected per job
    /// @param commitWindow Duration of commit phase in seconds
    /// @param revealWindow Duration of reveal phase in seconds
    /// @param approvalThreshold Percentage of stake required for approval
    /// @param slashingPct Percentage of stake slashed for incorrect votes
    function setParameters(
        uint256 committeeSize,
        uint256 commitWindow,
        uint256 revealWindow,
        uint256 approvalThreshold,
        uint256 slashingPct
    ) external;

    /// @notice Set the number of validators selected per job.
    function setValidatorsPerJob(uint256 count) external;

    /// @notice Owner configuration for timing windows
    function setCommitRevealWindows(uint256 commitWindow, uint256 revealWindow) external;

    /// @notice Convenience wrapper for timing configuration.
    function setTiming(uint256 commitWindow, uint256 revealWindow) external;

    /// @notice Owner configuration for validator counts
    function setValidatorBounds(uint256 minValidators, uint256 maxValidators) external;

    /// @notice Set the required number of validator approvals.
    function setRequiredValidatorApprovals(uint256 count) external;

    /// @notice Reset the validation nonce for a job after it is finalized or disputed
    /// @param jobId Identifier of the job
    function resetJobNonce(uint256 jobId) external;

    /// @notice Update approval threshold percentage
    function setApprovalThreshold(uint256 pct) external;

    /// @notice Toggle automatic tracking of the supermajority approval target.
    function setAutoApprovalTarget(bool enabled) external;

    /// @notice Update percentage of stake slashed for incorrect validator votes
    function setValidatorSlashingPct(uint256 pct) external;

    /// @notice Configure the penalty applied when validators fail to reveal.
    function setNonRevealPenalty(uint256 penaltyBps, uint256 banBlocks) external;

    /// @notice Update quorum requirements for validator reveals.
    function setRevealQuorum(uint256 pct, uint256 minValidators) external;

    /// @notice Update the cool-off delay before early finalization is permitted.
    function setEarlyFinalizeDelay(uint256 delay) external;

    /// @notice Update the force finalize grace period after the reveal window.
    function setForceFinalizeGrace(uint256 grace) external;

    /// @notice Map validators to ENS subdomains for selection
    function setValidatorSubdomains(
        address[] calldata accounts,
        string[] calldata subdomains
    ) external;

    /// @notice Map the caller to an ENS subdomain for selection.
    function setMySubdomain(string calldata subdomain) external;

    /// @notice Configure the validator sampling strategy.
    function setSelectionStrategy(SelectionStrategy strategy) external;

    /// @notice Invalidate all cached validator authorizations.
    function bumpValidatorAuthCacheVersion() external;


    /// @notice Return validators selected for a job
    /// @param jobId Identifier of the job
    /// @return validators Array of validator addresses
    function validators(uint256 jobId) external view returns (address[] memory validators);

    /// @notice Retrieve a validator's vote outcome for a job
    /// @param jobId Identifier of the job
    /// @param validator Address of the validator
    /// @return approved True if the validator approved the job
    function votes(
        uint256 jobId,
        address validator
    ) external view returns (bool approved);

    function failoverStates(uint256 jobId)
        external
        view
        returns (
            FailoverAction action,
            uint64 extensions,
            uint64 lastExtendedTo,
            uint64 lastTriggeredAt,
            bool escalated
        );
}

contracts/v2/libraries/TaxAcknowledgement.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.25;

import {ITaxPolicy} from "../interfaces/ITaxPolicy.sol";

abstract contract TaxAcknowledgement {
    error TaxPolicyNotAcknowledged(address account);

    modifier requiresTaxAcknowledgement(
        ITaxPolicy policy,
        address account,
        address owner,
        address exempt1,
        address exempt2
    ) {
        if (
            account != owner &&
            account != exempt1 &&
            account != exempt2 &&
            address(policy) != address(0)
        ) {
            if (!policy.hasAcknowledged(account)) {
                revert TaxPolicyNotAcknowledged(account);
            }
        }
        _;
    }
}
Настройки компилятораПоказать
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun"
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.