Skip to content
Verified contractExactMIT

ModuleRegistry

Address0x517a0c785ebda93e9ded4f0cab1477a2b161cc2c
Balance

0 ETH

 

Transactions

15

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,848,356
Creation transaction
0x63264dcc32…4c5373e6b7

src/sandbox/ModuleRegistry.sol

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

/*//////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   ░█░█░█▀█░█▀█░█░█░░░█▀▄░█░█░█▀█░▀█▀░▀█▀░█▄█░█▀▀                            //
//   ░█▀█░█░█░█░█░█▀▄░░░█▀▄░█░█░█░█░░█░░░█░░█░█░█▀▀                            //
//   ░▀░▀░▀▀▀░▀▀▀░▀░▀░░░▀░▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░▀▀▀                            //
//                                                                            //
//   Sandboxed module runtime for Uniswap V4 hooks                            //
//                                                                            //
//   web ............ https://evh.one                                         //
//   x .............. https://x.com/VirtualHookETH                            //
//                                                                            //
//////////////////////////////////////////////////////////////////////////////*/

import {Owned} from "../utils/Owned.sol";
import {IModuleRegistry, IBytecodeValidator, IPermissionManager, IStakingVault} from "../interfaces/IProtocol.sol";
import {IModule} from "../interfaces/IModule.sol";
import {Manifest, ModuleStatus, HookMask, Capabilities} from "../types/Types.sol";

