Skip to content
Verified contractPartialMIT

VaultGuardSetup

Address0xfe7309e11aaa41af0c99f7253f6f77dd786c5498
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,494,155
Creation transaction
0x6d330dc6e9…434b132409

src/VaultGuardSetup.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {GuardManager} from "@safe/base/GuardManager.sol";
import {VaultGuard} from "./VaultGuard.sol";

contract VaultGuardSetup {
    address private immutable SELF = address(this);

    /// @notice Must run via DELEGATECALL from `Safe.setup`. A zero `master` creates a personal vault.
    function setupGuard(address guard, address master, address server, uint256 quorum) external {
        require(address(this) != SELF, "Only delegatecall");
        require(guard.code.length > 0, "Guard not deployed");
        GuardManager(address(this)).setGuard(guard);
        if (master != address(0)) {
            VaultGuard(guard).registerVault(master, server, quorum);
        }
    }
}

dependencies/safe-smart-account-1.3.0/contracts/base/GuardManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

import "../common/Enum.sol";
import "../common/SelfAuthorized.sol";

interface Guard {
    function checkTransaction(
        address to,
        uint256 value,
        bytes memory data,
        Enum.Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address payable refundReceiver,
        bytes memory signatures,
        address msgSender
    ) external;

    function checkAfterExecution(bytes32 txHash, bool success) external;
}

/// @title Fallback Manager - A contract that manages fallback calls made to this contract
/// @author Richard Meissner - <[email protected]>
contract GuardManager is SelfAuthorized {
    event ChangedGuard(address guard);
    // keccak256("guard_manager.guard.address")
    bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;

    /// @dev Set a guard that checks transactions before execution
    /// @param guard The address of the guard to be used or the 0 address to disable the guard
    function setGuard(address guard) external authorized {
        bytes32 slot = GUARD_STORAGE_SLOT;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            sstore(slot, guard)
        }
        emit ChangedGuard(guard);
    }

    function getGuard() internal view returns (address guard) {
        bytes32 slot = GUARD_STORAGE_SLOT;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            guard := sload(slot)
        }
    }
}

dependencies/safe-smart-account-1.3.0/contracts/common/Enum.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title Enum - Collection of enums
/// @author Richard Meissner - <[email protected]>
contract Enum {
    enum Operation {Call, DelegateCall}
}

dependencies/safe-smart-account-1.3.0/contracts/common/SelfAuthorized.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title SelfAuthorized - authorizes current contract to perform actions
/// @author Richard Meissner - <[email protected]>
contract SelfAuthorized {
    function requireSelfCall() private view {
        require(msg.sender == address(this), "GS031");
    }

    modifier authorized() {
        // This is a function call as it minimized the bytecode size
        requireSelfCall();
        _;
    }
}

src/VaultGuard.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {Enum} from "@safe/common/Enum.sol";
import {Guard} from "@safe/base/GuardManager.sol";
import {IERC165} from "./interfaces/IERC165.sol";
import {ISafe} from "./interfaces/ISafe.sol";

