Skip to content
Verified contractPartialMIT

AutoSweepControl

Address0x53f2ceffffd626daae1501e2fcea69af5b8d945f
Balance

0 ETH

 

Transactions

99

 

Compiler

solc 0.8.22

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.22+commit.4fc1097e
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
shanghai
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
24,889,844
Creation transaction
0xd4715aec81…bb9dced725
Libraries
src/autosweep/AutoSweepControl.sol:Utils0xcbe7…d23aa6

src/autosweep/AutoSweepControl.sol

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

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { LedgerEntry } from "../utils/Utils.sol";
import { AutoSweepConfig, ManagerConfig } from "./AutoSweepConfig.sol";
import { AutoSweepCallback } from "./AutoSweepCallback.sol";
import { MultisigWalletDeployer } from "./MultisigWalletDeployer.sol";
import { AddressRegistry, AddressInfo } from "../utils/AddressRegistry.sol";
import { Manageable } from "../utils/Manageable.sol";
import { ADDRESS_TYPE_MULTSIG_WALLET } from "./AutoSweepConstants.sol";
import { IInvocable } from "./IInvocable.sol";

contract AutoSweepControl is AutoSweepCallback, AutoSweepConfig, MultisigWalletDeployer, Ownable, IInvocable {
    error NoCallbackImpl();

    constructor(address owner) Ownable(owner) { }

    function initAutoSweepControl(
        address[] calldata initManagers,
        address[] calldata initAdmins,
        uint160 initRequiredAdminApprovals,
        address[] calldata initWalletFactories,
        address[] calldata initWalletConfigs,
        address autoSweepFactory
    )
        public
        virtual
        onlyOwner // only owner can init parameters. After init, renounce owner

    {
        // init sweep config
        super._initAutoSweepConfig(
            initManagers, initAdmins, initRequiredAdminApprovals, initWalletFactories, initWalletConfigs
        );
        // init factory
        super._initAutoSweepDeployer(autoSweepFactory);
        // renounce owner
        renounceOwnership();
    }

    function isManager(address manager) public view override(ManagerConfig, Manageable) returns (bool) {
        return super.isManager(manager);
    }

    function getAddressInfo(address addr)
        public
        view
        override(AddressRegistry, AutoSweepCallback)
        returns (AddressInfo memory info)
    {
        return super.getAddressInfo(addr); // from AddressRegistry
    }

    function _isCallbackInvoker(address) internal pure override(AutoSweepCallback) returns (bool) {
        // No callback implementation
        return false;
    }

    function _callbackRecipient(
        address,
        IERC20,
        address,
        LedgerEntry[] calldata,
        address
    )
        internal
        pure
        override(AutoSweepCallback)
    {
        revert NoCallbackImpl();
    }

    function _isValidWalletFactory(address walletFactory)
        internal
        view
        override(MultisigWalletDeployer)
        returns (bool)
    {
        return isWalletFactory(walletFactory);
    }

    function _isValidWalletConfig(address walletConfig) internal view override(MultisigWalletDeployer) returns (bool) {
        return isWalletConfig(walletConfig);
    }

    function onCreateWalletSuccessfully(
        address walletAddress,
        address walletOwner
    )
        internal
        override(MultisigWalletDeployer)
    {
        // add wallet address to recipient list
        // wallet owner is added to mappedData
        // auto add multisg wallet to recipient
        _addRecipientAddress(ADDRESS_TYPE_MULTSIG_WALLET, walletAddress, true, walletOwner); 
    }

    function pause() external onlyAdmin {
        _pause();
    }

    function canInvoke(
        address recipient,
        address invoker
    )
        external
        view
        override(IInvocable)
        returns (bool isRecipient, bool isInvoker)
    {
        AddressInfo memory info = super.getAddressInfo(recipient);
        return _canInvoke(info, invoker);
    }
}

node_modules/@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

node_modules/@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

node_modules/@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

node_modules/@openzeppelin/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

node_modules/@openzeppelin/contracts/utils/Pausable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

node_modules/@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);
}

src/autosweep/AutoSweepCallback.sol

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

import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { LedgerEntry } from "../utils/Utils.sol";
import { IAddressRegistry, AddressInfo, AddressStatus } from "../utils/AddressRegistry.sol";
import { AutoSweepDeployer } from "./AutoSweepDeployer.sol";

interface IAutoSweepCallback {
    function callback(address invoker, IERC20 token, address recipient, LedgerEntry[] calldata ledgerEntries) external;
}

abstract contract AutoSweepCallback is AutoSweepDeployer, IAutoSweepCallback, IAddressRegistry, Pausable {
    error InvalidRecipient(address addr);
    error InvalidInvoker(address addr);

    function callback(
        address invoker,
        IERC20 token,
        address recipient,
        LedgerEntry[] calldata entries
    )
        external
        override
        whenNotPaused // accept callback if not paused.
        onlySweepContract // from AutoSweepDeployer, only sweep contract can callback

    {
        // check to address status
        AddressInfo memory addressInfo = getAddressInfo(recipient); // from IAddressRegistry

        // validate recipient and invoker
        (bool isRecipient, bool isInvoker) = _canInvoke(addressInfo, invoker);
        if (!isRecipient) {
            revert InvalidRecipient(recipient);
        }
        if (!isInvoker) {
            revert InvalidInvoker(invoker);
        }
        // if need callback
        if (addressInfo.needCallback) {
            _callbackRecipient(invoker, token, recipient, entries, addressInfo.mappedData);
        }
        // TODO audit suggest to add an event
    }

    function _canInvoke(AddressInfo memory info, address invoker)
        internal
        view
        returns (bool isRecipient, bool isInvoker)
    {
        if (info.status != AddressStatus.Empty) {
            isRecipient = (info.status == AddressStatus.Enabled);
            if (info.needCallback) {
                // call _isCallbackInvoker implementation to validate
                isInvoker = _isCallbackInvoker(invoker);
            } else {
                // invoker can only be the owner
                isInvoker = (invoker == info.mappedData);
            }
        }
        // both isRecipient and isInvoker default to be false if address not found. 
    }

    function _isCallbackInvoker(address invoker) internal view virtual returns (bool);

    function _callbackRecipient(
        address invoker,
        IERC20 token,
        address recipient,
        LedgerEntry[] calldata entries,
        address mappedData
    )
        internal
        virtual;

    function getAddressInfo(address addr) public view virtual override returns (AddressInfo memory info);
}

src/autosweep/AutoSweepConfig.sol

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