/// @title ModuleRegistry
/// @notice The sandbox's process table.
///
///         Registration is permissionless but not free: the developer must have
///         EVH staked, the module's bytecode must pass the validator's opcode
///         scan, and the on-chain `manifest()` must match every value declared in
///         the registration call. That last check is what makes the registry's
///         data trustworthy — a module cannot advertise a 30k gas cap here and
///         behave like a 3M one.
///
///         Attachment is separate from registration. A registered module does
///         nothing until it is placed in a pool's queue for a specific hook
///         point at a specific priority. Queues are kept sorted on insert and
///         bounded at MAX_QUEUE, so the Executor's read path is a single
///         contiguous array with no sorting at execution time.
///
///         Strikes are the failure accounting: three reverts and the module is
///         removed from every queue and its backing stake slashed.
contract ModuleRegistry is Owned, IModuleRegistry {
    using HookMask for uint16;

    // --------------------------------------------------------------- constants
    uint256 public constant MAX_QUEUE = 16;
    uint8 public constant MAX_STRIKES = 3;
    uint32 public constant MIN_MODULE_GAS = 5_000;
    uint32 public constant MAX_MODULE_GAS = 2_000_000;

    // ------------------------------------------------------------ dependencies
    IBytecodeValidator public validator;
    IPermissionManager public permissions;
    IStakingVault public stakingVault;

    /// @notice Contracts allowed to record executions / issue strikes (Executor).
    mapping(address => bool) public isExecutor;
    /// @notice Addresses allowed to attach/detach modules on a given pool.
    mapping(bytes32 => mapping(address => bool)) public isPoolAdmin;
    /// @notice The kernel, which registers pools as they are initialized.
    address public kernel;

    // ------------------------------------------------------------------ state
    mapping(bytes32 => ModuleInfo) internal _modules;
    mapping(bytes32 => string) internal _names;
    mapping(bytes32 => string) internal _versions;
    mapping(bytes32 => string) internal _sourceURIs;
    mapping(address => bytes32) public override moduleIdOf;
    bytes32[] internal _moduleIds;

    /// @dev poolId => hookPoint => sorted queue
    mapping(bytes32 => mapping(uint8 => QueueEntry[])) internal _queue;
    /// @dev poolId => moduleId => hookPoint => attached
    mapping(bytes32 => mapping(bytes32 => mapping(uint8 => bool))) public isAttached;
    /// @dev moduleId => list of pools it is attached to (deduped)
    mapping(bytes32 => bytes32[]) internal _attachedPools;
    mapping(bytes32 => mapping(bytes32 => bool)) internal _attachedPoolKnown;

    /// @notice Minimum EVH the developer must have staked to register.
    uint256 public minDeveloperStake = 1_000e18;
    /// @notice Basis points of the module's backing stake burned per slash.
    uint256 public slashBps = 5_000;

    // ----------------------------------------------------------------- events
    event ModuleRegistered(
        bytes32 indexed moduleId,
        address indexed module,
        address indexed developer,
        string name,
        string version,
        uint16 hookMask,
        uint32 gasLimit
    );
    event ModuleStatusChanged(bytes32 indexed moduleId, uint8 oldStatus, uint8 newStatus);
    event ModuleAttached(bytes32 indexed poolId, bytes32 indexed moduleId, uint8 hookPoint, uint16 priority);
    event ModuleDetached(bytes32 indexed poolId, bytes32 indexed moduleId, uint8 hookPoint);
    event ModuleStriked(bytes32 indexed moduleId, uint8 strikes, bytes revertData);
    event ModuleSourceUpdated(bytes32 indexed moduleId, string sourceURI);
    event PoolAdminSet(bytes32 indexed poolId, address indexed admin, bool allowed);
    event ExecutorSet(address indexed executor, bool allowed);
    event RegistryParamsSet(uint256 minDeveloperStake, uint256 slashBps);

    // ----------------------------------------------------------------- errors
    error ModuleAlreadyRegistered();
    error InvalidHookMask();
    error InvalidGasLimit();
    error ManifestMismatch();
    error InsufficientStake(uint256 have, uint256 need);
    error NotModuleDeveloper();
    error NotExecutor();
    error NotPoolAdmin();
    error ModuleNotActive();
    error ModuleIsBanned();
    error HookPointNotSubscribed();
    error QueueFull();
    error PriorityTaken();
    error AlreadyAttached();
    error NotAttached();
    error InvalidHookPoint();

    modifier onlyExecutor() {
        if (!isExecutor[msg.sender]) revert NotExecutor();
        _;
    }

    modifier onlyPoolAdmin(bytes32 poolId) {
        if (!isPoolAdmin[poolId][msg.sender] && msg.sender != owner) revert NotPoolAdmin();
        _;
    }

    constructor(address _owner, address _validator, address _permissions) Owned(_owner) {
        validator = IBytecodeValidator(_validator);
        permissions = IPermissionManager(_permissions);
    }

    // ------------------------------------------------------------------ admin

    function setDependencies(address _validator, address _permissions, address _stakingVault, address _kernel)
        external
        onlyOwner
    {
        if (_validator != address(0)) validator = IBytecodeValidator(_validator);
        if (_permissions != address(0)) permissions = IPermissionManager(_permissions);
        if (_stakingVault != address(0)) stakingVault = IStakingVault(_stakingVault);
        if (_kernel != address(0)) kernel = _kernel;
    }

    function setExecutor(address executor, bool allowed) external onlyOwner {
        isExecutor[executor] = allowed;
        emit ExecutorSet(executor, allowed);
    }

    function setPoolAdmin(bytes32 poolId, address admin, bool allowed) external onlyOwner {
        isPoolAdmin[poolId][admin] = allowed;
        emit PoolAdminSet(poolId, admin, allowed);
    }

    function setParams(uint256 _minDeveloperStake, uint256 _slashBps) external onlyOwner {
        require(_slashBps <= 10_000, "bps");
        minDeveloperStake = _minDeveloperStake;
        slashBps = _slashBps;
        emit RegistryParamsSet(_minDeveloperStake, _slashBps);
    }

    // ----------------------------------------------------------- registration

    /// @notice Register a deployed module into the sandbox.
    /// @dev    Every declared field is cross-checked against the module's own
    ///         `manifest()`. Registration grants only unprivileged capabilities;
    ///         privileged ones are recorded as requested and await promotion.
    function register(
        address module,
        string calldata name,
        string calldata version,
        uint16 hookMask,
        uint32 gasLimit,
        uint8 capabilities,
        string calldata sourceURI
    ) external returns (bytes32 moduleId) {
        moduleId = computeModuleId(module);
        if (_modules[moduleId].module != address(0)) revert ModuleAlreadyRegistered();

        if (!hookMask.isValid()) revert InvalidHookMask();
        if (gasLimit < MIN_MODULE_GAS || gasLimit > MAX_MODULE_GAS) revert InvalidGasLimit();

        // Developer must have skin in the game before code is admitted.
        if (address(stakingVault) != address(0) && minDeveloperStake != 0) {
            uint256 staked = stakingVault.stakedOf(msg.sender);
            if (staked < minDeveloperStake) revert InsufficientStake(staked, minDeveloperStake);
        }

        // Opcode scan. Reverts with the exact opcode and byte offset.
        validator.assertValid(module);

        // The module must describe itself the same way the developer describes it.
        Manifest memory m = IModule(module).manifest();
        if (
            m.hookMask != hookMask || m.gasLimit != gasLimit || m.capabilities != capabilities
                || keccak256(bytes(m.name)) != keccak256(bytes(name))
                || keccak256(bytes(m.version)) != keccak256(bytes(version))
        ) revert ManifestMismatch();

        _modules[moduleId] = ModuleInfo({
            module: module,
            developer: msg.sender,
            codeHash: module.codehash,
            hookMask: hookMask,
            gasLimit: gasLimit,
            capabilities: capabilities,
            status: ModuleStatus.Sandboxed,
            strikes: 0,
            registeredAt: uint64(block.timestamp),
            executions: 0,
            failures: 0,
            gasConsumed: 0
        });
        _names[moduleId] = name;
        _versions[moduleId] = version;
        _sourceURIs[moduleId] = sourceURI;
        moduleIdOf[module] = moduleId;
        _moduleIds.push(moduleId);

        permissions.onRegister(moduleId, capabilities);

        emit ModuleRegistered(moduleId, module, msg.sender, name, version, hookMask, gasLimit);
        emit ModuleStatusChanged(moduleId, uint8(ModuleStatus.Unregistered), uint8(ModuleStatus.Sandboxed));
    }

    function computeModuleId(address module) public pure returns (bytes32) {
        return keccak256(abi.encodePacked("token.module", module));
    }

    function setSourceURI(bytes32 moduleId, string calldata sourceURI) external {
        if (_modules[moduleId].developer != msg.sender) revert NotModuleDeveloper();
        _sourceURIs[moduleId] = sourceURI;
        emit ModuleSourceUpdated(moduleId, sourceURI);
    }

    // -------------------------------------------------------------- lifecycle

    /// @notice Governance promotion: unlocks privileged capabilities.
    function promote(bytes32 moduleId) external onlyOwner {
        ModuleInfo storage info = _modules[moduleId];
        if (info.status == ModuleStatus.Banned) revert ModuleIsBanned();
        _setStatus(moduleId, ModuleStatus.Promoted);
        permissions.onPromote(moduleId);
    }

    /// @notice Pause a module. The developer may pause their own; the owner any.
    function pause(bytes32 moduleId) external {
        ModuleInfo storage info = _modules[moduleId];
        if (msg.sender != info.developer && msg.sender != owner) revert NotModuleDeveloper();
        _setStatus(moduleId, ModuleStatus.Paused);
    }

    function resume(bytes32 moduleId) external {
        ModuleInfo storage info = _modules[moduleId];
        if (msg.sender != info.developer && msg.sender != owner) revert NotModuleDeveloper();
        if (info.status != ModuleStatus.Paused) revert ModuleNotActive();
        _setStatus(moduleId, ModuleStatus.Sandboxed);
    }

    function ban(bytes32 moduleId) external onlyOwner {
        _setStatus(moduleId, ModuleStatus.Banned);
        permissions.onRevokeAll(moduleId);
    }

    function _setStatus(bytes32 moduleId, ModuleStatus next) internal {
        ModuleInfo storage info = _modules[moduleId];
        uint8 prev = uint8(info.status);
        info.status = next;
        emit ModuleStatusChanged(moduleId, prev, uint8(next));
    }

    // -------------------------------------------------------------- attaching

    /// @notice Place a module in a pool's queue for one hook point.
    /// @param priority Lower runs first. Must be unused in that queue.
    function attach(bytes32 poolId, bytes32 moduleId, uint8 hookPoint, uint16 priority)
        external
        onlyPoolAdmin(poolId)
    {
        if (hookPoint > 7) revert InvalidHookPoint();
        ModuleInfo memory info = _modules[moduleId];
        if (info.module == address(0)) revert ModuleNotActive();
        if (info.status == ModuleStatus.Banned || info.status == ModuleStatus.Slashed) revert ModuleIsBanned();
        if (!info.hookMask.subscribed(hookPoint)) revert HookPointNotSubscribed();
        if (isAttached[poolId][moduleId][hookPoint]) revert AlreadyAttached();

        QueueEntry[] storage q = _queue[poolId][hookPoint];
        if (q.length >= MAX_QUEUE) revert QueueFull();

        // Find the sorted insert position; reject duplicate priorities so the
        // execution order is a total order and never depends on insert history.
        uint256 pos = q.length;
        for (uint256 i; i < q.length; ++i) {
            if (q[i].priority == priority) revert PriorityTaken();
            if (q[i].priority > priority && i < pos) pos = i;
        }

        q.push(QueueEntry({moduleId: bytes32(0), module: address(0), priority: 0, gasLimit: 0}));
        for (uint256 i = q.length - 1; i > pos; --i) {
            q[i] = q[i - 1];
        }
        q[pos] =
            QueueEntry({moduleId: moduleId, module: info.module, priority: priority, gasLimit: info.gasLimit});

        isAttached[poolId][moduleId][hookPoint] = true;
        if (!_attachedPoolKnown[moduleId][poolId]) {
            _attachedPoolKnown[moduleId][poolId] = true;
            _attachedPools[moduleId].push(poolId);
        }

        emit ModuleAttached(poolId, moduleId, hookPoint, priority);
    }

    function detach(bytes32 poolId, bytes32 moduleId, uint8 hookPoint) external onlyPoolAdmin(poolId) {
        _detach(poolId, moduleId, hookPoint);
    }

    function _detach(bytes32 poolId, bytes32 moduleId, uint8 hookPoint) internal {
        if (!isAttached[poolId][moduleId][hookPoint]) revert NotAttached();
        QueueEntry[] storage q = _queue[poolId][hookPoint];
        uint256 n = q.length;
        for (uint256 i; i < n; ++i) {
            if (q[i].moduleId == moduleId) {
                for (uint256 j = i; j + 1 < n; ++j) {
                    q[j] = q[j + 1];
                }
                q.pop();
                break;
            }
        }
        isAttached[poolId][moduleId][hookPoint] = false;
        emit ModuleDetached(poolId, moduleId, hookPoint);
    }

    /// @notice Remove a module from every queue it sits in. Used on slashing.
    function detachAll(bytes32 moduleId) public {
        if (!isExecutor[msg.sender] && msg.sender != owner) revert NotExecutor();
        bytes32[] memory pools = _attachedPools[moduleId];
        for (uint256 p; p < pools.length; ++p) {
            for (uint8 h; h < 8; ++h) {
                if (isAttached[pools[p]][moduleId][h]) {
                    _detach(pools[p], moduleId, h);
                }
            }
        }
    }

    // ------------------------------------------------------------- accounting

    /// @notice Called by the Executor after every frame, success or failure.
    function recordExecution(bytes32 moduleId, uint256 gasUsed, bool success) external override onlyExecutor {
        ModuleInfo storage info = _modules[moduleId];
        unchecked {
            info.executions += 1;
            info.gasConsumed += gasUsed;
            if (!success) info.failures += 1;
        }
    }

    /// @notice Called by the Executor when a module reverts. Three strikes and
    ///         the module is slashed and pulled from every queue.
    function strike(bytes32 moduleId, bytes calldata revertData) external override onlyExecutor {
        ModuleInfo storage info = _modules[moduleId];
        if (info.status == ModuleStatus.Slashed || info.status == ModuleStatus.Banned) return;

        unchecked {
            info.strikes += 1;
        }
        emit ModuleStriked(moduleId, info.strikes, revertData);

        if (info.strikes >= MAX_STRIKES) {
            _setStatus(moduleId, ModuleStatus.Slashed);
            permissions.onRevokeAll(moduleId);
            detachAll(moduleId);
            if (address(stakingVault) != address(0)) {
                // Never let a slashing failure block the swap path.
                try stakingVault.slash(moduleId, slashBps, "three strikes in sandbox") {} catch {}
            }
        }
    }

    /// @notice Governance can forgive strikes on a module that has been fixed.
    function clearStrikes(bytes32 moduleId) external onlyOwner {
        _modules[moduleId].strikes = 0;
        if (_modules[moduleId].status == ModuleStatus.Slashed) {
            _setStatus(moduleId, ModuleStatus.Sandboxed);
        }
    }

    // ----------------------------------------------------------------- views

    function getModule(bytes32 moduleId) external view override returns (ModuleInfo memory) {
        return _modules[moduleId];
    }

    function getManifest(bytes32 moduleId)
        external
        view
        override
        returns (string memory name, string memory version, string memory sourceURI)
    {
        return (_names[moduleId], _versions[moduleId], _sourceURIs[moduleId]);
    }

    function isActive(bytes32 moduleId) public view override returns (bool) {
        ModuleStatus s = _modules[moduleId].status;
        return s == ModuleStatus.Sandboxed || s == ModuleStatus.Promoted;
    }

    /// @notice The Executor's read path: the active, sorted queue for one hook
    ///         point. Inactive modules are filtered here so the VM never has to
    ///         branch on status.
    function executionPlan(bytes32 poolId, uint8 hookPoint)
        external
        view
        override
        returns (QueueEntry[] memory plan)
    {
        QueueEntry[] storage q = _queue[poolId][hookPoint];
        uint256 n = q.length;
        QueueEntry[] memory buf = new QueueEntry[](n);
        uint256 k;
        for (uint256 i; i < n; ++i) {
            if (isActive(q[i].moduleId)) {
                buf[k] = q[i];
                unchecked {
                    ++k;
                }
            }
        }
        plan = new QueueEntry[](k);
        for (uint256 i; i < k; ++i) {
            plan[i] = buf[i];
        }
    }

    /// @notice Full queue including inactive entries — for the pool dashboard.
    function fullQueue(bytes32 poolId, uint8 hookPoint) external view returns (QueueEntry[] memory) {
        return _queue[poolId][hookPoint];
    }

    function queueLength(bytes32 poolId, uint8 hookPoint) external view override returns (uint256) {
        return _queue[poolId][hookPoint].length;
    }

    /// @notice Queue depth across all eight hook points in one call.
    function queueDepths(bytes32 poolId) external view returns (uint256[8] memory depths, uint256 total) {
        for (uint8 h; h < 8; ++h) {
            depths[h] = _queue[poolId][h].length;
            total += depths[h];
        }
    }

    function attachedPools(bytes32 moduleId) external view returns (bytes32[] memory) {
        return _attachedPools[moduleId];
    }

    function moduleCount() external view override returns (uint256) {
        return _moduleIds.length;
    }

    function moduleIdAt(uint256 index) external view returns (bytes32) {
        return _moduleIds[index];
    }

    /// @notice Paginated listing so the frontend never loops N single calls.
    function listModules(uint256 offset, uint256 limit)
        external
        view
        returns (bytes32[] memory ids, ModuleInfo[] memory infos)
    {
        uint256 total = _moduleIds.length;
        if (offset >= total) return (new bytes32[](0), new ModuleInfo[](0));
        uint256 end = offset + limit;
        if (end > total) end = total;
        uint256 n = end - offset;
        ids = new bytes32[](n);
        infos = new ModuleInfo[](n);
        for (uint256 i; i < n; ++i) {
            ids[i] = _moduleIds[offset + i];
            infos[i] = _modules[ids[i]];
        }
    }

    /// @notice Names/versions for a page of modules, fetched separately because
    ///         strings do not pack into the struct cheaply.
    function listMetadata(bytes32[] calldata ids)
        external
        view
        returns (string[] memory names, string[] memory versions, string[] memory sourceURIs)
    {
        names = new string[](ids.length);
        versions = new string[](ids.length);
        sourceURIs = new string[](ids.length);
        for (uint256 i; i < ids.length; ++i) {
            names[i] = _names[ids[i]];
            versions[i] = _versions[ids[i]];
            sourceURIs[i] = _sourceURIs[ids[i]];
        }
    }
}

