Skip to content
Verified contractExactMIT

SecureMultisigWallet

Address0xe4d5a78bf9a5f2ffac291ddd1e4f79ea22083c9a
Balance

0.00001 ETH

 

Transactions

71

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
No
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,336,407
Creation transaction
0xb9790203f3…ea288e41bf

contracts/multisig.sol

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

import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";

/// @title Secure Multisig Wallet (v2)
/// @notice Generic EVM wallet for ETH, tokens, NFTs and arbitrary contract calls.
/// @dev Owner/threshold changes must be executed through this wallet itself.
///
/// Changes vs v1:
///  1. Receives ERC721 / ERC1155 safely (ERC721Holder, ERC1155Holder + ERC165).
///  2. `configNonce`: any owner/threshold change invalidates all pending txs,
///     so stale approvals can never be revived.
///  3. Every tx has a deadline (TX_LIFETIME) and can be cancelled by its proposer.
///  4. Calls with calldata to addresses without code revert instead of
///     silently "succeeding".
contract SecureMultisigWallet is ERC721Holder, ERC1155Holder {
    uint256 public constant MIN_APPROVALS = 3;
    uint256 public constant MAX_OWNERS = 50;
    uint256 public constant TX_LIFETIME = 7 days;

    struct Transaction {
        address target;
        bool executed;
        bool cancelled;
        address proposer;
        uint64 deadline;
        uint256 configNonce;
        uint256 value;
        bytes data;
    }

    address[] private owners;
    mapping(address => bool) public isOwner;

    uint256 public requiredApprovals;

    /// @notice Incremented on every owner/threshold change.
    uint256 public configNonce;

    Transaction[] private transactions;

    // txId => owner => approved
    mapping(uint256 => mapping(address => bool)) public isConfirmed;

    uint256 private locked = 1;

    error Unauthorized();
    error InvalidAddress();
    error InvalidOwnerCount();
    error InvalidThreshold();
    error InvalidTransaction();
    error AlreadyConfirmed();
    error NotConfirmed();
    error AlreadyExecuted();
    error AlreadyCancelled();
    error TransactionExpired();
    error StaleConfig();
    error TargetNotContract();
    error InsufficientApprovals(uint256 actual, uint256 required);
    error ReentrantCall();

    event Deposit(address indexed sender, uint256 amount);
    event TransactionSubmitted(
        uint256 indexed txId,
        address indexed proposer,
        address indexed target,
        uint256 value,
        uint256 deadline
    );
    event TransactionConfirmed(uint256 indexed txId, address indexed owner);
    event ConfirmationRevoked(uint256 indexed txId, address indexed owner);
    event TransactionExecuted(uint256 indexed txId, address indexed executor);
    event TransactionCancelled(uint256 indexed txId, address indexed owner);
    event OwnerAdded(address indexed owner);
    event OwnerRemoved(address indexed owner);
    event ThresholdChanged(uint256 oldThreshold, uint256 newThreshold);
    event ConfigNonceChanged(uint256 newNonce);

    modifier onlyOwner() {
        if (!isOwner[msg.sender]) revert Unauthorized();
        _;
    }

    modifier nonReentrant() {
        if (locked != 1) revert ReentrantCall();
        locked = 2;
        _;
        locked = 1;
    }

    modifier onlyWallet() {
        if (msg.sender != address(this)) revert Unauthorized();
        _;
    }

    constructor(address[] memory initialOwners, uint256 threshold) {
        uint256 count = initialOwners.length;

        if (count < MIN_APPROVALS || count > MAX_OWNERS) {
            revert InvalidOwnerCount();
        }

        if (threshold < MIN_APPROVALS || threshold > count) {
            revert InvalidThreshold();
        }

        for (uint256 i; i < count; ++i) {
            address owner = initialOwners[i];

            if (owner == address(0) || isOwner[owner]) {
                revert InvalidAddress();
            }

            isOwner[owner] = true;
            owners.push(owner);
            emit OwnerAdded(owner);
        }

        requiredApprovals = threshold;
        emit ThresholdChanged(0, threshold);
    }

    receive() external payable {
        emit Deposit(msg.sender, msg.value);
    }

    // ------------------------------------------------------------------
    // Transaction lifecycle
    // ------------------------------------------------------------------

    /// @notice Submit any EVM contract call or native-asset transfer.
    /// @param target Contract or recipient to call.
    /// @param value Native currency to send, in wei.
    /// @param data ABI-encoded function call; empty for a simple ETH transfer.
    function submitTransaction(
        address target,
        uint256 value,
        bytes calldata data
    ) external onlyOwner returns (uint256 txId) {
        if (target == address(0)) revert InvalidAddress();

        txId = transactions.length;
        uint64 deadline = uint64(block.timestamp + TX_LIFETIME);

        transactions.push(
            Transaction({
                target: target,
                executed: false,
                cancelled: false,
                proposer: msg.sender,
                deadline: deadline,
                configNonce: configNonce,
                value: value,
                data: data
            })
        );

        emit TransactionSubmitted(txId, msg.sender, target, value, deadline);
    }

    /// @notice Approve a pending transaction.
    function confirmTransaction(uint256 txId) external onlyOwner {
        _getActive(txId);
        if (isConfirmed[txId][msg.sender]) revert AlreadyConfirmed();

        isConfirmed[txId][msg.sender] = true;
        emit TransactionConfirmed(txId, msg.sender);
    }

    /// @notice Revoke your approval before execution.
    function revokeConfirmation(uint256 txId) external onlyOwner {
        if (txId >= transactions.length) revert InvalidTransaction();
        if (transactions[txId].executed) revert AlreadyExecuted();
        if (!isConfirmed[txId][msg.sender]) revert NotConfirmed();

        isConfirmed[txId][msg.sender] = false;
        emit ConfirmationRevoked(txId, msg.sender);
    }

    /// @notice Cancel a pending transaction. Only its proposer can do this.
    /// @dev Other owners can simply refuse to approve; the tx also dies on
    ///      expiry or on any owner/threshold change.
    function cancelTransaction(uint256 txId) external onlyOwner {
        if (txId >= transactions.length) revert InvalidTransaction();

        Transaction storage txn = transactions[txId];

        if (txn.executed) revert AlreadyExecuted();
        if (txn.cancelled) revert AlreadyCancelled();
        if (txn.proposer != msg.sender) revert Unauthorized();

        txn.cancelled = true;
        emit TransactionCancelled(txId, msg.sender);
    }

    /// @notice Execute a transaction once it has enough current-owner approvals.
    function executeTransaction(
        uint256 txId
    ) external onlyOwner nonReentrant returns (bytes memory result) {
        Transaction storage txn = _getActive(txId);

        uint256 approvals = _countApprovals(txId);
        if (approvals < requiredApprovals) {
            revert InsufficientApprovals(approvals, requiredApprovals);
        }

        // A call with calldata to an address without code would "succeed"
        // and do nothing (wrong address, wrong chain, not yet deployed).
        if (txn.data.length > 0 && txn.target.code.length == 0) {
            revert TargetNotContract();
        }

        // Effects before interaction; a reverted call rolls this back.
        txn.executed = true;

        (bool success, bytes memory returnData) =
            txn.target.call{value: txn.value}(txn.data);

        // Preserve the called contract's revert data.
        if (!success) {
            assembly ("memory-safe") {
                revert(add(returnData, 0x20), mload(returnData))
            }
        }

        emit TransactionExecuted(txId, msg.sender);
        return returnData;
    }

    // ------------------------------------------------------------------
    // Administration: only callable via a transaction executed by this
    // wallet itself (target = address(this)). Each change bumps
    // `configNonce`, which invalidates every pending transaction.
    // ------------------------------------------------------------------

    function addOwner(address newOwner) external onlyWallet {
        if (newOwner == address(0) || isOwner[newOwner]) {
            revert InvalidAddress();
        }
        if (owners.length >= MAX_OWNERS) revert InvalidOwnerCount();

        isOwner[newOwner] = true;
        owners.push(newOwner);

        _bumpConfig();
        emit OwnerAdded(newOwner);
    }

    function removeOwner(address oldOwner) external onlyWallet {
        if (!isOwner[oldOwner]) revert InvalidAddress();
        if (owners.length - 1 < requiredApprovals) {
            revert InvalidOwnerCount();
        }

        isOwner[oldOwner] = false;

        uint256 length = owners.length;

        for (uint256 i; i < length; ++i) {
            if (owners[i] == oldOwner) {
                owners[i] = owners[length - 1];
                owners.pop();
                break;
            }
        }

        _bumpConfig();
        emit OwnerRemoved(oldOwner);
    }

    function changeThreshold(uint256 newThreshold) external onlyWallet {
        if (
            newThreshold < MIN_APPROVALS ||
            newThreshold > owners.length
        ) {
            revert InvalidThreshold();
        }

        uint256 oldThreshold = requiredApprovals;
        requiredApprovals = newThreshold;

        _bumpConfig();
        emit ThresholdChanged(oldThreshold, newThreshold);
    }

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

    function getOwners() external view returns (address[] memory) {
        return owners;
    }

    function getTransactionCount() external view returns (uint256) {
        return transactions.length;
    }

    function getTransaction(
        uint256 txId
    ) external view returns (Transaction memory txn, uint256 currentApprovals) {
        if (txId >= transactions.length) revert InvalidTransaction();
        txn = transactions[txId];
        currentApprovals = _countApprovals(txId);
    }

    /// @notice Raw approval check (ignores expiry, cancellation, staleness).
    function hasEnoughApprovals(uint256 txId) external view returns (bool) {
        if (txId >= transactions.length) revert InvalidTransaction();
        return _countApprovals(txId) >= requiredApprovals;
    }

    /// @notice True only if the tx could be executed right now (by an owner).
    function isExecutable(uint256 txId) external view returns (bool) {
        if (txId >= transactions.length) revert InvalidTransaction();

        Transaction storage txn = transactions[txId];

        return
            !txn.executed &&
            !txn.cancelled &&
            txn.configNonce == configNonce &&
            block.timestamp <= txn.deadline &&
            _countApprovals(txId) >= requiredApprovals;
    }

    // ------------------------------------------------------------------
    // Internals
    // ------------------------------------------------------------------

    function _getActive(
        uint256 txId
    ) internal view returns (Transaction storage txn) {
        if (txId >= transactions.length) revert InvalidTransaction();

        txn = transactions[txId];

        if (txn.executed) revert AlreadyExecuted();
        if (txn.cancelled) revert AlreadyCancelled();
        if (txn.configNonce != configNonce) revert StaleConfig();
        if (block.timestamp > txn.deadline) revert TransactionExpired();
    }

    /// @dev Counts only approvals from owners who are owners NOW.
    ///      Bounded by MAX_OWNERS.
    function _countApprovals(
        uint256 txId
    ) internal view returns (uint256 approvals) {
        uint256 length = owners.length;
        for (uint256 i; i < length; ++i) {
            if (isConfirmed[txId][owners[i]]) {
                ++approvals;
            }
        }
    }

    function _bumpConfig() internal {
        ++configNonce;
        emit ConfigNonceChanged(configNonce);
    }
}

@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol

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

pragma solidity >=0.6.2;

import {IERC165} from "../../utils/introspection/IERC165.sol";

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.20;

import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 *
 * @custom:stateless
 */
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol

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

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
 * {IERC721-setApprovalForAll}.
 *
 * @custom:stateless
 */
abstract contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

@openzeppelin/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.