Skip to content
Verified contractExactLGPL-3.0-only

QuarantineDeployer

Address0xba1297ee70840d45988c51df63ef7abd6b70a2fd
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
No
EVM version
osaka
License
LGPL-3.0-only
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,442,105
Creation transaction
0x23283ee847…aa313d36d1

src/QuarantineDeployer.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

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

/// @title QuarantineDeployer — the one address a clear-signing registry needs to trust.
///
/// @notice Deploys Quarantine instances for Safes. Permissionless: anyone may deploy
///         for anyone; the deploying account only pays gas and holds no role.
///
/// @dev    Exists for ERC-7730: descriptors bind to known addresses, but every Quarantine
///         has its own. A `contract.factory` constraint lets a wallet attribute any
///         Quarantine to this deployer via the `QuarantineDeployed` event, so the
///         descriptor registers this one address instead of every instance. For that
///         to hold, instances must be deployed *through* this contract — a directly
///         deployed Quarantine emits no event and will not match the constraint.
contract QuarantineDeployer {
    event QuarantineDeployed(address indexed quarantine, address indexed safe);

    function deploy(address safe, Quarantine.Config calldata config)
        external
        returns (Quarantine q)
    {
        q = new Quarantine(safe, config);
        emit QuarantineDeployed(address(q), safe);
    }
}

src/Quarantine.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @dev ABI-identical to Safe's `Enum.Operation`.
enum Operation {
    Call,
    DelegateCall
}

/// @dev The subset of the Safe module interface this contract calls.
interface IAvatar {
    function execTransactionFromModule(
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) external returns (bool success);
}