src/interfaces/IModule.sol

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

/*//////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   ░█░█░█▀█░█▀█░█░█░░░█▀▄░█░█░█▀█░▀█▀░▀█▀░█▄█░█▀▀                            //
//   ░█▀█░█░█░█░█░█▀▄░░░█▀▄░█░█░█░█░░█░░░█░░█░█░█▀▀                            //
//   ░▀░▀░▀▀▀░▀▀▀░▀░▀░░░▀░▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░▀▀▀                            //
//                                                                            //
//   Sandboxed module runtime for Uniswap V4 hooks                            //
//                                                                            //
//   web ............ https://evh.one                                         //
//   x .............. https://x.com/VirtualHookETH                            //
//                                                                            //
//////////////////////////////////////////////////////////////////////////////*/

import {ExecContext, Manifest} from "../types/Types.sol";

/// @title IModule
/// @notice The entire surface a sandbox module must implement.
/// @dev    Two functions. That is the whole userspace ABI. `manifest()` is read
///         at registration and must be `pure`/`view`; `execute()` is called by
///         the Executor inside a hard gas cap with reverts caught.
interface IModule {
    /// @notice Self-describing metadata. Must match the values passed to
    ///         `ModuleRegistry.register` or registration reverts.
    function manifest() external view returns (Manifest memory);