/// @notice Transaction guard for Safe 1.3.0 vaults. All state is keyed by `msg.sender` (the Safe), so a
/// caller that is not a Safe only ever touches its own key.
contract VaultGuard is Guard, IERC165 {
    struct Vault {
        address master;
        bool registered;
        address server;
    }

    /// @dev Mirrors the Safe's EIP-712 SafeTx struct. It is all-static so `abi.encode` of it equals the Safe's
    /// flat encoding, which avoids a ten-argument external call that does not fit on the stack.
    struct SafeTx {
        bytes32 typehash;
        address to;
        uint256 value;
        bytes32 dataHash;
        Enum.Operation operation;
        uint256 safeTxGas;
        uint256 baseGas;
        uint256 gasPrice;
        address gasToken;
        address refundReceiver;
        uint256 nonce;
    }

    struct Ctx {
        address safe;
        SafeTx tx;
        address master;
        address server;
        bool needsMasterApproval;
        bool needsMasterCall;
    }

    // keccak256("SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)")
    bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;

    // Safe 1.3.0 OwnerManager keeps ownerCount at slot 3 and threshold at slot 4, so one getStorageAt reads both.
    uint256 private constant OWNER_COUNT_SLOT = 3;
    // keccak256("fallback_manager.handler.address")
    uint256 private constant FALLBACK_HANDLER_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;
    uint256 private constant MULTISEND_ITEM_HEAD = 85; // op(1) + to(20) + value(32) + dataLength(32)

    address private constant DEFAULT_CALLBACK_HANDLER = 0x1AC114C2099aFAf5261731655Dc6c306bFcd4Dbd;

    bytes4 private constant SEL_ERC20_TRANSFER = 0xa9059cbb;
    bytes4 private constant SEL_MULTISEND = 0x8d80ff0a;
    bytes4 private constant SEL_ADD_OWNER = 0x0d582f13;
    bytes4 private constant SEL_REMOVE_OWNER = 0xf8dc5dd9;
    bytes4 private constant SEL_SWAP_OWNER = 0xe318b52b;
    bytes4 private constant SEL_CHANGE_THRESHOLD = 0x694e80c3;

    address public immutable multiSendCallOnly141;
    address public immutable multiSendCallOnly150;
    address public immutable multiSendCallOnly130;

    mapping(address safe => Vault) private _vaults;

    event VaultRegistered(address indexed safe, address master, address server);
    event ServerChanged(address indexed safe, address server);
    event MasterChanged(address indexed safe, address master);

    constructor(address multiSendCallOnly141_, address multiSendCallOnly150_, address multiSendCallOnly130_) {
        multiSendCallOnly141 = multiSendCallOnly141_;
        multiSendCallOnly150 = multiSendCallOnly150_;
        multiSendCallOnly130 = multiSendCallOnly130_;
    }

    function supportsInterface(bytes4 interfaceId) external pure override returns (bool) {
        return interfaceId == type(Guard).interfaceId || interfaceId == 0x01ffc9a7;
    }

    /// @notice Called by the Safe (through the setup helper) while `Safe.setup` runs. A zero `master`
    /// makes a personal vault.
    function registerVault(address master, address server, uint256 quorum) external {
        Vault storage v = _vaults[msg.sender];
        require(!v.registered, "Vault already registered");
        if (master != address(0)) {
            ISafe safe = ISafe(msg.sender);
            // Only a handler without EIP-1271 keeps message signing out of reach of employees alone; the self-call
            // allow-list stops the handler from being changed later.
            address handler = abi.decode(safe.getStorageAt(FALLBACK_HANDLER_SLOT, 1), (address));
            require(handler == address(0) || handler == DEFAULT_CALLBACK_HANDLER, "Fallback handler not allowed");
            require(safe.isOwner(master), "Master must be an owner");
            require(server != master, "Server and Master must differ");
            require(safe.isOwner(server), "Server must be an owner");
            (uint256 ownerCount, uint256 threshold) = _ownerCountAndThreshold(safe);
            require(quorum != 0 && threshold == quorum + 1, "Threshold must be the employee quorum plus one");
            require(ownerCount > threshold, "Employee quorum not reachable");
            v.server = server;
        }
        v.registered = true;
        v.master = master;
        emit VaultRegistered(msg.sender, master, v.server);
    }

    function checkTransaction(
        address to,
        uint256 value,
        bytes calldata data,
        Enum.Operation operation,
        uint256 safeTxGas,
        uint256 baseGas,
        uint256 gasPrice,
        address gasToken,
        address payable refundReceiver,
        bytes memory signatures,
        address
    ) external view override {
        if (operation != Enum.Operation.Call) {
            require(
                to == multiSendCallOnly141 || to == multiSendCallOnly150 || to == multiSendCallOnly130,
                "Delegate calls are not allowed"
            );
            require(data.length >= 4 && bytes4(data[:4]) == SEL_MULTISEND, "Delegate calls are not allowed");
        }

        Vault storage v = _vaults[msg.sender];

        Ctx memory c;
        c.safe = msg.sender;
        c.master = v.master;
        c.server = v.server;
        c.tx.to = to;
        c.tx.value = value;
        c.tx.operation = operation;
        c.tx.safeTxGas = safeTxGas;
        c.tx.baseGas = baseGas;
        c.tx.gasPrice = gasPrice;
        c.tx.gasToken = gasToken;
        c.tx.refundReceiver = refundReceiver;

        if (operation == Enum.Operation.Call) {
            _checkCall(c, to, value, data);
        } else {
            _checkBatch(c, data);
        }
        if (c.master == address(0)) return;
        _authorize(c, data, signatures);
    }

    function _authorize(Ctx memory c, bytes calldata data, bytes memory signatures) private view {
        (bool server, bool master, uint256 employees, uint256 threshold) = _signers(c, data, signatures);
        require(!c.needsMasterApproval || master, "Only the Master can change vault settings");
        require(!c.needsMasterCall || master, "Only the Master can make this call");
        // With gasPrice 0 the Safe pays no refund whatever gasToken and baseGas say.
        require(master || c.tx.gasPrice == 0, "Gas refund needs the Master");
        // threshold = q + 1 signers with at least q employees leaves room for at most one of {S, M}; this rejects S + M + (q - 1).
        require(employees + 1 >= threshold, "Employee quorum not reached");
        require(server || master, "Server or Master signature required");
    }

    function checkAfterExecution(bytes32, bool success) external view override {
        Vault storage v = _vaults[msg.sender];
        if (v.master == address(0) || !success) return;
        ISafe safe = ISafe(msg.sender);
        require(safe.isOwner(v.master), "Master must remain an owner");
        require(safe.isOwner(v.server), "Server must remain an owner");
        (uint256 ownerCount, uint256 threshold) = _ownerCountAndThreshold(safe);
        require(threshold >= 2, "Threshold must be at least 2");
        // Fewer employees than q leaves no accepted signer set, which would freeze the vault.
        require(ownerCount > threshold, "Employee quorum not reachable");
    }

    function _ownerCountAndThreshold(ISafe safe) private view returns (uint256 ownerCount, uint256 threshold) {
        return abi.decode(safe.getStorageAt(OWNER_COUNT_SLOT, 2), (uint256, uint256));
    }

    function _checkBatch(Ctx memory c, bytes calldata data) private view {
        bytes calldata txs = _batchPayload(data);
        uint256 i;
        while (i < txs.length) {
            require(txs.length - i >= MULTISEND_ITEM_HEAD, "Malformed batch");
            uint8 op = uint8(txs[i]);
            address to = address(bytes20(txs[i + 1:i + 21]));
            uint256 value = uint256(bytes32(txs[i + 21:i + 53]));
            uint256 len = uint256(bytes32(txs[i + 53:i + 85]));
            require(len <= txs.length - i - MULTISEND_ITEM_HEAD, "Malformed batch");
            require(op == 0, "Delegate calls are not allowed");
            // MultiSendCallOnly 1.5.0 treats a zero target as the calling Safe.
            if (to == address(0)) to = c.safe;
            _checkCall(c, to, value, txs[i + 85:i + 85 + len]);
            i += MULTISEND_ITEM_HEAD + len;
        }
    }

    /// @dev Decodes the `bytes` argument of `multiSend(bytes)` the same way the Solidity ABI decoder
    /// in MultiSend does, so the guard and the executor see identical sub-transactions.
    function _batchPayload(bytes calldata data) private pure returns (bytes calldata txs) {
        require(data.length >= 36, "Malformed batch");
        uint256 offset = uint256(bytes32(data[4:36]));
        require(offset <= data.length - 36, "Malformed batch");
        uint256 lenPos = 4 + offset;
        uint256 len = uint256(bytes32(data[lenPos:lenPos + 32]));
        require(len <= data.length - lenPos - 32, "Malformed batch");
        txs = data[lenPos + 32:lenPos + 32 + len];
    }

    /// @dev An on-chain reject (empty self-call without value) only consumes the nonce, so it needs the same
    /// signers as a transfer, not the Master. Any other self-call (module, guard, fallback handler, nested
    /// execTransaction) would let one blind-signed transaction switch the guard off or make the vault sign
    /// EIP-1271 messages outside it, so only owner management is allowed. The guard can therefore not be
    /// removed or replaced: a new guard means a new vault. The allow-list applies to every vault; only the
    /// Master requirement is specific to organization vaults. A personal vault must not call the guard, or it
    /// could register itself as an organization vault outside the app.
    function _checkCall(Ctx memory c, address to, uint256 value, bytes calldata cd) private view {
        if (to == c.safe) {
            if (cd.length != 0) {
                require(cd.length >= 4 && _isOwnerManagement(bytes4(cd[:4])), "Vault call is not allowed");
                c.needsMasterApproval = true;
            } else if (value != 0) {
                c.needsMasterApproval = true;
            }
        } else if (to == address(this)) {
            require(c.master != address(0), "Vault call is not allowed");
            c.needsMasterApproval = true;
        } else if (cd.length != 0 && !(value == 0 && cd.length == 68 && bytes4(cd[:4]) == SEL_ERC20_TRANSFER)) {
            // The Server and employees may only move funds; any other call (approve, setApprovalForAll, ...)
            // can hand assets to a third party without a visible transfer.
            c.needsMasterCall = true;
        }
    }

    function _isOwnerManagement(bytes4 sel) private pure returns (bool) {
        return sel == SEL_ADD_OWNER || sel == SEL_REMOVE_OWNER || sel == SEL_SWAP_OWNER || sel == SEL_CHANGE_THRESHOLD;
    }

    function _txHash(Ctx memory c, bytes calldata data) private view returns (bytes32) {
        c.tx.typehash = SAFE_TX_TYPEHASH;
        c.tx.dataHash = keccak256(data);
        // Safe 1.3.0 increments the nonce before calling the guard, so the signed hash uses nonce - 1.
        c.tx.nonce = ISafe(c.safe).nonce() - 1;
        return keccak256(
            abi.encodePacked(bytes1(0x19), bytes1(0x01), ISafe(c.safe).domainSeparator(), keccak256(abi.encode(c.tx)))
        );
    }

    /// @dev Only the first `threshold` signatures count: the Safe verified them as distinct owners, so anyone
    /// who is not the Master or the Server is an employee.
    function _signers(Ctx memory c, bytes calldata data, bytes memory signatures)
        private
        view
        returns (bool server, bool master, uint256 employees, uint256 threshold)
    {
        bytes32 txHash = _txHash(c, data);
        threshold = ISafe(c.safe).getThreshold();
        uint256 n = threshold;
        if (n > signatures.length / 65) n = signatures.length / 65;
        for (uint256 i; i < n; i++) {
            (uint8 v, bytes32 r, bytes32 s) = _signatureSplit(signatures, i);
            address signer;
            if (v == 0 || v == 1) {
                signer = address(uint160(uint256(r)));
            } else if (v > 30) {
                signer = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", txHash)), v - 4, r, s);
            } else {
                signer = ecrecover(txHash, v, r, s);
            }
            if (signer == c.master) {
                // An approved-hash or contract signature would let a Master address with code, or a Master key
                // that sent a transaction, satisfy the rule without signing this one.
                require(v >= 27, "Master must sign with ECDSA");
                master = true;
            } else if (signer == c.server) {
                // An approved-hash or contract signature would let a Server address with code, or a Server key
                // that sent a transaction, satisfy the rule without signing this one.
                require(v == 27 || v == 28, "Server must sign with ECDSA");
                server = true;
            }
            else employees++;
        }
    }

    /// @dev Same layout the Safe reads: {bytes32 r}{bytes32 s}{uint8 v}, 65 bytes each. Bounds are
    /// checked by the caller (`i < signatures.length / 65`).
    function _signatureSplit(bytes memory signatures, uint256 pos)
        private
        pure
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        assembly ("memory-safe") {
            let signaturePos := mul(0x41, pos)
            r := mload(add(signatures, add(signaturePos, 0x20)))
            s := mload(add(signatures, add(signaturePos, 0x40)))
            v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)
        }
    }

    /// @notice Run through a Safe transaction signed by the Master, after the swapOwner that replaces the old
    /// Master. Ownership of the new Master is enforced in `checkAfterExecution`.
    function setMaster(address newMaster) external {
        Vault storage v = _requireOrg(msg.sender);
        // A zero Master would turn the vault into a personal one and switch every rule off.
        require(newMaster != address(0), "Master cannot be zero");
        require(newMaster != v.server, "Server and Master must differ");
        require(!ISafe(msg.sender).isOwner(v.master), "Previous Master must be removed");
        v.master = newMaster;
        emit MasterChanged(msg.sender, newMaster);
    }

    /// @notice Run through a Safe transaction signed by the Master, after the swapOwner that replaces the old
    /// Server. Ownership of the new Server is enforced in `checkAfterExecution`.
    function setServer(address newServer) external {
        Vault storage v = _requireOrg(msg.sender);
        require(newServer != address(0), "Server cannot be zero");
        require(newServer != v.master, "Server and Master must differ");
        // A previous Server left as owner would count as an employee: two seats for one key.
        require(!ISafe(msg.sender).isOwner(v.server), "Previous Server must be removed");
        v.server = newServer;
        emit ServerChanged(msg.sender, newServer);
    }

    function _requireOrg(address safe) private view returns (Vault storage v) {
        v = _vaults[safe];
        require(v.master != address(0), "Only organization vaults have a Master and a Server");
    }

    function vaultState(address safe) external view returns (bool registered, address master, address server) {
        Vault storage v = _vaults[safe];
        return (v.registered, v.master, v.server);
    }
}

src/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface IERC165 {
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/interfaces/ISafe.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

interface ISafe {
    function isOwner(address owner) external view returns (bool);

    function getThreshold() external view returns (uint256);

    function nonce() external view returns (uint256);

    function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);

    function domainSeparator() external view returns (bytes32);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris",
  "remappings": [
    "@safe/=dependencies/safe-smart-account-1.3.0/contracts/",
    "forge-std/=dependencies/forge-std-1.17.0/src/",
    "forge-std-1.17.0/=dependencies/forge-std-1.17.0/src/",
    "safe-smart-account-1.3.0/=dependencies/safe-smart-account-1.3.0/contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.