/// @title Quarantine — a delayed, guardian-vetoed transaction path for one Safe.
///
/// @notice Every transaction destined for `safe` enters a FIFO queue and must
///         age `delay` seconds before anyone may execute it. Entry is granted
///         to `owner` alone or to `enqueueThreshold` guardians. A prefix of
///         the queue can be discarded by `cancelThreshold` voters (guardians
///         and owner, one vote each; `2 <= cancelThreshold <= guardians.length`,
///         so the owner can never cancel alone and guardians can always cancel
///         without the owner). The contract's own configuration changes
///         only via a transaction that has itself passed through the queue.
///
/// @dev    Authority model and semantics are specified in SPEC.md; design
///         decisions D1–D12 in PLAN.md. In short:
///         - Queue identity is a nonce cursor pair (`txNonce`, `queueNonce`),
///           cancellation is prefix-only, execution is strictly FIFO. Both
///           cancelling and skipping expired slots are O(1) in the number of
///           slots, so queue spam cannot raise the defenders' on-chain cost.
///         - Pending guardian proposals are keyed by content hash, carry no
///           salt, store no calldata, and expire after `proposalTtl`.
///         - Every vote is an ordinary transaction from the voter: the only
///           authentication is `msg.sender`. There are no signatures, so what
///           a voter approves is the transaction they send, and wallets can
///           render it with an ERC-7730 calldata descriptor. Only a boolean
///           per voter is stored.
///         - Thresholds are recounted live over the *current* guardian set.
///         - No owner shortcuts, no upgradeability, no factory.
contract Quarantine {
    // ---------------------------------------------------------------------
    // Types
    // ---------------------------------------------------------------------

    /// @dev Full configuration; replaced atomically by `applyConfig`.
    struct Config {
        /// Enqueues alone; one cancel vote. `address(0)` disables the role.
        address owner;
        /// `1..MAX_GUARDIANS`, unique, non-zero, none equal to `owner`.
        address[] guardians;
        /// Guardians required to promote a proposal into the queue (>= 1).
        uint256 enqueueThreshold;
        /// Voters required to advance `txNonce` (2..guardians.length, so
        /// guardians alone can always cancel; the owner's vote is additive).
        uint256 cancelThreshold;
        /// Seconds a slot must age before `executeNextTx` (<= MAX_DELAY).
        uint256 delay;
        /// Seconds after `delay` during which a slot may still execute; 0 = forever.
        uint256 expiration;
        /// Seconds a pending proposal stays alive (>= 1).
        uint256 proposalTtl;
    }

    // ---------------------------------------------------------------------
    // Constants
    // ---------------------------------------------------------------------

    /// @dev Upper bound on `guardians.length`; bounds every recount loop.
    uint256 public constant MAX_GUARDIANS = 16;

    /// @dev `expiration` must be 0 or at least this many seconds.
    uint256 public constant MIN_EXPIRATION = 60;

    /// @dev `delay` must not exceed this (~6 months). Bounds how long a
    ///      mis-set `delay` can freeze the module: even if a delay-raising
    ///      config change slips past the guardians, a corrective config can
    ///      always mature and execute within MAX_DELAY.
    uint256 public constant MAX_DELAY = 26 weeks;

    // ---------------------------------------------------------------------
    // Storage
    // ---------------------------------------------------------------------

    /// @notice The Safe this module executes into. The only external call target.
    address public immutable safe;

    // --- config: mutable only through `applyConfig` ---

    address public owner;
    address[] private _guardians;
    mapping(address => bool) public isGuardian;
    uint256 public enqueueThreshold;
    uint256 public cancelThreshold;
    uint256 public delay;
    uint256 public expiration;
    uint256 public proposalTtl;

    // --- queue: layout and semantics identical to Zodiac Delay ---

    /// @notice Read cursor: the next slot to execute. Monotonic.
    uint256 public txNonce;
    /// @notice Write cursor: the next slot to fill. Monotonic.
    uint256 public queueNonce;
    /// @notice Slot → content hash (`getTransactionHash`).
    mapping(uint256 => bytes32) public txHash;
    /// @notice Slot → timestamp at which it entered the queue.
    mapping(uint256 => uint256) public txCreatedAt;

    // --- pending proposals: keyed by content hash ---

    /// @notice Content hash → creation timestamp. 0 means no live proposal.
    mapping(bytes32 => uint256) public proposalCreatedAt;
    /// @notice Content hash → round. Incremented on every deletion
    ///         (promotion or prune). Votes are keyed by round, so deleting a
    ///         proposal makes all of its votes unreachable in O(1) and a later
    ///         proposal of the same content starts with none.
    mapping(bytes32 => uint256) public proposalRound;
    /// @notice Content hash → round → voter → has approved.
    mapping(bytes32 => mapping(uint256 => mapping(address => bool))) public hasApproved;

    // --- cancel votes: keyed by target nonce ---

    /// @notice Target `newNonce` → voter → has approved. A key is dead
    ///         forever once `txNonce >= newNonce`.
    mapping(uint256 => mapping(address => bool)) public hasApprovedCancel;

    // ---------------------------------------------------------------------
    // Events
    // ---------------------------------------------------------------------

    event ConfigApplied(Config config);

    /// @dev Kept from Delay: carries the full preimage for queue slots.
    event TransactionAdded(
        uint256 indexed queueNonce,
        bytes32 indexed txHash,
        address to,
        uint256 value,
        bytes data,
        Operation operation
    );
    /// @dev Emitted on cancellation and on `skipExpiredTo`. Slots in
    ///      `[oldNonce, newNonce)` will never execute.
    event TxNonceSet(uint256 newNonce, uint256 oldNonce);
    event TransactionExecuted(uint256 indexed queueNonce, bytes32 indexed txHash);

    /// @dev First approval of a content hash. Carries the preimage; nothing
    ///      but the hash, timestamp and round is stored on-chain.
    event Proposed(
        bytes32 indexed hash,
        address to,
        uint256 value,
        bytes data,
        Operation operation,
        uint256 round
    );
    event Approved(bytes32 indexed hash, uint256 round, address indexed voter);
    event ProposalPromoted(bytes32 indexed hash, uint256 round, uint256 indexed queueNonce);
    event ProposalPruned(bytes32 indexed hash, uint256 round);

    event CancelApproved(uint256 indexed newNonce, address indexed voter);

    // ---------------------------------------------------------------------
    // Errors
    // ---------------------------------------------------------------------

    error InvalidConfig(string reason);
    error NotOwner();
    error OnlySelf();
    error NotVoter();
    error NoProposal(bytes32 hash);
    error ProposalNotExpired(bytes32 hash);
    error NonceTooLow(uint256 newNonce, uint256 txNonce);
    error NonceTooHigh(uint256 newNonce, uint256 queueNonce);
    error NotExpired(uint256 nonce);
    error QueueEmpty();
    error StillInDelay(uint256 nonce, uint256 readyAt);
    error Expired(uint256 nonce);
    error HashMismatch(uint256 nonce);
    error SelfDelegateCall();
    error SelfCallWithValue();
    error SelfCallNotConfig();
    error ExecutionFailed(uint256 nonce);

    // ---------------------------------------------------------------------
    // Construction
    // ---------------------------------------------------------------------

    /// @param safe_ The Safe this module will execute into. Must be enabled
    ///              as a module on that Safe separately.
    /// @param config Initial configuration; validated exactly as `applyConfig`.
    constructor(address safe_, Config memory config) {
        if (safe_ == address(0)) revert InvalidConfig("safe");
        safe = safe_;
        _validateConfig(config);
        _applyConfig(config);
    }

    // ---------------------------------------------------------------------
    // Enqueue
    // ---------------------------------------------------------------------

    /// @notice Owner's direct path: place a transaction into the next slot.
    /// @dev    Does not interact with pending proposals for the same content.
    /// @return nonce The slot assigned.
    function enqueue(address to, uint256 value, bytes calldata data, Operation operation)
        external
        returns (uint256 nonce)
    {
        if (owner == address(0) || msg.sender != owner) revert NotOwner();
        nonce = _enqueue(getTransactionHash(to, value, data, operation), to, value, data, operation);
    }

    /// @notice Voter path: `msg.sender` votes for a transaction. The first
    ///         vote on a content hash creates the proposal (and emits its
    ///         preimage); reaching `enqueueThreshold` live guardian votes — or
    ///         any vote from `owner` — promotes it into the next queue slot
    ///         and deletes the proposal (bumping `round`).
    ///
    /// @dev    Reverts `NotVoter` unless `msg.sender` is the owner or a current
    ///         guardian. A repeated vote by the same voter records nothing but
    ///         still triggers a recount, so an existing voter can re-call to
    ///         apply a lowered threshold.
    function approve(address to, uint256 value, bytes calldata data, Operation operation) external {
        if (!_isVoter(msg.sender)) revert NotVoter();
        bytes32 hash = getTransactionHash(to, value, data, operation);

        // Garbage-collect a stale proposal for this content before voting.
        if (isProposalExpired(hash)) {
            emit ProposalPruned(hash, proposalRound[hash]);
            _deleteProposal(hash);
        }

        uint256 round = proposalRound[hash];
        if (proposalCreatedAt[hash] == 0) {
            proposalCreatedAt[hash] = block.timestamp;
            emit Proposed(hash, to, value, data, operation, round);
        }

        if (!hasApproved[hash][round][msg.sender]) {
            hasApproved[hash][round][msg.sender] = true;
            emit Approved(hash, round, msg.sender);
        }

        if (msg.sender == owner || approvalCount(hash) >= enqueueThreshold) {
            uint256 nonce = _enqueue(hash, to, value, data, operation);
            emit ProposalPromoted(hash, round, nonce);
            _deleteProposal(hash);
        }
    }

    /// @notice Garbage-collect an expired pending proposal. Permissionless.
    /// @dev    Reverts `NoProposal` if none is live for this content,
    ///         `ProposalNotExpired` if it is still within `proposalTtl`.
    function pruneProposal(address to, uint256 value, bytes calldata data, Operation operation)
        external
    {
        bytes32 hash = getTransactionHash(to, value, data, operation);
        if (proposalCreatedAt[hash] == 0) revert NoProposal(hash);
        if (!isProposalExpired(hash)) revert ProposalNotExpired(hash);
        emit ProposalPruned(hash, proposalRound[hash]);
        _deleteProposal(hash);
    }

    // ---------------------------------------------------------------------
    // Cancel
    // ---------------------------------------------------------------------

    /// @notice Vote to advance `txNonce` to `newNonce`, discarding every slot
    ///         in `[txNonce, newNonce)`. Applied when live votes from the
    ///         current guardians plus owner reach `cancelThreshold`.
    ///
    /// @dev    Reverts `NotVoter` unless `msg.sender` is the owner or a current
    ///         guardian. Requires `txNonce < newNonce <= queueNonce`; because
    ///         `txNonce` is monotonic, votes under a consumed `newNonce` are
    ///         unreachable forever. "Cancel everything" is
    ///         `approveCancel(queueNonce)`.
    function approveCancel(uint256 newNonce) external {
        if (!_isVoter(msg.sender)) revert NotVoter();
        uint256 current = txNonce;
        if (newNonce <= current) revert NonceTooLow(newNonce, current);
        if (newNonce > queueNonce) revert NonceTooHigh(newNonce, queueNonce);

        if (!hasApprovedCancel[newNonce][msg.sender]) {
            hasApprovedCancel[newNonce][msg.sender] = true;
            emit CancelApproved(newNonce, msg.sender);
        }

        if (cancelApprovalCount(newNonce) >= cancelThreshold) {
            _setTxNonce(newNonce);
        }
    }

    // ---------------------------------------------------------------------
    // Execute
    // ---------------------------------------------------------------------

    /// @notice Execute the slot at `txNonce`. Permissionless.
    /// @dev    Requires the slot to have aged `delay`, not to have expired,
    ///         and the arguments to hash to `txHash[txNonce]`. Increments
    ///         `txNonce` before the external call. Reverts (rolling the
    ///         increment back) if the call fails.
    ///
    ///         If `to == address(this)` the call is made directly
    ///         (`address(this).call(data)`), never through the Safe, and must
    ///         be a zero-value `Call` whose selector is `applyConfig`. This
    ///         is what makes `OnlySelf` a sound guard even when the Safe has
    ///         other modules.
    function executeNextTx(address to, uint256 value, bytes calldata data, Operation operation)
        external
    {
        uint256 nonce = txNonce;
        if (nonce >= queueNonce) revert QueueEmpty();

        uint256 createdAt = txCreatedAt[nonce];
        uint256 readyAt = createdAt + delay;
        if (block.timestamp < readyAt) revert StillInDelay(nonce, readyAt);
        if (expiration != 0 && block.timestamp > readyAt + expiration) {
            revert Expired(nonce);
        }

        bytes32 hash = getTransactionHash(to, value, data, operation);
        if (txHash[nonce] != hash) revert HashMismatch(nonce);

        bool isSelf = to == address(this);
        if (isSelf) {
            if (operation != Operation.Call) revert SelfDelegateCall();
            if (value != 0) revert SelfCallWithValue();
            if (data.length < 4 || bytes4(data[:4]) != this.applyConfig.selector) {
                revert SelfCallNotConfig();
            }
        }

        txNonce = nonce + 1;

        bool ok;
        if (isSelf) {
            (ok,) = address(this).call(data);
        } else {
            ok = IAvatar(safe).execTransactionFromModule(to, value, data, operation);
        }
        if (!ok) revert ExecutionFailed(nonce);

        emit TransactionExecuted(nonce, hash);
    }

    /// @notice Advance `txNonce` to `newNonce`, discarding slots
    ///         `[txNonce, newNonce)`, all of which must be expired.
    ///         Permissionless.
    /// @dev    O(1): slots enter the queue in timestamp order and the expiry
    ///         rule is uniform, so if slot `newNonce - 1` is expired every
    ///         slot before it is too. Only that one slot is checked. There is
    ///         no per-call cap; a caller may skip any number of expired slots.
    ///         Reverts `NotExpired` when `expiration == 0` (nothing ever
    ///         expires) or when slot `newNonce - 1` is still within its window.
    function skipExpiredTo(uint256 newNonce) external {
        uint256 current = txNonce;
        if (newNonce <= current) revert NonceTooLow(newNonce, current);
        if (newNonce > queueNonce) revert NonceTooHigh(newNonce, queueNonce);

        uint256 exp = expiration;
        uint256 last = newNonce - 1;
        if (exp == 0 || block.timestamp <= txCreatedAt[last] + delay + exp) {
            revert NotExpired(last);
        }

        _setTxNonce(newNonce);
    }

    // ---------------------------------------------------------------------
    // Config
    // ---------------------------------------------------------------------

    /// @notice Replace the entire configuration.
    /// @dev    Callable only by this contract, i.e. only from the self-call
    ///         branch of `executeNextTx`. Validated per SPEC.md §2. Touches no
    ///         proposal or cancel-vote state: recounting over the new guardian
    ///         set is what makes removed guardians' votes stop counting.
    function applyConfig(Config calldata config) external {
        if (msg.sender != address(this)) revert OnlySelf();
        _validateConfig(config);
        _applyConfig(config);
    }

    // ---------------------------------------------------------------------
    // Views
    // ---------------------------------------------------------------------

    /// @notice Current guardian set.
    function guardians() external view returns (address[] memory) {
        return _guardians;
    }

    function guardianCount() external view returns (uint256) {
        return _guardians.length;
    }

    /// @notice Live guardian approvals for the current round of `hash`.
    ///         Owner is not counted (owner's approval promotes outright).
    function approvalCount(bytes32 hash) public view returns (uint256 count) {
        uint256 round = proposalRound[hash];
        uint256 n = _guardians.length;
        for (uint256 i = 0; i < n; i++) {
            if (hasApproved[hash][round][_guardians[i]]) count++;
        }
    }

    /// @notice Live cancel votes for `newNonce` over current guardians + owner.
    function cancelApprovalCount(uint256 newNonce) public view returns (uint256 count) {
        address o = owner;
        if (o != address(0) && hasApprovedCancel[newNonce][o]) count++;
        uint256 n = _guardians.length;
        for (uint256 i = 0; i < n; i++) {
            if (hasApprovedCancel[newNonce][_guardians[i]]) count++;
        }
    }

    /// @notice True iff a proposal is live for `hash` and past `proposalTtl`.
    function isProposalExpired(bytes32 hash) public view returns (bool) {
        uint256 createdAt = proposalCreatedAt[hash];
        return createdAt != 0 && block.timestamp > createdAt + proposalTtl;
    }

    /// @notice Content hash shared by queue slots and proposals.
    ///         Unchanged from Delay: `keccak256(abi.encodePacked(to, value, data, operation))`.
    function getTransactionHash(address to, uint256 value, bytes memory data, Operation operation)
        public
        pure
        returns (bytes32)
    {
        return keccak256(abi.encodePacked(to, value, data, operation));
    }

    // ---------------------------------------------------------------------
    // Internal
    // ---------------------------------------------------------------------

    /// @dev SPEC.md §2 rules C1–C10. Reverts `InvalidConfig(reason)`.
    function _validateConfig(Config memory config) internal pure {
        uint256 n = config.guardians.length;
        if (n == 0) revert InvalidConfig("no guardians"); // C1
        if (n > MAX_GUARDIANS) revert InvalidConfig("too many guardians"); // C1
        for (uint256 i = 0; i < n; i++) {
            address g = config.guardians[i];
            if (g == address(0)) revert InvalidConfig("zero guardian"); // C2
            if (g == config.owner) revert InvalidConfig("guardian is owner"); // C4
            for (uint256 j = i + 1; j < n; j++) {
                if (config.guardians[j] == g) {
                    revert InvalidConfig("duplicate guardian"); // C3
                }
            }
        }
        if (config.enqueueThreshold == 0) {
            revert InvalidConfig("enqueueThreshold zero"); // C5
        }
        if (config.enqueueThreshold > n) {
            revert InvalidConfig("enqueueThreshold unreachable"); // C6
        }
        if (config.cancelThreshold < 2) {
            revert InvalidConfig("cancelThreshold below 2"); // C7
        }
        if (config.cancelThreshold > n) {
            revert InvalidConfig("cancelThreshold unreachable"); // C8
        }
        if (config.expiration != 0 && config.expiration < MIN_EXPIRATION) {
            revert InvalidConfig("expiration too short"); // C9
        }
        if (config.proposalTtl == 0) revert InvalidConfig("proposalTtl zero"); // C10
        if (config.delay > MAX_DELAY) revert InvalidConfig("delay too long"); // C11
    }

    /// @dev Clears `isGuardian` for the old set, writes the new set and all
    ///      scalar fields, emits `ConfigApplied`.
    function _applyConfig(Config memory config) internal {
        uint256 oldLen = _guardians.length;
        for (uint256 i = 0; i < oldLen; i++) {
            isGuardian[_guardians[i]] = false;
        }
        _guardians = config.guardians;
        uint256 newLen = config.guardians.length;
        for (uint256 i = 0; i < newLen; i++) {
            isGuardian[config.guardians[i]] = true;
        }

        owner = config.owner;
        enqueueThreshold = config.enqueueThreshold;
        cancelThreshold = config.cancelThreshold;
        delay = config.delay;
        expiration = config.expiration;
        proposalTtl = config.proposalTtl;

        emit ConfigApplied(config);
    }

    /// @dev Writes a slot, bumps `queueNonce`, emits `TransactionAdded`.
    function _enqueue(
        bytes32 hash,
        address to,
        uint256 value,
        bytes calldata data,
        Operation operation
    ) internal returns (uint256 nonce) {
        nonce = queueNonce;
        txHash[nonce] = hash;
        txCreatedAt[nonce] = block.timestamp;
        emit TransactionAdded(nonce, hash, to, value, data, operation);
        queueNonce = nonce + 1;
    }

    /// @dev Zeroes `proposalCreatedAt[hash]` and increments `proposalRound[hash]`.
    ///      O(1); old vote flags become unreachable via the round key.
    function _deleteProposal(bytes32 hash) internal {
        proposalCreatedAt[hash] = 0;
        proposalRound[hash] += 1;
    }

    /// @dev Advances the read cursor. The only writer of `txNonce` besides
    ///      `executeNextTx`.
    function _setTxNonce(uint256 newNonce) internal {
        uint256 old = txNonce;
        txNonce = newNonce;
        emit TxNonceSet(newNonce, old);
    }

    /// @dev True iff `account` may vote: `owner` (when non-zero) or a current guardian.
    function _isVoter(address account) internal view returns (bool) {
        return (account != address(0) && account == owner) || isGuardian[account];
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "viaSSACFG": false,
  "evmVersion": "osaka",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.