    /// @notice Called once per subscribed hook point per pool operation.
    /// @param ctx Read-only view of the pool, the caller and the hook payload.
    /// @return returnData Opaque bytes. May carry a tagged fee proposal — see
    ///         `ModuleReturn`. Recorded in the trace either way.
    function execute(ExecContext calldata ctx) external returns (bytes memory returnData);
}

src/interfaces/IProtocol.sol

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

/*//////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   ░█░█░█▀█░█▀█░█░█░░░█▀▄░█░█░█▀█░▀█▀░▀█▀░█▄█░█▀▀                            //
//   ░█▀█░█░█░█░█░█▀▄░░░█▀▄░█░█░█░█░░█░░░█░░█░█░█▀▀                            //
//   ░▀░▀░▀▀▀░▀▀▀░▀░▀░░░▀░▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░▀▀▀                            //
//                                                                            //
//   Sandboxed module runtime for Uniswap V4 hooks                            //
//                                                                            //
//   web ............ https://evh.one                                         //
//   x .............. https://x.com/VirtualHookETH                            //
//                                                                            //
//////////////////////////////////////////////////////////////////////////////*/

import {ExecContext, Manifest, ModuleStatus} from "../types/Types.sol";

interface IBytecodeValidator {
    error ForbiddenOpcode(uint8 opcode, uint256 offset);
    error EmptyBytecode();
    error CodeTooLarge(uint256 size);

