creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "src/core/SubaccountChainer.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {Enum, ISafeWallet} from \"interfaces/external/ISafeWallet.sol\";\nimport {ReentrancyGuard} from \"openzeppelin-contracts/security/ReentrancyGuard.sol\";\nimport {SafeERC20} from \"openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol\";\nimport {IERC20} from \"openzeppelin-contracts/token/ERC20/IERC20.sol\";\nimport {AddressProviderService} from \"src/core/AddressProviderService.sol\";\nimport {ExecutorRegistry} from \"src/core/registries/ExecutorRegistry.sol\";\nimport {SafeDeployer} from \"src/core/SafeDeployer.sol\";\n\n/**\n * @notice Allows console accounts to deploy automation subaccounts in one transaction\n */\ncontract SubaccountChainer is AddressProviderService, ReentrancyGuard {\n    using SafeERC20 for IERC20;\n\n    error InvalidTokenLength();\n    error OnlyDelegateCall();\n    error TokenTransferFailed();\n    error InvalidGasFeeToken();\n\n    struct AutomationSubaccountParams {\n        address[] token;\n        uint256[] amount;\n        address gasFeeToken;\n        address executorAddress;\n        uint256 gasFeeAmount;\n        bytes32 policyCommitHash;\n    }\n\n    address internal constant _ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n    address internal immutable _self;\n\n    bytes32 internal constant _FEE_RECIPIENT_HASH = bytes32(uint256(keccak256(\"console.core.FeeRecipient\")) - 1);\n\n    constructor(address _addressProvider) AddressProviderService(_addressProvider) {\n        _self = address(this);\n    }\n\n    /**\n     * @notice Console delegatecalls into this method to create an automation enabled subaccount\n     * @param params AutomationSubaccountParams to initialize subaccount\n     */\n    function createAutomationSubaccount(AutomationSubaccountParams memory params) external {\n        _onlyDelegateCall();\n\n        if (params.gasFeeToken == address(0)) revert InvalidGasFeeToken();\n\n        address[] memory subaccountOwners = new address[](1);\n        subaccountOwners[0] = address(this);\n\n        SafeDeployer safeDeployer = SafeDeployer(AddressProviderService._getAuthorizedAddress(_SAFE_DEPLOYER_HASH));\n        address subAccount = safeDeployer.deploySubAccount(subaccountOwners, 1, params.policyCommitHash, bytes32(0));\n\n        uint256 length = params.token.length;\n        if (length != params.amount.length) revert InvalidTokenLength();\n\n        for (uint256 i = 0; i < length;) {\n            _approveToken(params.token[i], subAccount, params.amount[i]);\n            unchecked {\n                ++i;\n            }\n        }\n\n        address feeRecipient = AddressProviderService._getAuthorizedAddress(_FEE_RECIPIENT_HASH);\n        _transferAsset(params.gasFeeToken, feeRecipient, params.gasFeeAmount);\n\n        ExecutorRegistry(executorRegistry).registerExecutor(subAccount, params.executorAddress);\n\n        ISafeWallet(subAccount).execTransactionFromModule(\n            subAccount,\n            0,\n            abi.encodeCall(ISafeWallet.enableModule, (addressProvider.getAuthorizedAddress(_EXECUTOR_PLUGIN_HASH))),\n            Enum.Operation.Call\n        );\n    }\n\n    /**\n     * @notice Approve assets to recipient to spend\n     * @param token Address of asset\n     * @param spender Address of spender\n     * @param amount amount of assets to approve\n     */\n    function _approveToken(address token, address spender, uint256 amount) internal {\n        IERC20(token).approve(spender, amount);\n    }\n\n    /**\n     * @notice Transfer assets to recipient\n     * @param token Address of asset\n     * @param recipient Address of recipient\n     * @param amount amount of assets to transfer\n     */\n    function _transferAsset(address token, address recipient, uint256 amount) internal {\n        if (amount == 0) return;\n        bool success = false;\n\n        if (token == _ETH) {\n            (success,) = payable(recipient).call{value: amount}(\"\");\n            if (!success) revert TokenTransferFailed();\n        } else {\n            IERC20(token).safeTransfer(recipient, amount);\n        }\n    }\n\n    /**\n     * @notice Validates if the current call being made is DELEGATECALL\n     * @dev reverts if not DELEGATECALL\n     */\n    function _onlyDelegateCall() private view {\n        if (address(this) == _self) revert OnlyDelegateCall();\n    }\n}\n"
      },
      "interfaces/external/ISafeWallet.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.19;\n\nimport {IERC165} from \"openzeppelin-contracts/utils/introspection/IERC165.sol\";\n\n/// @title Enum - Collection of enums\n/// @author Richard Meissner - <richard@gnosis.pm>\ncontract Enum {\n    enum Operation {\n        Call,\n        DelegateCall\n    }\n}\n\ninterface ISafeWallet {\n    /// @dev Allows a Module to execute a Safe transaction without any further confirmations.\n    /// @param to Destination address of module transaction.\n    /// @param value Ether value of module transaction.\n    /// @param data Data payload of module transaction.\n    /// @param operation Operation type of module transaction.\n    function execTransactionFromModule(address to, uint256 value, bytes calldata data, Enum.Operation operation)\n        external\n        returns (bool success);\n\n    /// @dev Allows a Module to execute a Safe transaction without any further confirmations and return data\n    /// @param to Destination address of module transaction.\n    /// @param value Ether value of module transaction.\n    /// @param data Data payload of module transaction.\n    /// @param operation Operation type of module transaction.\n    function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Enum.Operation operation)\n        external\n        returns (bool success, bytes memory returnData);\n    function getStorageAt(uint256 offset, uint256 length) external view returns (bytes memory);\n    function isOwner(address owner) external view returns (bool);\n    function nonce() external view returns (uint256);\n    function getThreshold() external view returns (uint256);\n    function isModuleEnabled(address module) external view returns (bool);\n    function enableModule(address module) external;\n    function disableModule(address prevModule, address module) external;\n    function removeOwner(address prevOwner, address owner, uint256 _threshold) external;\n    function swapOwner(address prevOwner, address oldOwner, address newOwner) external;\n    function getOwners() external view returns (address[] memory);\n    function approveHash(bytes32 hashToApprove) external;\n    function signedMessages(bytes32 _dataHash) external returns (uint256 _signatures);\n    function execTransaction(\n        address to,\n        uint256 value,\n        bytes calldata data,\n        Enum.Operation operation,\n        uint256 safeTxGas,\n        uint256 baseGas,\n        uint256 gasPrice,\n        address gasToken,\n        address payable refundReceiver,\n        bytes memory signatures\n    ) external payable returns (bool);\n\n    function setup(\n        address[] memory _owners,\n        uint256 _threshold,\n        address to,\n        bytes memory data,\n        address fallbackHandler,\n        address paymentToken,\n        uint256 payment,\n        address paymentReceiver\n    ) external;\n\n    function addOwnerWithThreshold(address owner, uint256 _threshold) external;\n    function domainSeparator() external view returns (bytes32);\n    function setFallbackHandler(address _fallbackHandler) external;\n    function setGuard(address guard) external;\n    function encodeTransactionData(\n        address to,\n        uint256 value,\n        bytes calldata data,\n        Enum.Operation operation,\n        uint256 safeTxGas,\n        uint256 baseGas,\n        uint256 gasPrice,\n        address gasToken,\n        address refundReceiver,\n        uint256 _nonce\n    ) external view returns (bytes memory);\n}\n\ninterface Guard is IERC165 {\n    function checkTransaction(\n        address to,\n        uint256 value,\n        bytes memory data,\n        Enum.Operation operation,\n        uint256 safeTxGas,\n        uint256 baseGas,\n        uint256 gasPrice,\n        address gasToken,\n        address payable refundReceiver,\n        bytes memory signatures,\n        address msgSender\n    ) external;\n\n    function checkAfterExecution(bytes32 txHash, bool success) external;\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant _NOT_ENTERED = 1;\n    uint256 private constant _ENTERED = 2;\n\n    uint256 private _status;\n\n    constructor() {\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, _status will be _NOT_ENTERED\n        require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n        // Any calls to nonReentrant after this point will fail\n        _status = _ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        _status = _NOT_ENTERED;\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _status == _ENTERED;\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    using Address for address;\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n    }\n\n    /**\n     * @dev Deprecated. This function has issues similar to the ones found in\n     * {IERC20-approve}, and its usage is discouraged.\n     *\n     * Whenever possible, use {safeIncreaseAllowance} and\n     * {safeDecreaseAllowance} instead.\n     */\n    function safeApprove(IERC20 token, address spender, uint256 value) internal {\n        // safeApprove should only be called when setting an initial allowance,\n        // or when resetting it to zero. To increase and decrease it, use\n        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n        require(\n            (value == 0) || (token.allowance(address(this), spender) == 0),\n            \"SafeERC20: approve from non-zero to non-zero allowance\"\n        );\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        unchecked {\n            uint256 oldAllowance = token.allowance(address(this), spender);\n            require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));\n            _callOptionalReturn(token, approvalCall);\n        }\n    }\n\n    /**\n     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.\n     * Revert on invalid signature.\n     */\n    function safePermit(\n        IERC20Permit token,\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal {\n        uint256 nonceBefore = token.nonces(owner);\n        token.permit(owner, spender, value, deadline, v, r, s);\n        uint256 nonceAfter = token.nonces(owner);\n        require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n        // the target address contains contract code and also asserts for success in the low-level call.\n\n        bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n        require(returndata.length == 0 || abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false\n        // and not revert is the subcall reverts.\n\n        (bool success, bytes memory returndata) = address(token).call(data);\n        return\n            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the amount of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the amount of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves `amount` tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 amount) external returns (bool);\n\n    /**\n     * @dev Moves `amount` tokens from `from` to `to` using the\n     * allowance mechanism. `amount` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n"
      },
      "src/core/AddressProviderService.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {IAddressProviderService} from \"../../interfaces/IAddressProviderService.sol\";\nimport {AddressProvider} from \"../core/AddressProvider.sol\";\nimport {Constants} from \"./Constants.sol\";\n\n/**\n * @title AddressProviderService\n * @author Brahma.fi\n * @notice Provides a base contract for services to resolve other services through AddressProvider\n * @dev This contract is designed to be inheritable by other contracts\n *  Provides quick and easy access to all contracts in Console Ecosystem\n */\nabstract contract AddressProviderService is IAddressProviderService, Constants {\n    error InvalidAddressProvider();\n    error NotGovernance(address);\n    error InvalidAddress();\n\n    /// @notice address of addressProvider\n    // solhint-disable-next-line immutable-vars-naming\n    AddressProvider public immutable addressProvider;\n    address public immutable walletRegistry;\n    address public immutable policyRegistry;\n    address public immutable executorRegistry;\n\n    constructor(address _addressProvider) {\n        if (_addressProvider == address(0)) revert InvalidAddressProvider();\n        addressProvider = AddressProvider(_addressProvider);\n\n        walletRegistry = addressProvider.getRegistry(_WALLET_REGISTRY_HASH);\n        policyRegistry = addressProvider.getRegistry(_POLICY_REGISTRY_HASH);\n        executorRegistry = addressProvider.getRegistry(_EXECUTOR_REGISTRY_HASH);\n\n        _notNull(walletRegistry);\n        _notNull(policyRegistry);\n        _notNull(executorRegistry);\n    }\n\n    /**\n     * @inheritdoc IAddressProviderService\n     */\n    function addressProviderTarget() external view override returns (address) {\n        return address(addressProvider);\n    }\n\n    /**\n     * @notice Helper to get authorized address from address provider\n     * @param _key keccak256 key corresponding to authorized address\n     * @return authorizedAddress\n     */\n    function _getAuthorizedAddress(bytes32 _key) internal view returns (address authorizedAddress) {\n        authorizedAddress = addressProvider.getAuthorizedAddress(_key);\n        _notNull(authorizedAddress);\n    }\n\n    /**\n     * @notice Helper to revert if address is null\n     * @param _addr address to check\n     */\n    function _notNull(address _addr) internal pure {\n        if (_addr == address(0)) revert InvalidAddress();\n    }\n}\n"
      },
      "src/core/registries/ExecutorRegistry.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {AddressProviderService} from \"../AddressProviderService.sol\";\nimport {WalletRegistry} from \"./WalletRegistry.sol\";\nimport {EnumerableSet} from \"openzeppelin-contracts/utils/structs/EnumerableSet.sol\";\n\n/**\n * @title ExecutorRegistry\n * @author Brahma.fi\n * @notice Registry for executors for sub accounts\n */\ncontract ExecutorRegistry is AddressProviderService {\n    using EnumerableSet for EnumerableSet.AddressSet;\n\n    error NotAuthorized();\n    error AlreadyExists();\n    error DoesNotExist();\n    error NoPolicyCommit();\n\n    event RegisterExecutor(address indexed _account, address indexed _authorizer, address indexed _executor);\n    event DeRegisterExecutor(address indexed _account, address indexed _authorizer, address indexed _executor);\n\n    /// @notice account addresses mapped to executor addresses\n    mapping(address account => EnumerableSet.AddressSet) private accountExecutors;\n\n    constructor(address _addressProvider) AddressProviderService(_addressProvider) {}\n\n    /**\n     * @notice Registers an executor for account\n     * @dev Adds new executor if it doesn't already exists else reverts with AlreadyExists()\n     * @dev Can be only called by main console\n     * @param _account console/subaccount address to add executor to\n     * @param _executor executor to add\n     */\n    function registerExecutor(address _account, address _executor) external {\n        _validateMsgSenderConsoleAccount(_account);\n        if (!accountExecutors[_account].add(_executor)) revert AlreadyExists();\n        emit RegisterExecutor(_account, msg.sender, _executor);\n    }\n\n    /**\n     * @notice De-registers an executor for console account/ subaccount\n     * @dev removes an executor if it exists else reverts with DoesNotExist()\n     * @dev Can be only called by main console\n     * @param _account console/subaccount address to remove executor from\n     * @param _executor executor to remove\n     */\n    function deRegisterExecutor(address _account, address _executor) external {\n        _validateMsgSenderConsoleAccount(_account);\n\n        if (!accountExecutors[_account].remove(_executor)) revert DoesNotExist();\n        emit DeRegisterExecutor(_account, msg.sender, _executor);\n    }\n\n    /**\n     * @notice checks if _executor is registered for _account\n     * @param _account address of account\n     * @param _executor address of executor\n     * @return isExecutorValid\n     */\n    function isExecutor(address _account, address _executor) external view returns (bool) {\n        return accountExecutors[_account].contains(_executor);\n    }\n\n    /**\n     * @return all the executors for a console account / subaccount\n     * @param _account address of account\n     */\n    function getExecutorsForAccount(address _account) external view returns (address[] memory) {\n        return accountExecutors[_account].values();\n    }\n\n    function _validateMsgSenderConsoleAccount(address _account) internal view {\n        // msg.sender is console account\n        if (msg.sender == _account && WalletRegistry(walletRegistry).isWallet(msg.sender)) return;\n\n        // msg.sender is console account and owns the _account\n        if (WalletRegistry(walletRegistry).subAccountToWallet(_account) == msg.sender) return;\n\n        revert NotAuthorized();\n    }\n}\n"
      },
      "src/core/SafeDeployer.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {ReentrancyGuard} from \"openzeppelin-contracts/security/ReentrancyGuard.sol\";\nimport {AddressProviderService} from \"../core/AddressProviderService.sol\";\nimport {WalletRegistry} from \"../core/registries/WalletRegistry.sol\";\nimport {PolicyRegistry} from \"../core/registries/PolicyRegistry.sol\";\nimport {ISafeProxyFactory} from \"../../interfaces/external/ISafeProxyFactory.sol\";\nimport {ISafeWallet} from \"../../interfaces/external/ISafeWallet.sol\";\nimport {Types, SafeHelper} from \"../libraries/SafeHelper.sol\";\nimport {ISafeMultiSend} from \"../../interfaces/external/ISafeMultiSend.sol\";\n\n/**\n * @title SafeDeployer\n * @author Brahma.fi\n * @notice Deploys new brahma console accounts and sub accounts\n */\ncontract SafeDeployer is AddressProviderService, ReentrancyGuard {\n    /// @notice version of safe deployer\n    string public constant VERSION = \"1\";\n\n    /**\n     * @notice hash of safe create2 failure reason\n     * @dev keccak256(\"Create2 call failed\");\n     */\n    bytes32 internal constant _SAFE_CREATION_FAILURE_REASON =\n        0xd7c71a0bdd2eb2834ad042153c811dd478e4ee2324e3003b9522e03e7b3735dc;\n\n    event SafeProxyCreationFailure(address indexed singleton, uint256 indexed nonce, bytes initializer);\n    event ConsoleAccountDeployed(address indexed consoleAddress);\n    event SubAccountDeployed(address indexed subAccountAddress, address indexed consoleAddress);\n    event PreComputeAccount(address[] indexed owners, uint256 indexed threshold);\n\n    error InvalidCommitment();\n    error NotWallet();\n    error PreComputedAccount(address addr);\n    error SafeProxyCreationFailed();\n\n    constructor(address _addressProvider) AddressProviderService(_addressProvider) {}\n\n    /// @notice owners nonce\n    mapping(bytes32 ownersHash => uint256 count) public ownerSafeCount;\n\n    /**\n     * @notice Deploys a new console account with or without policy commit and registers it\n     * @dev _owners list should contain addresses in the same order to generate same console address on all chains\n     * @param _owners list of safe owners\n     * @param _threshold safe threshold\n     * @param _policyCommit commitment\n     * @param _salt salt to be used during creation of safe\n     * @return _safe deployed console account address\n     */\n    function deployConsoleAccount(address[] calldata _owners, uint256 _threshold, bytes32 _policyCommit, bytes32 _salt)\n        external\n        nonReentrant\n        returns (address _safe)\n    {\n        bool _policyHashValid = _policyCommit != bytes32(0);\n\n        _safe = _createSafe(_owners, _setupConsoleAccount(_owners, _threshold, _policyHashValid), _salt);\n\n        if (_policyHashValid) {\n            PolicyRegistry(policyRegistry).updatePolicy(_safe, _policyCommit);\n        }\n        emit ConsoleAccountDeployed(_safe);\n    }\n\n    /**\n     * @notice Deploys a new sub-account with policy commit and registers it\n     * @dev ConsoleAccount is enabled as module\n     * @param _owners list of safe owners\n     * @param _threshold safe threshold\n     * @param _policyCommit commitment\n     * @param _salt salt to be used during creation of safe, to generate nonce\n     * @return _subAcc deployed sub-account address\n     */\n    function deploySubAccount(address[] calldata _owners, uint256 _threshold, bytes32 _policyCommit, bytes32 _salt)\n        external\n        nonReentrant\n        returns (address _subAcc)\n    {\n        // Policy commit is required for sub account\n        if (_policyCommit == bytes32(0)) revert InvalidCommitment();\n\n        // Check if msg.sender is a registered wallet\n        if (!WalletRegistry(walletRegistry).isWallet(msg.sender)) revert NotWallet();\n\n        // Deploy sub account\n        _subAcc = _createSafe(_owners, _setupSubAccount(_owners, _threshold), _salt);\n\n        // Register sub account to wallet\n        WalletRegistry(walletRegistry).registerSubAccount(msg.sender, _subAcc);\n\n        // Update policy commit for sub account\n        PolicyRegistry(policyRegistry).updatePolicy(_subAcc, _policyCommit);\n        emit SubAccountDeployed(_subAcc, msg.sender);\n    }\n\n    /**\n     * @notice Private helper function to setup Console account with setUp transactions\n     * @param _owners list of owners addresses\n     * @param _threshold safe threshold\n     */\n    function _setupConsoleAccount(address[] memory _owners, uint256 _threshold, bool _policyHashValid)\n        private\n        view\n        returns (bytes memory)\n    {\n        address fallbackHandler;\n        Types.Executable[] memory txns;\n\n        if (_policyHashValid) {\n            txns = new Types.Executable[](2);\n            fallbackHandler = AddressProviderService._getAuthorizedAddress(_CONSOLE_FALLBACK_HANDLER_HASH);\n\n            // Enable guard on console account\n            txns[1] = Types.Executable({\n                callType: Types.CallType.DELEGATECALL,\n                target: AddressProviderService._getAuthorizedAddress(_SAFE_ENABLER_HASH),\n                value: 0,\n                data: abi.encodeCall(\n                    ISafeWallet.setGuard, (AddressProviderService._getAuthorizedAddress(_SAFE_MODERATOR_OVERRIDABLE_HASH))\n                    )\n            });\n        } else {\n            txns = new Types.Executable[](1);\n            fallbackHandler = AddressProviderService._getAuthorizedAddress(_SAFE_FALLBACK_HANDLER_HASH);\n        }\n\n        // Register Wallet\n        /// @dev This function is being packed as a part of multisend transaction as, safe internally performs\n        // a delegatecall during initializer to the target contract, so direct call doesnt work. Multisend is\n        // supposed to be delegatecall\n        txns[0] = Types.Executable({\n            callType: Types.CallType.CALL,\n            target: walletRegistry,\n            value: 0,\n            data: abi.encodeCall(WalletRegistry.registerWallet, ())\n        });\n\n        return abi.encodeCall(\n            ISafeWallet.setup,\n            (\n                _owners,\n                _threshold,\n                AddressProviderService._getAuthorizedAddress(_SAFE_MULTI_SEND_HASH),\n                abi.encodeCall(ISafeMultiSend.multiSend, (SafeHelper._packMultisendTxns(txns))),\n                fallbackHandler,\n                address(0),\n                0,\n                address(0)\n            )\n        );\n    }\n\n    /**\n     * @notice Private helper function to setup subAccount safe with setUp transactions\n     * @param _owners list of owners addresses\n     * @param _threshold safe threshold\n     */\n    function _setupSubAccount(address[] memory _owners, uint256 _threshold) private view returns (bytes memory) {\n        address safeEnabler = AddressProviderService._getAuthorizedAddress(_SAFE_ENABLER_HASH);\n        Types.Executable[] memory txns = new Types.Executable[](2);\n\n        // Enable Brhma Console account as module on sub Account\n        txns[0] = Types.Executable({\n            callType: Types.CallType.DELEGATECALL,\n            target: safeEnabler,\n            value: 0,\n            data: abi.encodeCall(ISafeWallet.enableModule, (msg.sender))\n        });\n\n        // Enable guard on subAccount\n        txns[1] = Types.Executable({\n            callType: Types.CallType.DELEGATECALL,\n            target: safeEnabler,\n            value: 0,\n            data: abi.encodeCall(ISafeWallet.setGuard, (AddressProviderService._getAuthorizedAddress(_SAFE_MODERATOR_HASH)))\n        });\n\n        return abi.encodeCall(\n            ISafeWallet.setup,\n            (\n                _owners,\n                _threshold,\n                AddressProviderService._getAuthorizedAddress(_SAFE_MULTI_SEND_HASH),\n                abi.encodeCall(ISafeMultiSend.multiSend, (SafeHelper._packMultisendTxns(txns))),\n                AddressProviderService._getAuthorizedAddress(_CONSOLE_FALLBACK_HANDLER_HASH),\n                address(0),\n                0,\n                address(0)\n            )\n        );\n    }\n\n    /**\n     * @notice Internal function to create a new Safe Wallet.\n     * @dev SafeDeployer calls createProxyWithNonce to deploy a new Safe Wallet. This also contains initializer bytes\n     *  which are used during creation to setup the safe with owners and threshold. An actor can precompute the salt\n     *  for a given set of owners and deploy the safe. We choose to not consider that safe as a valid safe and deploy a new\n     *  safe. In case the actor chooses to deploy multiple precomputed safes with bumped nonces, the transaction will run out\n     *  of gas and user can retry with a new random salt\n     *  To generate deterministic addresses for a given set of owners, the order of owner addresses and threshold should be same\n     * @param _owners list of owners addresses\n     * @param _salt salt to be used during creation of safe, to generate nonce\n     * @return _safe The address of the created Safe Wallet.\n     */\n    function _createSafe(address[] calldata _owners, bytes memory _initializer, bytes32 _salt)\n        private\n        returns (address _safe)\n    {\n        address safeProxyFactory = AddressProviderService._getAuthorizedAddress(_SAFE_PROXY_FACTORY_HASH);\n        address safeSingleton = AddressProviderService._getAuthorizedAddress(_SAFE_SINGLETON_HASH);\n        bytes32 ownersHash = keccak256(abi.encode(_owners));\n\n        // Generate nonce based on owners and user provided salt\n        do {\n            uint256 nonce = _genNonce(ownersHash, _salt);\n            try ISafeProxyFactory(safeProxyFactory).createProxyWithNonce(safeSingleton, _initializer, nonce) returns (\n                address _deployedSafe\n            ) {\n                _safe = _deployedSafe;\n            } catch Error(string memory reason) {\n                // KEK\n                if (keccak256(bytes(reason)) != _SAFE_CREATION_FAILURE_REASON) {\n                    // Revert if the error is not due to create2 call failure\n                    revert SafeProxyCreationFailed();\n                }\n                // A safe is already deployed with the same salt, retry with bumped nonce\n                emit SafeProxyCreationFailure(safeSingleton, nonce, _initializer);\n            } catch {\n                revert SafeProxyCreationFailed();\n            }\n        } while (_safe == address(0));\n    }\n\n    /**\n     * @notice Internal function to get the nonce of a user's safe deployment\n     * @param _ownersHash address of owner of the safe.\n     * @param _salt salt to be used in nonce generation\n     * @return The nonce of the user's safe deployment.\n     */\n    function _genNonce(bytes32 _ownersHash, bytes32 _salt) private returns (uint256) {\n        return uint256(keccak256(abi.encodePacked(_ownersHash, ownerSafeCount[_ownersHash]++, _salt, VERSION)));\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev Returns true if `account` is a contract.\n     *\n     * [IMPORTANT]\n     * ====\n     * It is unsafe to assume that an address for which this function returns\n     * false is an externally-owned account (EOA) and not a contract.\n     *\n     * Among others, `isContract` will return false for the following\n     * types of addresses:\n     *\n     *  - an externally-owned account\n     *  - a contract in construction\n     *  - an address where a contract will be created\n     *  - an address where a contract lived, but was destroyed\n     *\n     * Furthermore, `isContract` will also return true if the target contract within\n     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,\n     * which only has an effect at the end of a transaction.\n     * ====\n     *\n     * [IMPORTANT]\n     * ====\n     * You shouldn't rely on `isContract` to protect against flash loan attacks!\n     *\n     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n     * constructor.\n     * ====\n     */\n    function isContract(address account) internal view returns (bool) {\n        // This method relies on extcodesize/address.code.length, which returns 0\n        // for contracts in construction, since the code is only stored at the end\n        // of the constructor execution.\n\n        return account.code.length > 0;\n    }\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        require(success, \"Address: unable to send value, recipient may have reverted\");\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason, it is bubbled up by this\n     * function (like regular Solidity function calls).\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n     * `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\n     *\n     * _Available since v3.1._\n     */\n    function functionCallWithValue(\n        address target,\n        bytes memory data,\n        uint256 value,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a static call.\n     *\n     * _Available since v3.3._\n     */\n    function functionStaticCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n     * but performing a delegate call.\n     *\n     * _Available since v3.4._\n     */\n    function functionDelegateCall(\n        address target,\n        bytes memory data,\n        string memory errorMessage\n    ) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n     *\n     * _Available since v4.8._\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal view returns (bytes memory) {\n        if (success) {\n            if (returndata.length == 0) {\n                // only check isContract if the call was successful and the return data is empty\n                // otherwise we already know that it was a contract\n                require(isContract(target), \"Address: call to non-contract\");\n            }\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n     * revert reason or using the provided one.\n     *\n     * _Available since v4.3._\n     */\n    function verifyCallResult(\n        bool success,\n        bytes memory returndata,\n        string memory errorMessage\n    ) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else {\n            _revert(returndata, errorMessage);\n        }\n    }\n\n    function _revert(bytes memory returndata, string memory errorMessage) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            /// @solidity memory-safe-assembly\n            assembly {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert(errorMessage);\n        }\n    }\n}\n"
      },
      "interfaces/IAddressProviderService.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\ninterface IAddressProviderService {\n    /// @notice Returns the address of the AddressProvider\n    function addressProviderTarget() external view returns (address);\n}\n"
      },
      "src/core/AddressProvider.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {IAddressProviderService} from \"interfaces/IAddressProviderService.sol\";\nimport {Constants} from \"src/core/Constants.sol\";\n\n/**\n * @title AddressProvider\n * @author Brahma.fi\n * @notice Single source of truth for resolving addresses of core components and external contracts\n */\ncontract AddressProvider is Constants {\n    error RegistryAlreadyExists();\n    error AddressProviderUnsupported();\n    error NotGovernance(address);\n    error NotPendingGovernance(address);\n    error NullAddress();\n\n    event RegistryInitialised(address indexed registry, bytes32 indexed key);\n    event AuthorizedAddressInitialised(address indexed authorizedAddress, bytes32 indexed key);\n    event GovernanceTransferRequested(address indexed previousGovernance, address indexed newGovernance);\n    event GovernanceTransferred(address indexed previousGovernance, address indexed newGovernance);\n\n    /// @notice address of governance\n    address public governance;\n    /// @notice address of pending governance before accepting\n    address public pendingGovernance;\n\n    /**\n     * @notice keccak256 hash of authorizedAddress keys mapped to their addresses\n     * @dev Core & Roles are used as keys for this mapping. These addresses are mutable\n     * @dev authorizedAddresses are updatable by governance\n     */\n    mapping(bytes32 => address) internal authorizedAddresses;\n\n    /**\n     * @notice keccak256 hash of registry keys mapped to their addresses\n     * @dev registries are only set once by governance and immutable\n     */\n    mapping(bytes32 => address) internal registries;\n\n    constructor(address _governance, address walletRegistry, address policyRegistry, address executorRegistry) {\n        _notNull(_governance);\n        governance = _governance;\n\n        _notNull(walletRegistry);\n        _notNull(policyRegistry);\n        _notNull(executorRegistry);\n        registries[_WALLET_REGISTRY_HASH] = walletRegistry;\n        registries[_POLICY_REGISTRY_HASH] = policyRegistry;\n        registries[_EXECUTOR_REGISTRY_HASH] = executorRegistry;\n    }\n\n    /**\n     * @notice Governance setter\n     * @param _newGovernance address of new governance\n     */\n    function setGovernance(address _newGovernance) external {\n        _notNull(_newGovernance);\n        _onlyGov();\n        emit GovernanceTransferRequested(governance, _newGovernance);\n        pendingGovernance = _newGovernance;\n    }\n\n    /**\n     * @notice Governance accepter\n     */\n    function acceptGovernance() external {\n        if (msg.sender != pendingGovernance) {\n            revert NotPendingGovernance(msg.sender);\n        }\n        emit GovernanceTransferred(governance, msg.sender);\n        governance = msg.sender;\n        delete pendingGovernance;\n    }\n\n    /**\n     * @notice Authorized address setter\n     * @param _key key of authorizedAddress\n     * @param _authorizedAddress address to set\n     * @param _overrideCheck overrides check for supported address provider\n     */\n    function setAuthorizedAddress(bytes32 _key, address _authorizedAddress, bool _overrideCheck) external {\n        _onlyGov();\n        _notNull(_authorizedAddress);\n\n        /// @dev skips checks for supported `addressProvider()` if `_overrideCheck` is true\n        if (!_overrideCheck) {\n            /// @dev skips checks for supported `addressProvider()` if `_authorizedAddress` is an EOA\n            if (_authorizedAddress.code.length != 0) _ensureAddressProvider(_authorizedAddress);\n        }\n\n        authorizedAddresses[_key] = _authorizedAddress;\n\n        emit AuthorizedAddressInitialised(_authorizedAddress, _key);\n    }\n\n    /**\n     * @notice Registry address setter\n     * @param _key key of registry address\n     * @param _registry address to set\n     */\n    function setRegistry(bytes32 _key, address _registry) external {\n        _onlyGov();\n        _ensureAddressProvider(_registry);\n\n        if (registries[_key] != address(0)) revert RegistryAlreadyExists();\n        registries[_key] = _registry;\n\n        emit RegistryInitialised(_registry, _key);\n    }\n\n    /**\n     * @notice Authorized address getter\n     * @param _key key of authorized address\n     * @return address of authorized address\n     */\n    function getAuthorizedAddress(bytes32 _key) external view returns (address) {\n        return authorizedAddresses[_key];\n    }\n\n    /**\n     * @notice Registry address getter\n     * @param _key key of registry address\n     * @return address of registry address\n     */\n    function getRegistry(bytes32 _key) external view returns (address) {\n        return registries[_key];\n    }\n\n    /**\n     * @notice Ensures that the new address supports the AddressProviderService interface\n     * and is pointing to this AddressProvider\n     * @param _newAddress address to check\n     */\n    function _ensureAddressProvider(address _newAddress) internal view {\n        if (IAddressProviderService(_newAddress).addressProviderTarget() != address(this)) {\n            revert AddressProviderUnsupported();\n        }\n    }\n\n    /**\n     * @notice Checks if msg.sender is governance\n     */\n    function _onlyGov() internal view {\n        if (msg.sender != governance) revert NotGovernance(msg.sender);\n    }\n\n    /**\n     * @notice Checks and reverts if address is null\n     * @param addr address to check if null\n     */\n    function _notNull(address addr) internal pure {\n        if (addr == address(0)) revert NullAddress();\n    }\n}\n"
      },
      "src/core/Constants.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\n/**\n * @title Constants\n * @author Brahma.fi\n * @notice Contains constants used by multiple contracts\n * @dev Inflates bytecode size by approximately 560 bytes on deployment, but saves gas on runtime\n */\nabstract contract Constants {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                        REGISTRIES                          */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n    /// @notice Key to map address of ExecutorRegistry\n    bytes32 internal constant _EXECUTOR_REGISTRY_HASH = bytes32(uint256(keccak256(\"console.core.ExecutorRegistry\")) - 1);\n\n    /// @notice Key to map address of WalletRegistry\n    bytes32 internal constant _WALLET_REGISTRY_HASH = bytes32(uint256(keccak256(\"console.core.WalletRegistry\")) - 1);\n\n    /// @notice Key to map address of PolicyRegistry\n    bytes32 internal constant _POLICY_REGISTRY_HASH = bytes32(uint256(keccak256(\"console.core.PolicyRegistry\")) - 1);\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                          CORE                              */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n    /// @notice Key to map address of ExecutorPlugin\n    bytes32 internal constant _EXECUTOR_PLUGIN_HASH = bytes32(uint256(keccak256(\"console.core.ExecutorPlugin\")) - 1);\n\n    /// @notice Key to map address of ConsoleFallbackHandler\n    bytes32 internal constant _CONSOLE_FALLBACK_HANDLER_HASH =\n        bytes32(uint256(keccak256(\"console.core.FallbackHandler\")) - 1);\n\n    /// @notice Key to map address of Safe FallbackHandler\n    bytes32 internal constant _SAFE_FALLBACK_HANDLER_HASH = bytes32(uint256(keccak256(\"safe.FallbackHandler\")) - 1);\n\n    /// @notice Key to map address of Safe MultiSend\n    bytes32 internal constant _SAFE_MULTI_SEND_HASH = bytes32(uint256(keccak256(\"safe.MultiSend\")) - 1);\n\n    /// @notice Key to map address of SafeProxyFactory\n    bytes32 internal constant _SAFE_PROXY_FACTORY_HASH = bytes32(uint256(keccak256(\"safe.ProxyFactory\")) - 1);\n\n    /// @notice Key to map address of SafeSingleton\n    bytes32 internal constant _SAFE_SINGLETON_HASH = bytes32(uint256(keccak256(\"safe.Singleton\")) - 1);\n\n    /// @notice Key to map address of PolicyValidator\n    bytes32 internal constant _POLICY_VALIDATOR_HASH = bytes32(uint256(keccak256(\"console.core.PolicyValidator\")) - 1);\n\n    /// @notice Key to map address of SafeDeployer\n    bytes32 internal constant _SAFE_DEPLOYER_HASH = bytes32(uint256(keccak256(\"console.core.SafeDeployer\")) - 1);\n\n    /// @notice Key to map address of SafeEnabler\n    bytes32 internal constant _SAFE_ENABLER_HASH = bytes32(uint256(keccak256(\"console.core.SafeEnabler\")) - 1);\n\n    /// @notice Key to map address of SafeModerator\n    bytes32 internal constant _SAFE_MODERATOR_HASH = bytes32(uint256(keccak256(\"console.core.SafeModerator\")) - 1);\n\n    /// @notice Key to map address of SafeModeratorOverridable\n    bytes32 internal constant _SAFE_MODERATOR_OVERRIDABLE_HASH =\n        bytes32(uint256(keccak256(\"console.core.SafeModeratorOverridable\")) - 1);\n\n    /// @notice Key to map address of TransactionValidator\n    bytes32 internal constant _TRANSACTION_VALIDATOR_HASH =\n        bytes32(uint256(keccak256(\"console.core.TransactionValidator\")) - 1);\n\n    /// @notice Key to map address of ConsoleOpBuilder\n    bytes32 internal constant _CONSOLE_OP_BUILDER_HASH =\n        bytes32(uint256(keccak256(\"console.core.ConsoleOpBuilder\")) - 1);\n\n    /// @notice Key to map address of ExecutionBlocker\n    bytes32 internal constant _EXECUTION_BLOCKER_HASH = bytes32(uint256(keccak256(\"console.core.ExecutionBlocker\")) - 1);\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                          ROLES                             */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @notice Key to map address of Role PolicyAuthenticator\n    bytes32 internal constant _POLICY_AUTHENTICATOR_HASH =\n        bytes32(uint256(keccak256(\"console.roles.PolicyAuthenticator\")) - 1);\n}\n"
      },
      "src/core/registries/WalletRegistry.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {AddressProviderService} from \"../AddressProviderService.sol\";\n\n/**\n * @title WalletRegistry\n * @author Brahma.fi\n * @notice Registry for wallet and sub account addresses\n */\ncontract WalletRegistry is AddressProviderService {\n    error AlreadyRegistered();\n    error InvalidSender();\n    error IsSubAccount();\n\n    event RegisterWallet(address indexed wallet);\n    event RegisterSubAccount(address indexed wallet, address indexed subAccount);\n\n    /// @notice subAccount addresses mapped to owner wallet\n    mapping(address subAccount => address wallet) public subAccountToWallet;\n    /// @notice wallet addresses mapped to list of subAccounts\n    mapping(address wallet => address[] subAccountList) public walletToSubAccountList;\n    /// @notice address of wallet mapped to boolean indicating if it's a wallet\n    mapping(address => bool) public isWallet;\n\n    constructor(address _addressProvider) AddressProviderService(_addressProvider) {}\n\n    /**\n     * @notice Registers a wallet\n     * @dev Can only be called by wallet to register itself\n     */\n    function registerWallet() external {\n        if (isWallet[msg.sender]) revert AlreadyRegistered();\n        if (subAccountToWallet[msg.sender] != address(0)) revert IsSubAccount();\n        isWallet[msg.sender] = true;\n        emit RegisterWallet(msg.sender);\n    }\n\n    /**\n     * @notice Registers a sub account for a Safe\n     * @param _wallet Console account address, owner of sub account\n     * @param _subAccount Sub account address to register\n     * @dev Can only be called by safe deployer\n     */\n\n    function registerSubAccount(address _wallet, address _subAccount) external {\n        if (msg.sender != AddressProviderService._getAuthorizedAddress(_SAFE_DEPLOYER_HASH)) revert InvalidSender();\n\n        if (subAccountToWallet[_subAccount] != address(0) || isWallet[_subAccount]) revert AlreadyRegistered();\n\n        subAccountToWallet[_subAccount] = _wallet;\n        walletToSubAccountList[_wallet].push(_subAccount);\n        emit RegisterSubAccount(_wallet, _subAccount);\n    }\n\n    /**\n     * @notice sub account list getter\n     * @dev returns sub account list associated with _wallet\n     * @param _wallet safe address\n     * @return list of subAccounts for wallet\n     */\n    function getSubAccountsForWallet(address _wallet) external view returns (address[] memory) {\n        return walletToSubAccountList[_wallet];\n    }\n}\n"
      },
      "lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position of the value in the `values` array, plus 1 because index 0\n        // means a value is not in the set.\n        mapping(bytes32 => uint256) _indexes;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._indexes[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We read and store the value's index to prevent multiple reads from the same storage slot\n        uint256 valueIndex = set._indexes[value];\n\n        if (valueIndex != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 toDeleteIndex = valueIndex - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (lastIndex != toDeleteIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the last value to the index where the value to delete is\n                set._values[toDeleteIndex] = lastValue;\n                // Update the index for the moved value\n                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the index for the deleted slot\n            delete set._indexes[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._indexes[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\n    }\n}\n"
      },
      "src/core/registries/PolicyRegistry.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {AddressProviderService} from \"src/core/AddressProviderService.sol\";\nimport {WalletRegistry} from \"src/core/registries/WalletRegistry.sol\";\n\n/**\n * @title PolicyRegistry\n * @author Brahma.fi\n * @notice Registry for policy commits for wallets and sub accounts\n */\ncontract PolicyRegistry is AddressProviderService {\n    error PolicyCommitInvalid();\n    error UnauthorizedPolicyUpdate();\n\n    event UpdatedPolicyCommit(address indexed account, bytes32 policyCommit, bytes32 oldPolicyCommit);\n\n    /// @notice account addresses mapped to their policy commits\n    mapping(address account => bytes32 policyCommit) public commitments;\n\n    constructor(address _addressProvider) AddressProviderService(_addressProvider) {}\n\n    /**\n     * @notice Enables setting policy commits for accounts\n     * @param account address of account to set policy commit for\n     * @param policyCommit policy commit hash to set\n     * @dev policyCommit for an account can be set by:\n     *  1. by safe deployer, if the account is uninitialized\n     *  2. by the registered wallet, if the account is a subAccount\n     *  3. by the account itself, if account is a registered wallet\n     */\n    function updatePolicy(address account, bytes32 policyCommit) external {\n        if (policyCommit == bytes32(0)) {\n            revert PolicyCommitInvalid();\n        }\n\n        bytes32 currentCommit = commitments[account];\n\n        // solhint-disable no-empty-blocks\n        if (\n            currentCommit == bytes32(0)\n                && msg.sender == AddressProviderService._getAuthorizedAddress(_SAFE_DEPLOYER_HASH)\n        ) {\n            // In case invoker is safe  deployer\n        } else {\n            if (WalletRegistry(walletRegistry).subAccountToWallet(account) == msg.sender) {\n                //In case invoker is updating on behalf of sub account\n            } else if (msg.sender == account && WalletRegistry(walletRegistry).isWallet(msg.sender)) {\n                // In case invoker is a registered wallet\n            } else {\n                revert UnauthorizedPolicyUpdate();\n            }\n        }\n        // solhint-enable no-empty-blocks\n        _updatePolicy(account, policyCommit, currentCommit);\n    }\n\n    /**\n     * @notice Internal function to update policy commit for an account\n     * @param account address of account to set policy commit for\n     * @param policyCommit policy commit hash to set\n     */\n    function _updatePolicy(address account, bytes32 policyCommit, bytes32 oldPolicyCommit) internal {\n        emit UpdatedPolicyCommit(account, policyCommit, oldPolicyCommit);\n        commitments[account] = policyCommit;\n    }\n}\n"
      },
      "interfaces/external/ISafeProxyFactory.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\ninterface ISafeProxyFactory {\n    event ProxyCreation(address proxy, address singleton);\n\n    function calculateCreateProxyWithNonceAddress(address _singleton, bytes memory initializer, uint256 saltNonce)\n        external\n        returns (address proxy);\n\n    function createProxy(address singleton, bytes memory data) external returns (address proxy);\n\n    function createProxyWithCallback(address _singleton, bytes memory initializer, uint256 saltNonce, address callback)\n        external\n        returns (address proxy);\n\n    function createProxyWithNonce(address _singleton, bytes memory initializer, uint256 saltNonce)\n        external\n        returns (address proxy);\n\n    function proxyCreationCode() external pure returns (bytes memory);\n\n    function proxyRuntimeCode() external pure returns (bytes memory);\n}\n"
      },
      "src/libraries/SafeHelper.sol": {
        "content": "/// SPDX-License-Identifier: BUSL-1.1\n\n/// Copyright (C) 2023 Brahma.fi\n\npragma solidity 0.8.19;\n\nimport {Enum, ISafeWallet} from \"interfaces/external/ISafeWallet.sol\";\nimport {Types} from \"interfaces/Types.sol\";\n\n/**\n * @title SafeHelper\n * @author Brahma.fi\n * @notice Helper library containing functions to interact with safe wallet\n */\nlibrary SafeHelper {\n    error InvalidMultiSendInput();\n    error UnableToParseOperation();\n\n    /// @notice uint256(keccak256(\"guard_manager.guard.address\"))\n    /// @dev This refers to the storage slot where guard is stored in Safe's layout: https://github.com/safe-global/safe-contracts/blob/ff4c6761fbfae8ab8a94f36fd26bcfb2b5414eb1/contracts/base/GuardManager.sol#L77\n    uint256 internal constant _GUARD_STORAGE_SLOT =\n        33528237782592280163068556224972516439282563014722366175641814928123294921928;\n    /// @notice uint256(keccak256(\"fallback_manager.handler.address\"))\n    /// @dev This refers to the storage slot where fallback handler is stored in Safe's layout: https://github.com/safe-global/safe-contracts/blob/ff4c6761fbfae8ab8a94f36fd26bcfb2b5414eb1/contracts/base/FallbackManager.sol#L14\n    uint256 internal constant _FALLBACK_HANDLER_STORAGE_SLOT =\n        49122629484629529244014240937346711770925847994644146912111677022347558721749;\n\n    /**\n     * @notice Contains hash for expected overridable guard removal calldata\n     * @dev This is the hash of the calldata for the following function call\n     *\n     * abi.encodeCall(ISafeWallet.setGuard, (address(0))) = 0xe19a9dd90000000000000000000000000000000000000000000000000000000000000000\n     * keccak256(abi.encodeCall(ISafeWallet.setGuard, (address(0)))) = 0xc0e2c16ecb99419a40dd8b9c0b339b27acebd27c481a28cd606927aeb86f5079\n     */\n    bytes32 internal constant _GUARD_REMOVAL_CALLDATA_HASH =\n        0xc0e2c16ecb99419a40dd8b9c0b339b27acebd27c481a28cd606927aeb86f5079;\n\n    /**\n     * @notice Contains hash for expected overridable fallback handler removal calldata\n     * @dev This is the hash of the calldata for the following function call\n     *\n     * abi.encodeCall(ISafeWallet.setFallbackHandler, (address(0))) = 0xf08a03230000000000000000000000000000000000000000000000000000000000000000\n     * keccak256(abi.encodeCall(ISafeWallet.setFallbackHandler, (address(0)))) = 0x5bdf8c44c012c1347b2b15694dc5cc39b899eb99e32614676b7661001be925b7\n     */\n    bytes32 internal constant _FALLBACK_REMOVAL_CALLDATA_HASH =\n        0x5bdf8c44c012c1347b2b15694dc5cc39b899eb99e32614676b7661001be925b7;\n\n    /**\n     * @notice Packs multiple executables into a single bytes array compatible with Safe's MultiSend contract which can be used as argument for multicall method\n     * @dev Reference contract at https://github.com/safe-global/safe-contracts/blob/main/contracts/libraries/MultiSend.sol\n     * @param _txns Array of executables to pack\n     * @return packedTxns bytes array containing packed transactions\n     */\n    function _packMultisendTxns(Types.Executable[] memory _txns) internal pure returns (bytes memory packedTxns) {\n        uint256 len = _txns.length;\n        if (len == 0) revert InvalidMultiSendInput();\n\n        uint256 i = 0;\n        do {\n            uint8 call = uint8(_parseOperationEnum(_txns[i].callType));\n\n            uint256 calldataLength = _txns[i].data.length;\n\n            bytes memory encodedTxn = abi.encodePacked(\n                bytes1(call), bytes20(_txns[i].target), bytes32(_txns[i].value), bytes32(calldataLength), _txns[i].data\n            );\n\n            if (i != 0) {\n                // If not first transaction, append to packedTxns\n                packedTxns = abi.encodePacked(packedTxns, encodedTxn);\n            } else {\n                // If first transaction, set packedTxns to encodedTxn\n                packedTxns = encodedTxn;\n            }\n\n            unchecked {\n                ++i;\n            }\n        } while (i < len);\n    }\n\n    /**\n     * @notice Gets the guard for a safe\n     * @param safe address of safe\n     * @return address of guard, address(0) if no guard exists\n     */\n    function _getGuard(address safe) internal view returns (address) {\n        bytes memory guardAddress = ISafeWallet(safe).getStorageAt(_GUARD_STORAGE_SLOT, 1);\n        return address(uint160(uint256(bytes32(guardAddress))));\n    }\n\n    /**\n     * @notice Gets the fallback handler for a safe\n     * @param safe address of safe\n     * @return address of fallback handler, address(0) if no fallback handler exists\n     */\n    function _getFallbackHandler(address safe) internal view returns (address) {\n        bytes memory fallbackHandlerAddress = ISafeWallet(safe).getStorageAt(_FALLBACK_HANDLER_STORAGE_SLOT, 1);\n        return address(uint160(uint256(bytes32(fallbackHandlerAddress))));\n    }\n\n    /**\n     * @notice Converts a CallType enum to an Operation enum.\n     * @dev Reverts with UnableToParseOperation error if the CallType is not supported.\n     * @param callType The CallType enum to be converted.\n     * @return operation The converted Operation enum.\n     */\n    function _parseOperationEnum(Types.CallType callType) internal pure returns (Enum.Operation operation) {\n        if (callType == Types.CallType.DELEGATECALL) {\n            operation = Enum.Operation.DelegateCall;\n        } else if (callType == Types.CallType.CALL) {\n            operation = Enum.Operation.Call;\n        } else {\n            revert UnableToParseOperation();\n        }\n    }\n}\n"
      },
      "interfaces/external/ISafeMultiSend.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\ninterface ISafeMultiSend {\n    function multiSend(bytes memory transactions) external payable;\n}\n"
      },
      "interfaces/Types.sol": {
        "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.19;\n\ninterface Types {\n    enum CallType {\n        CALL,\n        DELEGATECALL,\n        STATICCALL\n    }\n\n    struct Executable {\n        CallType callType;\n        address target;\n        uint256 value;\n        bytes data;\n    }\n\n    struct TokenRequest {\n        address token;\n        uint256 amount;\n    }\n}\n"
      }
    },
    "settings": {
      "remappings": [
        "ds-test/=lib/forge-std/lib/ds-test/src/",
        "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
        "forge-std/=lib/forge-std/src/",
        "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
        "openzeppelin/=lib/openzeppelin-contracts/contracts/",
        "safe-contracts/=lib/safe-contracts/contracts/",
        "solady/=lib/solady/src/",
        "solmate/=lib/solady/lib/solmate/src/",
        "solidity-bytes-utils/=lib/solidity-bytes-utils/contracts/"
      ],
      "optimizer": {
        "enabled": true,
        "runs": 20000
      },
      "metadata": {
        "useLiteralContent": false,
        "bytecodeHash": "ipfs",
        "appendCBOR": true
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "evmVersion": "paris",
      "viaIR": false,
      "libraries": {}
    }
  }}