import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { ProposalVoting } from "../utils/ProposalVoting.sol";
import { AddressRegistry, AddressStatus, InvalidAddressStatus } from "../utils/AddressRegistry.sol";
import { Manageable } from "../utils/Manageable.sol";
import { ProposalVoting } from "../utils/ProposalVoting.sol";
import { Rescueable } from "../utils/Rescueable.sol";
import { AddressProposalVoting } from "../utils/AddressProposalVoting.sol";
import {
    ADDRESS_TYPE_RECIPIENT,
    PROPOSAL_ADD_RECIPIENT_ADDRESS,
    PROPOSAL_DISABLE_RECIPIENT_ADDRESS,
    PROPOSAL_ENABLE_RECIPIENT_ADDRESS,
    PROPOSAL_ADD_MANAGER_ADDRESS,
    PROPOSAL_REMOVE_MANAGER_ADDRESS,
    PROPOSAL_ADD_WALLET_FACTORY_ADDRESS,
    PROPOSAL_REMOVE_WALLET_FACTORY_ADDRESS,
    PROPOSAL_ADD_WALLET_CONFIG_ADDRESS,
    PROPOSAL_REMOVE_WALLET_CONFIG_ADDRESS,
    PROPOSAL_ADD_ADMIN_ADDRESS,
    PROPOSAL_REMOVE_ADMIN_ADDRESS,
    PROPOSAL_REQUIRED_ADMIN_APPROVALS,
    PROPOSAL_SET_RESCUER_ADDRESS,
    PROPOSAL_UNSET_RESCUER,
    PROPOSAL_UNPAUSE,
    PROPOSAL_CATEGORY_RECIPIENT,
    PROPOSAL_CATEGORY_MANAGER,
    PROPOSAL_CATEGORY_WALLET_FACTORY,
    PROPOSAL_CATEGORY_WALLET_CONFIG,
    PROPOSAL_CATEGORY_ADMIN,
    PROPOSAL_CATEGORY_RESCUER,
    PROPOSAL_CATEGORY_PAUSE
} from "../../src/autosweep/AutoSweepConstants.sol";

error ProposalTypeNotSupported();