    function validate(address target) external view returns (bool ok, uint8 opcode, uint256 offset);
    function assertValid(address target) external view;
    function isForbidden(uint8 opcode) external view returns (bool);
    function forbiddenOpcodes() external view returns (uint8[] memory);
}

interface IPermissionManager {
    error CapabilityDenied(bytes32 moduleId, uint8 capability);
    error TargetNotAllowlisted(address target);

    function capabilitiesOf(bytes32 moduleId) external view returns (uint8);
    function requestedOf(bytes32 moduleId) external view returns (uint8);
    function has(bytes32 moduleId, uint8 capability) external view returns (bool);
    function assertCapability(bytes32 moduleId, uint8 capability) external view;
    function isAllowlistedTarget(address target) external view returns (bool);
    function onRegister(bytes32 moduleId, uint8 requested) external;
    function onPromote(bytes32 moduleId) external;
    function onRevokeAll(bytes32 moduleId) external;
}

interface IGasMeter {
    function available(bytes32 moduleId) external view returns (uint256);
    function budgetOf(bytes32 moduleId) external view returns (uint256);
    function consume(bytes32 moduleId, uint256 gasUsed) external returns (uint256 remaining);
    function currentEpoch() external view returns (uint64);
    function epochEndsAt() external view returns (uint64);
}

interface IModuleStorage {
    error NotActiveModule();
    error QuotaExceeded(bytes32 moduleId, uint256 quota);

    function beginFrame(bytes32 moduleId, address module, uint8 capabilities) external;
    function endFrame() external;
    function sstore(bytes32 key, bytes32 value) external;
    function sload(bytes32 moduleId, bytes32 key) external view returns (bytes32);
    function slotsUsed(bytes32 moduleId) external view returns (uint256);
    function quotaOf(bytes32 moduleId) external view returns (uint256);
    function frameWrites() external view returns (bytes32[] memory keys, bytes32[] memory before_, bytes32[] memory after_);
}

interface IModuleRegistry {
    struct ModuleInfo {
        address module;
        address developer;
        bytes32 codeHash;
        uint16 hookMask;
        uint32 gasLimit;
        uint8 capabilities;
        ModuleStatus status;
        uint8 strikes;
        uint64 registeredAt;
        uint256 executions;
        uint256 failures;
        uint256 gasConsumed;
    }

    struct QueueEntry {
        bytes32 moduleId;
        address module;
        uint16 priority;
        uint32 gasLimit;
    }

    function moduleIdOf(address module) external view returns (bytes32);
    function getModule(bytes32 moduleId) external view returns (ModuleInfo memory);
    function getManifest(bytes32 moduleId) external view returns (string memory name, string memory version, string memory sourceURI);
    function isActive(bytes32 moduleId) external view returns (bool);
    function executionPlan(bytes32 poolId, uint8 hookPoint) external view returns (QueueEntry[] memory);
    function queueLength(bytes32 poolId, uint8 hookPoint) external view returns (uint256);
    function recordExecution(bytes32 moduleId, uint256 gasUsed, bool success) external;
    function strike(bytes32 moduleId, bytes calldata revertData) external;
    function moduleCount() external view returns (uint256);
}

interface IExecutor {
    struct RunResult {
        uint256 modulesRun;
        uint256 modulesFailed;
        uint256 sandboxGas;
        uint24 proposedFee;
        bool feeProposed;
    }

    function execute(ExecContext memory ctx, uint256 gasBudget) external returns (RunResult memory);
    function executeSingle(bytes32 moduleId, ExecContext memory ctx) external returns (bool success, bytes memory ret, uint256 gasUsed);
}