abstract contract AddressRegistryConfig is Manageable, ProposalVoting, AddressRegistry {
    mapping(uint256 voteId => address recipientOwner) private recipientOwners;

    event ChangeRecipientOwner(address indexed addr, address owner, address manager);

    function _valididateAddRecipientAddress(address addr) private view {
        if (getAddressInfo(addr).status != AddressStatus.Empty) {
            revert InvalidAddressStatus();
        }
    }

    function _valididateDisableRecipientAddress(address addr) private view {
        if (getAddressInfo(addr).status != AddressStatus.Enabled) {
            revert InvalidAddressStatus();
        }
    }

    function _valididateEnableRecipientAddress(address addr) private view {
        if (getAddressInfo(addr).status != AddressStatus.Disabled) {
            revert InvalidAddressStatus();
        }
    }

    function proposeAddRecipientAddress(address addr, address recipientOwner) external onlyAdmin returns (uint256) {
        _valididateAddRecipientAddress(addr);
        uint256 voteId = createProposal({ proposalType: PROPOSAL_ADD_RECIPIENT_ADDRESS, data: uint160(addr) });
        recipientOwners[voteId] = recipientOwner;
        return voteId;
    }

    function proposeDisableRecipientAddress(address addr) external onlyAdmin returns (uint256) {
        _valididateDisableRecipientAddress(addr);
        return createProposal({ proposalType: PROPOSAL_DISABLE_RECIPIENT_ADDRESS, data: uint160(addr) });
    }

    function proposeEnableRecipientAddress(address addr) external onlyAdmin returns (uint256) {
        _valididateEnableRecipientAddress(addr);
        return createProposal({ proposalType: PROPOSAL_ENABLE_RECIPIENT_ADDRESS, data: uint160(addr) });
    }

    function _executeProposalRecipient(uint256 voteId, uint8 proposalType, address addr) internal {
        if (proposalType == PROPOSAL_ADD_RECIPIENT_ADDRESS) {
            // add recipient address
            _valididateAddRecipientAddress(addr);
            // autoAdded = false, manually add recipient
            _addRecipientAddress(ADDRESS_TYPE_RECIPIENT, addr, false, recipientOwners[voteId]); 
        } else if (proposalType == PROPOSAL_DISABLE_RECIPIENT_ADDRESS) {
            // disable recipient address
            _valididateDisableRecipientAddress(addr);
            _setAddressStatus(addr, AddressStatus.Disabled);
        } else if (proposalType == PROPOSAL_ENABLE_RECIPIENT_ADDRESS) {
            // enable recipient address
            _valididateEnableRecipientAddress(addr);
            _setAddressStatus(addr, AddressStatus.Enabled);
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function viewAddRecipientProposal(uint256 voteId)
        external
        view
        returns (uint8 proposalType, address addr, address recipientOwner)
    {
        (proposalType, addr) = viewAddressProposal(voteId);
        recipientOwner = recipientOwners[voteId];
    }

    function changeRecipientOwner(address addr, address recipientOwner) external onlyManager{
        _setMappedData(ADDRESS_TYPE_RECIPIENT, addr, recipientOwner);
        emit ChangeRecipientOwner(addr, recipientOwner, _msgSender());
    }
}

abstract contract AdminConfig is AddressProposalVoting {
    uint256 private constant MAX_ADMINS = 20;

    // Require at least 3 admins
    uint256 private constant MIN_ADMINS = 3;
    // Require at least 2 admin approvals
    uint256 private constant MIN_REQUIRED_APPROVALS = 2;
    // At least 1 admin more than the required approvals
    uint256 private constant MIN_REDUNDANT_ADMINS = 1;

    address[] private _adminAddresses;
    mapping(address admin => bool enable) private _adminAddressMap;
    uint160 private _requiredAdminApprovals;

    error InvalidAdminApprovals(uint160 requiredAdminApprovals);

    function _initAdminConfig(address[] calldata initAdmins, uint160 initRequiredAdminApprovals) internal {
        // check requiredAdminApprovals
        uint256 initAdminsLength = initAdmins.length;
        validateAdminsNumber(initRequiredAdminApprovals, initAdminsLength);
        // init
        _initAddressConfig(_adminAddresses, _adminAddressMap, initAdmins);
        _requiredAdminApprovals = initRequiredAdminApprovals;
    }

    modifier checkAdminsNumber() {
        _;
        _checkAdminsNumber();
    }

    function _checkAdminsNumber() private view {
        validateAdminsNumber(_requiredAdminApprovals, _adminAddresses.length);
    }

    function validateAdminsNumber(uint160 requiredAdminApprovals_, uint256 adminsLength) private pure {
        // check admin number between ${MIN_ADMINS} and ${MAX_ADMINS}
        _validateMaxLimit(adminsLength, MAX_ADMINS);
        _validateMinLimit(adminsLength, MIN_ADMINS);

        // at least ${MIN_REQUIRED_APPROVALS} approvals required.
        // number of admins at least ${MIN_REDUNDANT_ADMINS} more than approvals required.
        if (
            requiredAdminApprovals_ < MIN_REQUIRED_APPROVALS
                || adminsLength - MIN_REDUNDANT_ADMINS < requiredAdminApprovals_
        ) {
            revert InvalidAdminApprovals(requiredAdminApprovals_);
        }
    }

    function proposeAddAdmin(address adminAddress) external onlyAdmin returns (uint256) {
        return _proposeAddAddress(PROPOSAL_ADD_ADMIN_ADDRESS, _adminAddressMap, adminAddress);
    }

    function proposeRemoveAdmin(address adminAddress) external onlyAdmin returns (uint256) {
        return _proposeRemoveAddress(PROPOSAL_REMOVE_ADMIN_ADDRESS, _adminAddressMap, adminAddress);
    }

    function proposeRequiredAdminApprovals(uint160 requiredAdminApprovals_) external onlyAdmin returns (uint256) {
        validateAdminsNumber(requiredAdminApprovals_, _adminAddresses.length);
        return createProposal({ proposalType: PROPOSAL_REQUIRED_ADMIN_APPROVALS, data: requiredAdminApprovals_ });
    }

    function _executeProposalAdmin(uint8 proposalType, uint160 data) internal checkAdminsNumber {
        if (proposalType == PROPOSAL_ADD_ADMIN_ADDRESS) {
            // add admin
            _executeAddAddress(_adminAddresses, _adminAddressMap, address(data));
        } else if (proposalType == PROPOSAL_REMOVE_ADMIN_ADDRESS) {
            // remove admin
            _executeRemoveAddress(_adminAddresses, _adminAddressMap, address(data));
        } else if (proposalType == PROPOSAL_REQUIRED_ADMIN_APPROVALS) {
            // change required admin approvals
            _requiredAdminApprovals = data;
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function admins() public view override returns (address[] memory) {
        return _adminAddresses;
    }

    function isAdmin(address adminAddress) public view override returns (bool) {
        return _adminAddressMap[adminAddress];
    }

    function requiredApprovals() public view override returns (uint160) {
        return _requiredAdminApprovals;
    }
}

abstract contract ManagerConfig is Manageable, AddressProposalVoting {
    uint256 private constant MAX_MANAGERS = 100;

    address[] private _managerAddresses;
    mapping(address manager => bool enable) private _managerAddressMap;

    function _initManagerConfig(address[] memory initManagers) internal {
        _initAddressConfig(_managerAddresses, _managerAddressMap, initManagers);
    }

    function proposeAddManager(address managerAddress) external onlyAdmin returns (uint256) {
        return _proposeAddAddress(PROPOSAL_ADD_MANAGER_ADDRESS, _managerAddressMap, managerAddress);
    }

    function proposeRemoveManager(address managerAddress) external onlyAdmin returns (uint256) {
        return _proposeRemoveAddress(PROPOSAL_REMOVE_MANAGER_ADDRESS, _managerAddressMap, managerAddress);
    }

    function _executeProposalManager(uint8 proposalType, address addr) internal {
        if (proposalType == PROPOSAL_ADD_MANAGER_ADDRESS) {
            // add manager
            _executeAddAddress(_managerAddresses, _managerAddressMap, addr);
            // managers number no more than ${MAX_MANAGERS}
            _validateMaxLimit(_managerAddresses.length, MAX_MANAGERS);
        } else if (proposalType == PROPOSAL_REMOVE_MANAGER_ADDRESS) {
            // remove manager
            _executeRemoveAddress(_managerAddresses, _managerAddressMap, addr);
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function managers() external view returns (address[] memory) {
        return _managerAddresses;
    }

    function isManager(address manager) public view virtual override(Manageable) returns (bool) {
        return _managerAddressMap[manager];
    }
}

abstract contract WalletFactoryAddressConfig is AddressProposalVoting {
    uint256 private constant MAX_FACTORIES = 100;

    address[] private _walletFactoryAddresses;
    mapping(address walletFactoryAddress => bool enable) private _walletFactoryAddressMap;

    function _initWalletFactoryAddressConfig(address[] memory initWalletFactoies) internal {
        _initAddressConfig(_walletFactoryAddresses, _walletFactoryAddressMap, initWalletFactoies);
    }

    function proposeAddWalletFactory(address walletFactoryAddress) external onlyAdmin returns (uint256) {
        return _proposeAddAddress(PROPOSAL_ADD_WALLET_FACTORY_ADDRESS, _walletFactoryAddressMap, walletFactoryAddress);
    }

    function proposeRemoveWalletFactory(address walletFactoryAddress) external onlyAdmin returns (uint256) {
        return
            _proposeRemoveAddress(
                PROPOSAL_REMOVE_WALLET_FACTORY_ADDRESS, _walletFactoryAddressMap, walletFactoryAddress
            );
    }

    function _executeProposalWalletFactory(uint8 proposalType, address addr) internal {
        if (proposalType == PROPOSAL_ADD_WALLET_FACTORY_ADDRESS) {
            // add wallet factory
            _executeAddAddress(_walletFactoryAddresses, _walletFactoryAddressMap, addr);
            // factories number no more than ${MAX_FACTORIES}
            _validateMaxLimit(_walletFactoryAddresses.length, MAX_FACTORIES);
        } else if (proposalType == PROPOSAL_REMOVE_WALLET_FACTORY_ADDRESS) {
            // remove wallet factory
            _executeRemoveAddress(_walletFactoryAddresses, _walletFactoryAddressMap, addr);
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function walletFactories() external view returns (address[] memory) {
        return _walletFactoryAddresses;
    }

    function isWalletFactory(address walletFactoryAddress) public view returns (bool) {
        return _walletFactoryAddressMap[walletFactoryAddress];
    }
}

abstract contract WalletConfigAddressConfig is AddressProposalVoting {
    uint256 private constant MAX_CONFIGS = 100;

    address[] private _walletConfigAddresses;
    mapping(address walletConfigAddress => bool enable) private _walletConfigAddressMap;

    function _initWalletConfigAddressConfig(address[] memory initWalletConfigs) internal {
        _initAddressConfig(_walletConfigAddresses, _walletConfigAddressMap, initWalletConfigs);
    }

    function proposeAddWalletConfig(address walletConfigAddress) external onlyAdmin returns (uint256) {
        return _proposeAddAddress(PROPOSAL_ADD_WALLET_CONFIG_ADDRESS, _walletConfigAddressMap, walletConfigAddress);
    }

    function proposeRemoveWalletConfig(address walletConfigAddress) external onlyAdmin returns (uint256) {
        return
            _proposeRemoveAddress(PROPOSAL_REMOVE_WALLET_CONFIG_ADDRESS, _walletConfigAddressMap, walletConfigAddress);
    }

    function _executeProposalWalletConfig(uint8 proposalType, address addr) internal {
        if (proposalType == PROPOSAL_ADD_WALLET_CONFIG_ADDRESS) {
            // add wallet config
            _executeAddAddress(_walletConfigAddresses, _walletConfigAddressMap, addr);
            // configs number no more than ${MAX_CONFIGS}
            _validateMaxLimit(_walletConfigAddresses.length, MAX_CONFIGS);
        } else if (proposalType == PROPOSAL_REMOVE_WALLET_CONFIG_ADDRESS) {
            // remove wallet config
            _executeRemoveAddress(_walletConfigAddresses, _walletConfigAddressMap, addr);
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function walletConfigs() external view returns (address[] memory) {
        return _walletConfigAddresses;
    }

    function isWalletConfig(address walletConfigAddress) public view returns (bool) {
        return _walletConfigAddressMap[walletConfigAddress];
    }
}

abstract contract RescurerConfig is ProposalVoting, Rescueable {
    address private _rescuer;

    function _initRescuerConfig() internal {
        _rescuer = address(0);
    }

    function proposeSetRescuer(address proposedRescuer) external onlyAdmin returns (uint256) {
        if (proposedRescuer == address(0)) {
            revert InvalidAddress();
        }
        if (_rescuer == proposedRescuer) {
            revert AddressAlreadyExisted();
        }
        // emit create proposal event
        return createProposal({ proposalType: PROPOSAL_SET_RESCUER_ADDRESS, data: uint160(proposedRescuer) });
    }

    function proposeUnsetRescuer() external onlyAdmin returns (uint256) {
        return createProposal({ proposalType: PROPOSAL_UNSET_RESCUER, data: 0 });
    }

    function _executeProposalRescuer(uint8 proposalType, address addr) internal {
        if (proposalType == PROPOSAL_SET_RESCUER_ADDRESS) {
            // set rescuer
            _rescuer = addr;
        } else if (proposalType == PROPOSAL_UNSET_RESCUER) {
            // unset rescuer
            _rescuer = address(0);
        } else {
            revert ProposalTypeNotSupported();
        }
    }

    function rescuer() public view override returns (address) {
        return _rescuer;
    }
}

abstract contract PauseConfig is ProposalVoting, Pausable {
    function proposeUnpause() external onlyAdmin whenPaused returns (uint256) {
        return createProposal({ proposalType: PROPOSAL_UNPAUSE, data: 0 });
    }

    function _executeProposePause(uint8 proposalType) internal {
        if (proposalType == PROPOSAL_UNPAUSE) {
            _unpause();
        }
    }
}

abstract contract AutoSweepConfig is
    AddressRegistryConfig,
    AdminConfig,
    ManagerConfig,
    WalletFactoryAddressConfig,
    WalletConfigAddressConfig,
    RescurerConfig,
    PauseConfig
{
    function _initAutoSweepConfig(
        address[] calldata initManagers,
        address[] calldata initAdmins,
        uint160 initRequiredAdminApprovals,
        address[] calldata initWalletFactories,
        address[] calldata initWalletConfigs
    )
        internal
    {
        // init ManagerConfig to set manager
        _initManagerConfig(initManagers);

        // init AdminConfig to set admins
        _initAdminConfig(initAdmins, initRequiredAdminApprovals);

        // init RescurerConfig to set rescuer 0x0 addrdss
        _initRescuerConfig();

        // init wallet factories and configs
        _initWalletFactoryAddressConfig(initWalletFactories);
        _initWalletConfigAddressConfig(initWalletConfigs);
    }

    function getProposalCategory(uint8 proposalType) internal pure returns (uint8) {
        return proposalType & 0xfc;
    }

    function _executeProposal(
        uint256 voteId,
        uint8 proposalType,
        uint160 data
    )
        internal
        virtual
        override
        returns (bool)
    {
        bool obsoletePendingVotes = false;
        uint8 proposalCategory = getProposalCategory(proposalType);
        // execute proposal by type
        if (proposalCategory == PROPOSAL_CATEGORY_RECIPIENT) {
            super._executeProposalRecipient(voteId, proposalType, address(data));
        } else if (proposalCategory == PROPOSAL_CATEGORY_MANAGER) {
            super._executeProposalManager(proposalType, address(data));
        } else if (proposalCategory == PROPOSAL_CATEGORY_WALLET_FACTORY) {
            super._executeProposalWalletFactory(proposalType, address(data));
        } else if (proposalCategory == PROPOSAL_CATEGORY_WALLET_CONFIG) {
            super._executeProposalWalletConfig(proposalType, address(data));
        } else if (proposalCategory == PROPOSAL_CATEGORY_ADMIN) {
            super._executeProposalAdmin(proposalType, data);
            obsoletePendingVotes = true;
        } else if (proposalCategory == PROPOSAL_CATEGORY_RESCUER) {
            super._executeProposalRescuer(proposalType, address(data));
        } else if (proposalCategory == PROPOSAL_CATEGORY_PAUSE) {
            super._executeProposePause(proposalType);
        } else {
            revert ProposalTypeNotSupported();
        }
        return obsoletePendingVotes;
    }

    function isAddressProposal(uint8 proposalType) internal pure virtual override returns (bool) {
        if (
            proposalType == PROPOSAL_ADD_RECIPIENT_ADDRESS || proposalType == PROPOSAL_DISABLE_RECIPIENT_ADDRESS
                || proposalType == PROPOSAL_ENABLE_RECIPIENT_ADDRESS || proposalType == PROPOSAL_ADD_MANAGER_ADDRESS
                || proposalType == PROPOSAL_REMOVE_MANAGER_ADDRESS
                || proposalType == PROPOSAL_ADD_WALLET_FACTORY_ADDRESS
                || proposalType == PROPOSAL_REMOVE_WALLET_FACTORY_ADDRESS
                || proposalType == PROPOSAL_ADD_WALLET_CONFIG_ADDRESS
                || proposalType == PROPOSAL_REMOVE_WALLET_CONFIG_ADDRESS || proposalType == PROPOSAL_ADD_ADMIN_ADDRESS
                || proposalType == PROPOSAL_REMOVE_ADMIN_ADDRESS || proposalType == PROPOSAL_SET_RESCUER_ADDRESS
        ) {
            return true;
        }
        return false;
    }
}

src/autosweep/AutoSweepConstants.sol

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

uint8 constant ADDRESS_TYPE_RECIPIENT = 1;
uint8 constant ADDRESS_TYPE_MULTSIG_WALLET = 2;
uint8 constant ADDRESS_TYPE_AUTO_SWEEP = 3;

uint8 constant PROPOSAL_CATEGORY_RECIPIENT = 4; // 0b0000_0100
uint8 constant PROPOSAL_CATEGORY_MANAGER = 8; // 0b0000_01000
uint8 constant PROPOSAL_CATEGORY_WALLET_FACTORY = 12; //0b0000_1100
uint8 constant PROPOSAL_CATEGORY_WALLET_CONFIG = 16; //0b0001_0000
uint8 constant PROPOSAL_CATEGORY_ADMIN = 20; //0b0001_0100
uint8 constant PROPOSAL_CATEGORY_RESCUER = 24; //0b0001_1000
uint8 constant PROPOSAL_CATEGORY_PAUSE = 28; //0b0001_1100

uint8 constant PROPOSAL_ADD_RECIPIENT_ADDRESS = PROPOSAL_CATEGORY_RECIPIENT | 0x0; // 4
uint8 constant PROPOSAL_DISABLE_RECIPIENT_ADDRESS = PROPOSAL_CATEGORY_RECIPIENT | 0x1; // 5
uint8 constant PROPOSAL_ENABLE_RECIPIENT_ADDRESS = PROPOSAL_CATEGORY_RECIPIENT | 0x2; // 6

uint8 constant PROPOSAL_ADD_MANAGER_ADDRESS = PROPOSAL_CATEGORY_MANAGER | 0x0; // 8
uint8 constant PROPOSAL_REMOVE_MANAGER_ADDRESS = PROPOSAL_CATEGORY_MANAGER | 0x1; // 9

uint8 constant PROPOSAL_ADD_WALLET_FACTORY_ADDRESS = PROPOSAL_CATEGORY_WALLET_FACTORY | 0x0; // 12
uint8 constant PROPOSAL_REMOVE_WALLET_FACTORY_ADDRESS = PROPOSAL_CATEGORY_WALLET_FACTORY | 0x1; // 13

uint8 constant PROPOSAL_ADD_WALLET_CONFIG_ADDRESS = PROPOSAL_CATEGORY_WALLET_CONFIG | 0x0; // 16
uint8 constant PROPOSAL_REMOVE_WALLET_CONFIG_ADDRESS = PROPOSAL_CATEGORY_WALLET_CONFIG | 0x1; // 17

uint8 constant PROPOSAL_ADD_ADMIN_ADDRESS = PROPOSAL_CATEGORY_ADMIN | 0x0; // 20
uint8 constant PROPOSAL_REMOVE_ADMIN_ADDRESS = PROPOSAL_CATEGORY_ADMIN | 0x1; // 21
uint8 constant PROPOSAL_REQUIRED_ADMIN_APPROVALS = PROPOSAL_CATEGORY_ADMIN | 0x2; // 22

uint8 constant PROPOSAL_SET_RESCUER_ADDRESS = PROPOSAL_CATEGORY_RESCUER | 0x0; // 24
uint8 constant PROPOSAL_UNSET_RESCUER = PROPOSAL_CATEGORY_RESCUER | 0x1; // 25

uint8 constant PROPOSAL_UNPAUSE = PROPOSAL_CATEGORY_PAUSE | 0x0; // 28

src/autosweep/AutoSweepDeployer.sol

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

import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { AddressInfo, AddressStatus, InvalidAddressStatus } from "../utils/AddressRegistry.sol";
import { Manageable } from "../utils/Manageable.sol";
import { IAutoSweepFactory } from "./IAutoSweepFactory.sol";
import { ADDRESS_TYPE_AUTO_SWEEP } from "../../src/autosweep/AutoSweepConstants.sol";

abstract contract AutoSweepDeployer is Manageable, Context {
    mapping(address autoSweepContract => AddressInfo info) private autoSweepContracts;
    IAutoSweepFactory private _autoSweepFactory;
    
    event CreateAutoSweep(uint160 indexed id, address contractAddr, address manager);
    event ChangeSweepStatus(uint160 indexed id, address contractAddr, AddressStatus status, address manager);

    error NotAuthorizedContract();

    function _initAutoSweepDeployer(address autoSweepFactory) internal {
        _autoSweepFactory = IAutoSweepFactory(autoSweepFactory);
    }

    function getAutoSweepAddressInfo(address contractAddress) public view returns (AddressInfo memory info) {
        info = autoSweepContracts[contractAddress];
    }

    function _setAutoSweepAddressInfo(
        address contractAddress,
        AddressInfo memory addressInfo
    )
        private
    {
        autoSweepContracts[contractAddress] = addressInfo;
    }

    function createAutoSweep(uint160 id) external onlyManager returns (address) {
        address contractAddress = _autoSweepFactory.createAutoSweep(id);
        _setAutoSweepAddressInfo(
            contractAddress,
            AddressInfo({
                addressType: ADDRESS_TYPE_AUTO_SWEEP,
                status: AddressStatus.Enabled,
                autoAdded: true,
                needCallback: false,
                mappedData: address(id) // convert id to address to store in mappedData
            })
        );
        emit CreateAutoSweep(id, contractAddress, _msgSender());
        return contractAddress;
    }

    function getAutoSweepAddress(uint160 id) external view returns (address addr, bool deployed) {
        (addr, deployed) = _autoSweepFactory.getAutoSweepAddress(id);
    }

    function getAutoSweepFactory() external view returns (address) {
        return address(_autoSweepFactory);
    }

    function enableSweepContract(address contractAddress) external onlyManager {
        AddressInfo memory info = getAutoSweepAddressInfo(contractAddress);
        if (info.status != AddressStatus.Disabled) {
            revert InvalidAddressStatus();
        }
        info.status = AddressStatus.Enabled;
        _setAutoSweepAddressInfo(contractAddress, info);
        emit ChangeSweepStatus(uint160(info.mappedData), contractAddress, AddressStatus.Enabled, _msgSender());
    }

    function disableSweepContract(address contractAddress) external onlyManager {
        AddressInfo memory info = getAutoSweepAddressInfo(contractAddress);
        if (info.status != AddressStatus.Enabled) {
            revert InvalidAddressStatus();
        }
        info.status = AddressStatus.Disabled;
        _setAutoSweepAddressInfo(contractAddress, info);
        emit ChangeSweepStatus(uint160(info.mappedData), contractAddress, AddressStatus.Disabled, _msgSender());
    }

    modifier onlySweepContract() {
        _onlySweepContract();
        _;
    }

    function _onlySweepContract() private view {
        if (getAutoSweepAddressInfo(_msgSender()).status != AddressStatus.Enabled) {
            revert NotAuthorizedContract();
        }
    }
}

src/autosweep/IAutoSweepFactory.sol

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

interface IAutoSweepFactory {
    function createAutoSweep(uint160 id) external returns (address);

    function getAutoSweepAddress(uint160 id) external view returns (address addr, bool deployed);
}

src/autosweep/IInvocable.sol

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

interface IInvocable {
    function canInvoke(address recipient, address invoker) external returns (bool isRecipient, bool isInvoker);
}

src/autosweep/MultisigWalletDeployer.sol

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

import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { Manageable } from "../utils/Manageable.sol";
import { Utils } from "../utils/Utils.sol";

interface IMultisigWalletFactory {
    struct Config {
        uint256 concurrentTxNumber;
        address configAddress;
    }

    function getConfigByVersion(uint256 version) external view returns (Config memory);

    function createWallet(address owner, uint256 version) external returns (address);
}

abstract contract MultisigWalletDeployer is Manageable, Context {

    error NotAuthorizedWalletFactory();
    error NotAuthorizedWalletConfig();
    error InvalidOwner();

    event CreateWallet(address indexed walletAddress, address authorizedManager, address owner);

    function authorizeManager(
        address factoryAddress,
        address configAddress,
        address owner,
        uint256 version,
        bytes calldata signature
    )
        public
        view
        returns (bool authorized, address manager)
    {
        // call should be authorized by a manager
        if (signature.length == 0) {
            // no signature, check message sender
            manager = _msgSender();
        } else {
            // or authorized by manager
            // recover address
            manager =
                Utils.recoverAuthorizedAddress(address(this), factoryAddress, configAddress, owner, version, signature);
        }
        // check only manager can create wallet, else revert NotAuthorizedManager
        authorized = isManager(manager);
    }

    function createWallet(
        address factoryAddress,
        address owner,
        uint256 version,
        bytes calldata signature
    )
        external
        returns (address walletAddress)
    {
        if(owner == address(0)){
            revert InvalidOwner();
        }
        address configAddress = IMultisigWalletFactory(factoryAddress).getConfigByVersion(version).configAddress;
        // check manager authorization
        (bool authorized, address manager) = authorizeManager(factoryAddress, configAddress, owner, version, signature);
        if (!authorized) {
            revert NotAuthorizedManager();
        }
        // validate factory address
        if (!_isValidWalletFactory(factoryAddress)) {
            revert NotAuthorizedWalletFactory();
        }
        // validate config address
        if (!_isValidWalletConfig(configAddress)) {
            revert NotAuthorizedWalletConfig();
        }
        // deploy multisig wallet
        walletAddress = IMultisigWalletFactory(factoryAddress).createWallet(owner, version);

        onCreateWalletSuccessfully(walletAddress, owner);

        emit CreateWallet(walletAddress, manager, owner);
    }

    function _isValidWalletFactory(address walletFactory) internal view virtual returns (bool);

    function _isValidWalletConfig(address walletConfig) internal view virtual returns (bool);

    function onCreateWalletSuccessfully(address walletAddress, address walletOwner) internal virtual;
}

src/utils/AddressProposalVoting.sol

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

import { ProposalVoting } from "./ProposalVoting.sol";
import { Utils } from "./Utils.sol";

abstract contract AddressProposalVoting is ProposalVoting {

    error ExcessMaxLimit();
    error BelowMinLimit();

    function _initAddressConfig(
        address[] storage arrayStorage,
        mapping(address addr => bool enable) storage mapStorage,
        address[] memory initAddresses
    )
        internal
    {
        uint256 initAddressesLength = initAddresses.length;
        for (uint256 i = 0; i < initAddressesLength;) {
            _addAddress(arrayStorage, mapStorage, initAddresses[i]);
            unchecked {
                ++i;
            }
        }
    }

    function _addAddress(
        address[] storage arrayStorage,
        mapping(address addr => bool enable) storage mapStorage,
        address addr
    )
        private
    {
        if (addr == address(0)) {
            revert InvalidAddress();
        }
        if (mapStorage[addr]) {
            revert AddressAlreadyExisted();
        }
        arrayStorage.push(addr);
        mapStorage[addr] = true;
    }

    function _proposeAddAddress(
        uint8 proposalType,
        mapping(address addr => bool enable) storage mapStorage,
        address addr
    )
        internal
        returns (uint256)
    {
        if (addr == address(0)) {
            revert InvalidAddress();
        }
        if (mapStorage[addr]) {
            revert AddressAlreadyExisted();
        }
        // emit create proposal event
        return createProposal({ proposalType: proposalType, data: uint160(addr) });
    }

    function _proposeRemoveAddress(
        uint8 proposalType,
        mapping(address addr => bool enable) storage mapStorage,
        address addr
    )
        internal
        returns (uint256)
    {
        if (!mapStorage[addr]) {
            revert InvalidAddress();
        }
        // emit create proposal event
        return createProposal({ proposalType: proposalType, data: uint160(addr) });
    }

    function _executeAddAddress(
        address[] storage arrayStorage,
        mapping(address addr => bool enable) storage mapStorage,
        address addr
    )
        internal
    {
        _addAddress(arrayStorage, mapStorage, addr);
    }

    function _executeRemoveAddress(
        address[] storage arrayStorage,
        mapping(address addr => bool enable) storage mapStorage,
        address addr
    )
        internal
    {
        uint256 i = Utils.requireIn(addr, arrayStorage);
        uint256 lastIndex = arrayStorage.length - 1;
        if (i != lastIndex) {
            arrayStorage[i] = arrayStorage[lastIndex]; // replaced with the last one.
        }
        arrayStorage.pop(); // pop dulplicated one
        delete mapStorage[addr];
    }

    function _validateMaxLimit(uint256 addressesLength,uint256 maxLimit) internal pure {
        // no more than ${maxLimit} addresses
        if (addressesLength > maxLimit) {
            revert ExcessMaxLimit();
        }
    }

    function _validateMinLimit(uint256 addressesLength,uint256 minLimit) internal pure {
        // no less than ${minLimit} addresses
        if (addressesLength < minLimit) {
            revert BelowMinLimit();
        }
    }
}

src/utils/AddressRegistry.sol

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

enum AddressStatus {
    Empty,
    Enabled,
    Disabled
}

struct AddressInfo {
    AddressStatus status;
    bool autoAdded;
    bool needCallback;
    uint8 addressType;
    address mappedData;
}

error InvalidAddressStatus();
error AddressNotInitializied();
error AddressInitializied();
error AddressTypeNotMatch();

interface IAddressRegistry {
    function getAddressInfo(address addr) external view returns (AddressInfo memory info);
}

abstract contract AddressRegistry is IAddressRegistry {
    mapping(address addr => AddressInfo info) private addressMap;

    function getAddressInfo(address addr) public view virtual override returns (AddressInfo memory) {
        return addressMap[addr];
    }

    function _addAddress(address addr, AddressInfo memory info) private {
        if (getAddressInfo(addr).status != AddressStatus.Empty) {
            revert AddressInitializied();
        }
        addressMap[addr] = info;
    }

    function _addRecipientAddress(uint8 addressType, address addr, bool autoAdded, address recipientOwner) internal {
        _addAddress(
            addr,
            AddressInfo({
                status: AddressStatus.Enabled,
                autoAdded: autoAdded,
                needCallback: false,
                addressType: addressType,
                // if not needCallback, just only recipientOwner call autosweep contracts
                mappedData: recipientOwner 
            })
        );
    }

    function _addCallbackContractAddress(uint8 addressType, address addr, address mappedData) internal {
        _addAddress(
            addr,
            AddressInfo({
                status: AddressStatus.Enabled,
                autoAdded: true,
                needCallback: true,
                addressType: addressType,
                // if needCallback, mappedData will be passed to callback function.
                mappedData: mappedData 
            })
        );
    }

    function _setAddressStatus(address addr, AddressStatus status) internal {
        AddressInfo memory info = getAddressInfo(addr);
        if (status == AddressStatus.Empty) {
            revert InvalidAddressStatus();
        }
        if (info.status == AddressStatus.Empty) {
            revert AddressNotInitializied();
        }
        info.status = status;
        addressMap[addr] = info;
    }

    function _setMappedData(uint8 addressType, address addr, address mappedData) internal {
        AddressInfo memory info = getAddressInfo(addr);
        if (info.addressType != addressType) {
            revert AddressTypeNotMatch();
        }
        if (info.status == AddressStatus.Empty) {
            revert AddressNotInitializied();
        }
        info.mappedData = mappedData;
        addressMap[addr] = info;
    }
}

src/utils/Manageable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

interface IManageable {
    function isManager(address manager) external view returns (bool);
}

abstract contract Manageable is IManageable {
    error NotAuthorizedManager();

    function isManager(address manager) public view virtual override returns (bool);

    modifier onlyManager() {
        _onlyManager(msg.sender);
        _;
    }

    function _onlyManager(address manager) internal view {
        if (!isManager(manager)) {
            revert NotAuthorizedManager();
        }
    }
}

src/utils/ProposalVoting.sol

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

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

abstract contract ProposalVoting is Voting {
    struct Proposal {
        uint8 proposalType;
        uint160 data;
    }

    mapping(uint256 voteId => Proposal proposal) internal proposals;

    event CreateProposal(uint256 indexed voteId, uint8 proposalType, uint160 data, address admin);
    event ExecuteProposal(uint256 indexed voteId, uint8 proposalType, uint160 data, address admin);

    error InvalidAddress();
    error AddressAlreadyExisted();
    error NotAddressProposal();

    function createProposal(uint8 proposalType, uint160 data) internal returns (uint256) {
        uint256 voteId = Voting.createVote();
        proposals[voteId] = Proposal({ proposalType: proposalType, data: data });
        emit CreateProposal(voteId, proposalType, data, _msgSender());
        return voteId;
    }

    function executeVote(uint256 voteId) internal override(Voting) returns (bool) {
        Proposal memory proposal = proposals[voteId];
        uint8 proposalType = proposal.proposalType;
        uint160 data = proposal.data;
        bool obsoletePendingVotes = _executeProposal(voteId, proposalType, data);
        // emit execute proposal event
        emit ExecuteProposal(voteId, proposalType, data, _msgSender());
        return obsoletePendingVotes;
    }

    function _executeProposal(uint256 voteId, uint8 proposalType, uint160 data) internal virtual returns (bool);

    function viewProposal(uint256 voteId) public view returns (Proposal memory proposal) {
        return proposals[voteId];
    }

    function viewAddressProposal(uint256 voteId) public view returns (uint8 proposalType, address addr) {
        Proposal memory proposal = proposals[voteId];
        proposalType = proposal.proposalType;
        if (isAddressProposal(proposalType)) {
            addr = address(proposal.data);
        } else {
            revert NotAddressProposal();
        }
    }

    function isAddressProposal(uint8 proposalType) internal pure virtual returns (bool);
}

src/utils/Rescueable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

abstract contract Rescueable is Context {
    error RescueableUnauthorizedAccount(address account);
    error FailedToSendEther();
    error RescueableInvalidAccount();

    event Rescue(address indexed token, address indexed to, uint256 amount, address rescuer);

    function rescueNative(address payable recipient, uint256 amount) external onlyRescuer {
        if (recipient == address(0)) {
            revert RescueableInvalidAccount();
        }
        (bool success,) = recipient.call{ value: amount }("");
        if (!success) {
            revert FailedToSendEther();
        }
        emit Rescue(address(0), recipient, amount, _msgSender());
    }

    function rescueERC20(address token, address to, uint256 amount) external onlyRescuer {
        SafeERC20.safeTransfer(IERC20(token), to, amount);
        emit Rescue(token, to, amount, _msgSender());
    }

    modifier onlyRescuer() {
        _onlyRescuer();
        _;
    }

    function _onlyRescuer() private view {
        if (rescuer() != _msgSender()) {
            revert RescueableUnauthorizedAccount(_msgSender());
        }
    }

    function rescuer() public view virtual returns (address);
}

src/utils/Utils.sol

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

import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

struct Pool {
    address tokenIn;
    uint24 fee;
    address tokenOut;
}

struct SwapPath {
    address tokenIn;
    address tokenOut;
    bytes path;
}

struct LedgerEntry {
    address clientAddress;
    uint256 amount;
}

library Utils {
    using ECDSA for bytes32;

    error AddressAlreadyExisted(address addr);
    error AddressNotFound(address addr);
    error InvalidPath();

    /**
     * @dev Require specific address must be in a list
     * @param addr The address to be checked.
     * @param mustInList The address list to be checked.
     */
    function requireIn(address addr, address[] calldata mustInList) public pure returns (uint256) {
        (bool found, uint256 i) = find(addr, mustInList);
        if (!found) {
            revert AddressNotFound(addr);
        }
        return i;
    }

    /**
     * @dev Find specifc address in a list
     * @param addr The address to find
     * @param list The target address list
     * @return found true if the address found
     * @return index the first index of the address in the list
     */
    function find(address addr, address[] calldata list) public pure returns (bool, uint256) {
        uint256 len = list.length;
        for (uint256 i = 0; i < len;) {
            if (addr == list[i]) {
                return (true, i);
            }
            unchecked {
                ++i;
            }
        }
        return (false, 0);
    }

    function composePath(Pool[] memory pools) public pure returns (SwapPath memory) {
        uint256 poolsLength = pools.length;
        address tokenIn = pools[0].tokenIn;
        address tokenOut = pools[poolsLength - 1].tokenOut;
        bytes memory path;

        address lastTokenOut;
        for (uint256 i = 0; i < poolsLength;) {
            Pool memory p = pools[i];
            if (i > 0) {
                if (lastTokenOut != p.tokenIn) {
                    revert InvalidPath();
                }
            }
            path = abi.encodePacked(path, p.tokenIn, p.fee);
            lastTokenOut = p.tokenOut;
            unchecked {
                ++i;
            }
        }
        path = abi.encodePacked(path, lastTokenOut);

        return SwapPath({ tokenIn: tokenIn, tokenOut: tokenOut, path: path });
    }

    function recoverAuthorizedAddress(
        address deployerAddress,
        address factoryAddress,
        address configAddress,
        address owner,
        uint256 version,
        bytes calldata signature
    )
        external
        view
        returns (address authorizedAddress)
    {
        // hash of (chainid, autoSweepControlAddress, factoryAddress, configAddress, owner, version)
        /// forge-lint:disable-next-line(asm-keccak256)
        bytes32 hash = keccak256(abi.encodePacked(block.chainid, deployerAddress, factoryAddress, configAddress, owner, version));
        authorizedAddress = hash.recover(signature);
    }
}

src/utils/Voting.sol

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

import { Context } from "@openzeppelin/contracts/utils/Context.sol";

abstract contract Voting is Context {
    uint256 private constant VOTING_TIME_OUT = 1 days;

    enum Status {
        Empty, /*0*/
        Pending, /*1*/
        Executed, /*2*/
        Expired, /*3*/
        Obsoleted /*4*/
    }

    // combine proposer and status in to VoteInfo
    struct VoteInfo {
        address proposer;
        Status status;
        uint256 creationTime;
    }

    uint256 private _currentVoteId;
    // the vote execution only can move forward
    uint256 private _obsoletedVoteId;

    mapping(uint256 voteId => mapping(address adminAddress => bool vote)) private votes;
    mapping(uint256 voteId => VoteInfo voteInfo) private voteInfos;

    event CreateVoting(uint256 indexed voteId, address admin);
    event ExecuteVoting(uint256 indexed voteId, address admin);

    event ApproveVote(uint256 indexed voteId, address admin);
    event RevokeVote(uint256 indexed voteId, address admin);

    error InvalidVoteStatus(Status status);
    error VoteNotApproved();
    error NotAuthorizedPerson();

    modifier onlyAdmin() {
        _onlyAdmin();
        _;
    }

    function _onlyAdmin() internal view {
        address sender = _msgSender();
        if (!isAdmin(sender)) {
            revert NotAuthorizedPerson();
        }
    }

    function currentVoteId() public view returns (uint256) {
        return _currentVoteId;
    }

    function obsoletedVoteId() public view returns (uint256) {
        return _obsoletedVoteId;
    }

    function getVoteInfo(uint256 voteId) public view returns (VoteInfo memory info) {
        info = voteInfos[voteId];
        if (info.status == Status.Pending) {
            if (voteId <= _obsoletedVoteId) {
                info.status = Status.Obsoleted;
            } else if (block.timestamp > info.creationTime + VOTING_TIME_OUT) {
                info.status = Status.Expired;
            }
        }
    }

    function getVoteInfoForUpdate(uint256 voteId) internal view returns (VoteInfo memory info) {
        info = getVoteInfo(voteId);
        // only pending status can be updated
        if (info.status != Status.Pending) {
            revert InvalidVoteStatus(info.status);
        }
    }

    function createVote() internal onlyAdmin returns (uint256) {
        uint256 voteId = _currentVoteId + 1;
        // Create vote
        _currentVoteId = voteId;
        voteInfos[voteId] = VoteInfo({ proposer: _msgSender(), status: Status.Pending, creationTime: block.timestamp });
        emit CreateVoting(voteId, _msgSender());
        // Approve current vote at once
        _approve(voteId);
        return voteId;
    }

    function execute(uint256 voteId) public onlyAdmin {
        VoteInfo memory info = getVoteInfoForUpdate(voteId);

        // check vote can be executed.
        (, bool approved) = voteResult(voteId);
        if (!approved) {
            revert VoteNotApproved();
        }
        // Execute Vote...
        bool obsoletePendingVotes = executeVote(voteId);
        // mark executed
        info.status = Status.Executed;
        voteInfos[voteId] = info; // update storage
        if (obsoletePendingVotes) {
            // update _obsoletedVoteId to _currentVoteId to obsoleted all votes
            _obsoletedVoteId = _currentVoteId;
        } else {
            // update obsoletedVoteId
            _obsoletedVoteId = voteId;
        }
        emit ExecuteVoting(voteId, _msgSender());
    }

    function admins() public view virtual returns (address[] memory);

    function isAdmin(address adminAddress) public view virtual returns (bool);

    function requiredApprovals() public view virtual returns (uint160);

    /**
     * Implementation Codes to be executed.
     * return flag obsoletePendingVotes to indicate whether to obsolete all pending votes
     * if yes, change _obsoletedVoteId to _currentVoteId
     * @param voteId The vote id
     */
    function executeVote(uint256 voteId) internal virtual returns (bool);

    function approve(uint256 voteId) public onlyAdmin {
        _approve(voteId);
    }

    function _approve(uint256 voteId) private {
        getVoteInfoForUpdate(voteId);
        votes[voteId][_msgSender()] = true;
        emit ApproveVote(voteId, _msgSender());
    }

    function revokeApproval(uint256 voteId) public onlyAdmin {
        getVoteInfoForUpdate(voteId);
        votes[voteId][_msgSender()] = false;
        emit RevokeVote(voteId, _msgSender());
    }

    function checkAdminVote(uint256 voteId, address admin) public view returns (bool) {
        return votes[voteId][admin];
    }

    /**
     *
     * @param voteId Vote ID
     * @return approvals
     * @return approved
     */
    function voteResult(uint256 voteId) public view returns (uint256, bool) {
        mapping(address => bool) storage adminVotes = votes[voteId];
        address[] memory adminList = admins();
        uint256 approvals = 0;
        uint256 adminsLength = adminList.length;
        for (uint256 i = 0; i < adminsLength;) {
            // if voted
            if (adminVotes[adminList[i]]) {
                unchecked {
                    ++approvals;
                }
            }
            unchecked {
                ++i;
            }
        }
        return (approvals, approvals >= requiredApprovals());
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/autosweep/AutoSweepControl.sol": {
      "Utils": "0xcbe78d9bddfe6eed4e97e21f2eb9448f85d23aa6"
    }
  },
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    "@openzeppelin/contracts/=node_modules/@openzeppelin/contracts/",
    "@openzeppelin/contracts-upgradeable/=node_modules/@openzeppelin/contracts-upgradeable/",
    "forge-std/=node_modules/forge-std/",
    "tronbox/=node_modules/tronbox/",
    "eip712-codegen/=node_modules/eip712-codegen/",
    "solady/=node_modules/solady/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.