interface IExecutionScheduler {
    struct Task {
        bytes32 moduleId;
        bytes32 poolId;
        uint64 executeAfter;
        uint32 gasCap;
        bool cancelled;
        bool executed;
        bytes payload;
    }

    function schedule(bytes32 poolId, uint64 executeAfter, uint32 gasCap, bytes calldata payload) external returns (uint256 taskId);
    function cancel(uint256 taskId) external;
    function runDue(bytes32 poolId, uint256 maxTasks, uint256 gasBudget) external returns (uint256 executed);
    function dueCount(bytes32 poolId) external view returns (uint256);
    function getTask(uint256 taskId) external view returns (Task memory);
}

interface IStakingVault {
    function stakedOf(address user) external view returns (uint256);
    function tierOf(address user) external view returns (uint8);
    function backingOf(bytes32 moduleId) external view returns (uint256);
    function slash(bytes32 moduleId, uint256 bps, string calldata reason) external returns (uint256 burned);
    function notifyRewardToken(uint256 amount) external;
}

interface ITreasury {
    function creditDeveloper(bytes32 moduleId, address developer, uint256 amount) external;
    function distribute() external;
}

src/types/Types.sol

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

/*//////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   ░█░█░█▀█░█▀█░█░█░░░█▀▄░█░█░█▀█░▀█▀░▀█▀░█▄█░█▀▀                            //
//   ░█▀█░█░█░█░█░█▀▄░░░█▀▄░█░█░█░█░░█░░░█░░█░█░█▀▀                            //
//   ░▀░▀░▀▀▀░▀▀▀░▀░▀░░░▀░▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░▀▀▀                            //
//                                                                            //
//   Sandboxed module runtime for Uniswap V4 hooks                            //
//                                                                            //
//   web ............ https://evh.one                                         //
//   x .............. https://x.com/VirtualHookETH                            //
//                                                                            //
//////////////////////////////////////////////////////////////////////////////*/

/// @notice The eight Uniswap V4 lifecycle callbacks the EVH kernel exposes as
///         scheduling slots. Bit `i` of a module's `hookMask` corresponds to
///         `HookPoint(i)`. This ordering is load-bearing across the whole system
///         (contracts, subgraph-less indexing, and the frontend) — never reorder.
enum HookPoint {
    BeforeInitialize, //  0
    AfterInitialize, //   1
    BeforeAddLiquidity, //2
    AfterAddLiquidity, // 3
    BeforeRemoveLiquidity, // 4
    AfterRemoveLiquidity, //  5
    BeforeSwap, //        6
    AfterSwap //          7
}

/// @notice Lifecycle state of a registered module.
enum ModuleStatus {
    Unregistered, // 0 - never seen
    Sandboxed, //    1 - executes, but flagged as unaudited in the UI
    Promoted, //     2 - governance-approved, eligible for privileged caps
    Paused, //       3 - skipped by the scheduler, recoverable
    Slashed, //      4 - struck out; stake burned; skipped
    Banned //        5 - terminal, governance-imposed
}

/// @notice Self-describing module metadata. Must match what the developer
///         declares at registration or `ModuleRegistry.register` reverts.
struct Manifest {
    string name;
    string version;
    uint16 hookMask; // bit i => HookPoint(i)
    uint32 gasLimit; // per-execution gas cap the module requests
    uint8 capabilities; // requested capability mask, see Capabilities
}

/// @notice The read-only view of the world a module receives on every execution.
/// @dev    `payload` is the abi-encoded, hook-point-specific argument bundle.
///         See `Payloads` for the concrete decodings.
struct ExecContext {
    bytes32 poolId;
    bytes32 moduleId;
    address sender; // the original caller into the PoolManager
    address kernel;
    uint8 hookPoint; // HookPoint
    uint16 priority; // position in this hook point's queue
    uint32 gasCap; // the cap this frame is executing under
    uint64 blockNumber;
    uint64 timestamp;
    int24 tick;
    uint160 sqrtPriceX96;
    uint128 liquidity;
    uint24 lpFee; // current effective LP fee in pips
    bytes payload;
}

/// @notice Concrete payload shapes, abi-encoded into `ExecContext.payload`.
library Payloads {
    struct Swap {
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
        int128 amount0; // populated on AfterSwap only
        int128 amount1; // populated on AfterSwap only
    }

    struct Liquidity {
        int24 tickLower;
        int24 tickUpper;
        int256 liquidityDelta;
        bytes32 salt;
        int128 amount0; // populated on After* only
        int128 amount1; // populated on After* only
    }

    struct Initialize {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
    }
}

/// @notice Capability bitmask. Bit index order is part of the public ABI surface.
library Capabilities {
    uint8 internal constant READ_POOL_STATE = 1 << 0;
    uint8 internal constant WRITE_STORAGE = 1 << 1;
    uint8 internal constant EXTERNAL_CALL = 1 << 2;
    uint8 internal constant TOKEN_TRANSFER = 1 << 3;
    uint8 internal constant MODIFY_FEE = 1 << 4;
    uint8 internal constant EMIT_EVENT = 1 << 5;
    uint8 internal constant SCHEDULE = 1 << 6;
    uint8 internal constant POOL_CALL = 1 << 7;

    /// @dev Capabilities that may be granted automatically at registration.
    uint8 internal constant UNPRIVILEGED = READ_POOL_STATE | WRITE_STORAGE | EMIT_EVENT | MODIFY_FEE | SCHEDULE;

    /// @dev Capabilities that require an explicit governance grant.
    uint8 internal constant PRIVILEGED = EXTERNAL_CALL | TOKEN_TRANSFER | POOL_CALL;

    function has(uint8 mask, uint8 cap) internal pure returns (bool) {
        return mask & cap != 0;
    }
}

/// @notice Helpers for the 16-bit hook subscription mask.
library HookMask {
    uint16 internal constant ALL = 0x00FF;

    function subscribed(uint16 mask, uint8 hookPoint) internal pure returns (bool) {
        return mask & (uint16(1) << hookPoint) != 0;
    }

    function count(uint16 mask) internal pure returns (uint256 n) {
        for (uint256 i; i < 8; ++i) {
            if (mask & (uint16(1) << uint16(i)) != 0) ++n;
        }
    }

    function isValid(uint16 mask) internal pure returns (bool) {
        return mask != 0 && mask & ~ALL == 0;
    }
}

/// @notice Tagged return values a module may emit from `execute`.
/// @dev    A module wanting to move the dynamic fee returns
///         `abi.encode(ModuleReturn.FEE_PROPOSAL, uint256(feeInPips))`.
library ModuleReturn {
    bytes32 internal constant FEE_PROPOSAL = keccak256("token.return.feeProposal");
    bytes32 internal constant NO_OP = keccak256("token.return.noop");

    /// @notice Decode a fee proposal if the return data carries one.
    function feeProposal(bytes memory ret) internal pure returns (bool ok, uint24 fee) {
        if (ret.length != 64) return (false, 0);
        bytes32 tag;
        uint256 value;
        assembly ("memory-safe") {
            tag := mload(add(ret, 0x20))
            value := mload(add(ret, 0x40))
        }
        if (tag != FEE_PROPOSAL) return (false, 0);
        if (value > type(uint24).max) return (false, 0);
        return (true, uint24(value));
    }
}

src/utils/Owned.sol

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

/*//////////////////////////////////////////////////////////////////////////////
//                                                                            //
//   ░█░█░█▀█░█▀█░█░█░░░█▀▄░█░█░█▀█░▀█▀░▀█▀░█▄█░█▀▀                            //
//   ░█▀█░█░█░█░█░█▀▄░░░█▀▄░█░█░█░█░░█░░░█░░█░█░█▀▀                            //
//   ░▀░▀░▀▀▀░▀▀▀░▀░▀░░░▀░▀░▀▀▀░▀░▀░░▀░░▀▀▀░▀░▀░▀▀▀                            //
//                                                                            //
//   Sandboxed module runtime for Uniswap V4 hooks                            //
//                                                                            //
//   web ............ https://evh.one                                         //
//   x .............. https://x.com/VirtualHookETH                            //
//                                                                            //
//////////////////////////////////////////////////////////////////////////////*/

/// @title Owned
/// @notice Minimal two-step ownership. Used by every EVH protocol contract so the
///         whole system can be handed to the timelock in one sweep after launch.
abstract contract Owned {
    address public owner;
    address public pendingOwner;

    event OwnershipTransferStarted(address indexed from, address indexed to);
    event OwnershipTransferred(address indexed from, address indexed to);

    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    constructor(address _owner) {
        if (_owner == address(0)) revert ZeroAddress();
        owner = _owner;
        emit OwnershipTransferred(address(0), _owner);
    }

    function transferOwnership(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        pendingOwner = to;
        emit OwnershipTransferStarted(owner, to);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        address prev = owner;
        owner = pendingOwner;
        pendingOwner = address(0);
        emit OwnershipTransferred(prev, owner);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/",
    "v4-periphery/=lib/v4-periphery/",
    "@uniswap/v4-core/=lib/v4-core/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.