creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/access/Ownable.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\n\npragma solidity ^0.8.20;\n\nimport {Context} from \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is set to the address provided by the deployer. This can\n * later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n    address private _owner;\n\n    /**\n     * @dev The caller account is not authorized to perform an operation.\n     */\n    error OwnableUnauthorizedAccount(address account);\n\n    /**\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\n     */\n    error OwnableInvalidOwner(address owner);\n\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\n     */\n    constructor(address initialOwner) {\n        if (initialOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(initialOwner);\n    }\n\n    /**\n     * @dev Throws if called by any account other than the owner.\n     */\n    modifier onlyOwner() {\n        _checkOwner();\n        _;\n    }\n\n    /**\n     * @dev Returns the address of the current owner.\n     */\n    function owner() public view virtual returns (address) {\n        return _owner;\n    }\n\n    /**\n     * @dev Throws if the sender is not the owner.\n     */\n    function _checkOwner() internal view virtual {\n        if (owner() != _msgSender()) {\n            revert OwnableUnauthorizedAccount(_msgSender());\n        }\n    }\n\n    /**\n     * @dev Leaves the contract without owner. It will not be possible to call\n     * `onlyOwner` functions. Can only be called by the current owner.\n     *\n     * NOTE: Renouncing ownership will leave the contract without an owner,\n     * thereby disabling any functionality that is only available to the owner.\n     */\n    function renounceOwnership() public virtual onlyOwner {\n        _transferOwnership(address(0));\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual onlyOwner {\n        if (newOwner == address(0)) {\n            revert OwnableInvalidOwner(address(0));\n        }\n        _transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual {\n        address oldOwner = _owner;\n        _owner = newOwner;\n        emit OwnershipTransferred(oldOwner, newOwner);\n    }\n}\n"
      },
      "@openzeppelin/contracts/access/Ownable2Step.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)\n\npragma solidity ^0.8.20;\n\nimport {Ownable} from \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * The initial owner is specified at deployment time in the constructor for `Ownable`. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n    address private _pendingOwner;\n\n    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n    /**\n     * @dev Returns the address of the pending owner.\n     */\n    function pendingOwner() public view virtual returns (address) {\n        return _pendingOwner;\n    }\n\n    /**\n     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n     * Can only be called by the current owner.\n     */\n    function transferOwnership(address newOwner) public virtual override onlyOwner {\n        _pendingOwner = newOwner;\n        emit OwnershipTransferStarted(owner(), newOwner);\n    }\n\n    /**\n     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n     * Internal function without access restriction.\n     */\n    function _transferOwnership(address newOwner) internal virtual override {\n        delete _pendingOwner;\n        super._transferOwnership(newOwner);\n    }\n\n    /**\n     * @dev The new owner accepts the ownership transfer.\n     */\n    function acceptOwnership() public virtual {\n        address sender = _msgSender();\n        if (pendingOwner() != sender) {\n            revert OwnableUnauthorizedAccount(sender);\n        }\n        _transferOwnership(sender);\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Address.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error AddressInsufficientBalance(address account);\n\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedInnerCall();\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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert AddressInsufficientBalance(address(this));\n        }\n\n        (bool success, ) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            revert FailedInnerCall();\n        }\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 or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {FailedInnerCall} error.\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    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\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    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert AddressInsufficientBalance(address(this));\n        }\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        (bool success, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an\n     * unsuccessful call.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            // only check if target is a contract if the call was successful and the return data is empty\n            // otherwise we already know that it was a contract\n            if (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {FailedInnerCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.\n     */\n    function _revert(bytes memory returndata) 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 FailedInnerCall();\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Context.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/base/Executor.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\nimport \"../common/Enum.sol\";\n\n/**\n * @title Executor - A contract that can execute transactions\n * @author Richard Meissner - @rmeissner\n */\nabstract contract Executor {\n    /**\n     * @notice Executes either a delegatecall or a call with provided parameters.\n     * @dev This method doesn't perform any sanity check of the transaction, such as:\n     *      - if the contract at `to` address has code or not\n     *      It is the responsibility of the caller to perform such checks.\n     * @param to Destination address.\n     * @param value Ether value.\n     * @param data Data payload.\n     * @param operation Operation type.\n     * @return success boolean flag indicating if the call succeeded.\n     */\n    function execute(\n        address to,\n        uint256 value,\n        bytes memory data,\n        Enum.Operation operation,\n        uint256 txGas\n    ) internal returns (bool success) {\n        if (operation == Enum.Operation.DelegateCall) {\n            // solhint-disable-next-line no-inline-assembly\n            assembly {\n                success := delegatecall(txGas, to, add(data, 0x20), mload(data), 0, 0)\n            }\n        } else {\n            // solhint-disable-next-line no-inline-assembly\n            assembly {\n                success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0)\n            }\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/base/FallbackManager.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"../common/SelfAuthorized.sol\";\n\n/**\n * @title Fallback Manager - A contract managing fallback calls made to this contract\n * @author Richard Meissner - @rmeissner\n */\nabstract contract FallbackManager is SelfAuthorized {\n    event ChangedFallbackHandler(address indexed handler);\n\n    // keccak256(\"fallback_manager.handler.address\")\n    bytes32 internal constant FALLBACK_HANDLER_STORAGE_SLOT = 0x6c9a6c4a39284e37ed1cf53d337577d14212a4870fb976a4366c693b939918d5;\n\n    /**\n     *  @notice Internal function to set the fallback handler.\n     *  @param handler contract to handle fallback calls.\n     */\n    function internalSetFallbackHandler(address handler) internal {\n        /*\n            If a fallback handler is set to self, then the following attack vector is opened:\n            Imagine we have a function like this:\n            function withdraw() internal authorized {\n                withdrawalAddress.call.value(address(this).balance)(\"\");\n            }\n\n            If the fallback method is triggered, the fallback handler appends the msg.sender address to the calldata and calls the fallback handler.\n            A potential attacker could call a Safe with the 3 bytes signature of a withdraw function. Since 3 bytes do not create a valid signature,\n            the call would end in a fallback handler. Since it appends the msg.sender address to the calldata, the attacker could craft an address \n            where the first 3 bytes of the previous calldata + the first byte of the address make up a valid function signature. The subsequent call would result in unsanctioned access to Safe's internal protected methods.\n            For some reason, solidity matches the first 4 bytes of the calldata to a function signature, regardless if more data follow these 4 bytes.\n        */\n        require(handler != address(this), \"GS400\");\n\n        bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            sstore(slot, handler)\n        }\n    }\n\n    /**\n     * @notice Set Fallback Handler to `handler` for the Safe.\n     * @dev Only fallback calls without value and with data will be forwarded.\n     *      This can only be done via a Safe transaction.\n     *      Cannot be set to the Safe itself.\n     * @param handler contract to handle fallback calls.\n     */\n    function setFallbackHandler(address handler) public authorized {\n        internalSetFallbackHandler(handler);\n        emit ChangedFallbackHandler(handler);\n    }\n\n    // @notice Forwards all calls to the fallback handler if set. Returns 0 if no handler is set.\n    // @dev Appends the non-padded caller address to the calldata to be optionally used in the handler\n    //      The handler can make us of `HandlerContext.sol` to extract the address.\n    //      This is done because in the next call frame the `msg.sender` will be FallbackManager's address\n    //      and having the original caller address may enable additional verification scenarios.\n    // solhint-disable-next-line payable-fallback,no-complex-fallback\n    fallback() external {\n        bytes32 slot = FALLBACK_HANDLER_STORAGE_SLOT;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let handler := sload(slot)\n            if iszero(handler) {\n                return(0, 0)\n            }\n            calldatacopy(0, 0, calldatasize())\n            // The msg.sender address is shifted to the left by 12 bytes to remove the padding\n            // Then the address without padding is stored right after the calldata\n            mstore(calldatasize(), shl(96, caller()))\n            // Add 20 bytes for the address appended add the end\n            let success := call(gas(), handler, 0, 0, add(calldatasize(), 20), 0, 0)\n            returndatacopy(0, 0, returndatasize())\n            if iszero(success) {\n                revert(0, returndatasize())\n            }\n            return(0, returndatasize())\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/base/GuardManager.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"../common/Enum.sol\";\nimport \"../common/SelfAuthorized.sol\";\nimport \"../interfaces/IERC165.sol\";\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\nabstract contract BaseGuard is Guard {\n    function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {\n        return\n            interfaceId == type(Guard).interfaceId || // 0xe6d7a83a\n            interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7\n    }\n}\n\n/**\n * @title Guard Manager - A contract managing transaction guards which perform pre and post-checks on Safe transactions.\n * @author Richard Meissner - @rmeissner\n */\nabstract contract GuardManager is SelfAuthorized {\n    event ChangedGuard(address indexed guard);\n\n    // keccak256(\"guard_manager.guard.address\")\n    bytes32 internal constant GUARD_STORAGE_SLOT = 0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8;\n\n    /**\n     * @dev Set a guard that checks transactions before execution\n     *      This can only be done via a Safe transaction.\n     *      ⚠️ IMPORTANT: Since a guard has full power to block Safe transaction execution,\n     *        a broken guard can cause a denial of service for the Safe. Make sure to carefully\n     *        audit the guard code and design recovery mechanisms.\n     * @notice Set Transaction Guard `guard` for the Safe. Make sure you trust the guard.\n     * @param guard The address of the guard to be used or the 0 address to disable the guard\n     */\n    function setGuard(address guard) external authorized {\n        if (guard != address(0)) {\n            require(Guard(guard).supportsInterface(type(Guard).interfaceId), \"GS300\");\n        }\n        bytes32 slot = GUARD_STORAGE_SLOT;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            sstore(slot, guard)\n        }\n        emit ChangedGuard(guard);\n    }\n\n    /**\n     * @dev Internal method to retrieve the current guard\n     *      We do not have a public method because we're short on bytecode size limit,\n     *      to retrieve the guard address, one can use `getStorageAt` from `StorageAccessible` contract\n     *      with the slot `GUARD_STORAGE_SLOT`\n     * @return guard The address of the guard\n     */\n    function getGuard() internal view returns (address guard) {\n        bytes32 slot = GUARD_STORAGE_SLOT;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            guard := sload(slot)\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/base/ModuleManager.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\nimport \"../common/Enum.sol\";\nimport \"../common/SelfAuthorized.sol\";\nimport \"./Executor.sol\";\n\n/**\n * @title Module Manager - A contract managing Safe modules\n * @notice Modules are extensions with unlimited access to a Safe that can be added to a Safe by its owners.\n           ⚠️ WARNING: Modules are a security risk since they can execute arbitrary transactions, \n           so only trusted and audited modules should be added to a Safe. A malicious module can\n           completely takeover a Safe.\n * @author Stefan George - @Georgi87\n * @author Richard Meissner - @rmeissner\n */\nabstract contract ModuleManager is SelfAuthorized, Executor {\n    event EnabledModule(address indexed module);\n    event DisabledModule(address indexed module);\n    event ExecutionFromModuleSuccess(address indexed module);\n    event ExecutionFromModuleFailure(address indexed module);\n\n    address internal constant SENTINEL_MODULES = address(0x1);\n\n    mapping(address => address) internal modules;\n\n    /**\n     * @notice Setup function sets the initial storage of the contract.\n     *         Optionally executes a delegate call to another contract to setup the modules.\n     * @param to Optional destination address of call to execute.\n     * @param data Optional data of call to execute.\n     */\n    function setupModules(address to, bytes memory data) internal {\n        require(modules[SENTINEL_MODULES] == address(0), \"GS100\");\n        modules[SENTINEL_MODULES] = SENTINEL_MODULES;\n        if (to != address(0)) {\n            require(isContract(to), \"GS002\");\n            // Setup has to complete successfully or transaction fails.\n            require(execute(to, 0, data, Enum.Operation.DelegateCall, type(uint256).max), \"GS000\");\n        }\n    }\n\n    /**\n     * @notice Enables the module `module` for the Safe.\n     * @dev This can only be done via a Safe transaction.\n     * @param module Module to be whitelisted.\n     */\n    function enableModule(address module) public authorized {\n        // Module address cannot be null or sentinel.\n        require(module != address(0) && module != SENTINEL_MODULES, \"GS101\");\n        // Module cannot be added twice.\n        require(modules[module] == address(0), \"GS102\");\n        modules[module] = modules[SENTINEL_MODULES];\n        modules[SENTINEL_MODULES] = module;\n        emit EnabledModule(module);\n    }\n\n    /**\n     * @notice Disables the module `module` for the Safe.\n     * @dev This can only be done via a Safe transaction.\n     * @param prevModule Previous module in the modules linked list.\n     * @param module Module to be removed.\n     */\n    function disableModule(address prevModule, address module) public authorized {\n        // Validate module address and check that it corresponds to module index.\n        require(module != address(0) && module != SENTINEL_MODULES, \"GS101\");\n        require(modules[prevModule] == module, \"GS103\");\n        modules[prevModule] = modules[module];\n        modules[module] = address(0);\n        emit DisabledModule(module);\n    }\n\n    /**\n     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token)\n     * @dev Function is virtual to allow overriding for L2 singleton to emit an event for indexing.\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     * @return success Boolean flag indicating if the call succeeded.\n     */\n    function execTransactionFromModule(\n        address to,\n        uint256 value,\n        bytes memory data,\n        Enum.Operation operation\n    ) public virtual returns (bool success) {\n        // Only whitelisted modules are allowed.\n        require(msg.sender != SENTINEL_MODULES && modules[msg.sender] != address(0), \"GS104\");\n        // Execute transaction without further confirmations.\n        success = execute(to, value, data, operation, type(uint256).max);\n        if (success) emit ExecutionFromModuleSuccess(msg.sender);\n        else emit ExecutionFromModuleFailure(msg.sender);\n    }\n\n    /**\n     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token) 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     * @return success Boolean flag indicating if the call succeeded.\n     * @return returnData Data returned by the call.\n     */\n    function execTransactionFromModuleReturnData(\n        address to,\n        uint256 value,\n        bytes memory data,\n        Enum.Operation operation\n    ) public returns (bool success, bytes memory returnData) {\n        success = execTransactionFromModule(to, value, data, operation);\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            // Load free memory location\n            let ptr := mload(0x40)\n            // We allocate memory for the return data by setting the free memory location to\n            // current free memory location + data size + 32 bytes for data size value\n            mstore(0x40, add(ptr, add(returndatasize(), 0x20)))\n            // Store the size\n            mstore(ptr, returndatasize())\n            // Store the data\n            returndatacopy(add(ptr, 0x20), 0, returndatasize())\n            // Point the return data to the correct memory location\n            returnData := ptr\n        }\n    }\n\n    /**\n     * @notice Returns if an module is enabled\n     * @return True if the module is enabled\n     */\n    function isModuleEnabled(address module) public view returns (bool) {\n        return SENTINEL_MODULES != module && modules[module] != address(0);\n    }\n\n    /**\n     * @notice Returns an array of modules.\n     *         If all entries fit into a single page, the next pointer will be 0x1.\n     *         If another page is present, next will be the last element of the returned array.\n     * @param start Start of the page. Has to be a module or start pointer (0x1 address)\n     * @param pageSize Maximum number of modules that should be returned. Has to be > 0\n     * @return array Array of modules.\n     * @return next Start of the next page.\n     */\n    function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) {\n        require(start == SENTINEL_MODULES || isModuleEnabled(start), \"GS105\");\n        require(pageSize > 0, \"GS106\");\n        // Init array with max page size\n        array = new address[](pageSize);\n\n        // Populate return array\n        uint256 moduleCount = 0;\n        next = modules[start];\n        while (next != address(0) && next != SENTINEL_MODULES && moduleCount < pageSize) {\n            array[moduleCount] = next;\n            next = modules[next];\n            moduleCount++;\n        }\n\n        /**\n          Because of the argument validation, we can assume that the loop will always iterate over the valid module list values\n          and the `next` variable will either be an enabled module or a sentinel address (signalling the end). \n          \n          If we haven't reached the end inside the loop, we need to set the next pointer to the last element of the modules array\n          because the `next` variable (which is a module by itself) acting as a pointer to the start of the next page is neither \n          included to the current page, nor will it be included in the next one if you pass it as a start.\n        */\n        if (next != SENTINEL_MODULES) {\n            next = array[moduleCount - 1];\n        }\n        // Set correct size of returned array\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            mstore(array, moduleCount)\n        }\n    }\n\n    /**\n     * @notice Returns true if `account` is a contract.\n     * @dev This function will return false if invoked during the constructor of a contract,\n     *      as the code is not actually created until after the constructor finishes.\n     * @param account The address being queried\n     */\n    function isContract(address account) internal view returns (bool) {\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/base/OwnerManager.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\nimport \"../common/SelfAuthorized.sol\";\n\n/**\n * @title OwnerManager - Manages Safe owners and a threshold to authorize transactions.\n * @dev Uses a linked list to store the owners because the code generate by the solidity compiler\n *      is more efficient than using a dynamic array.\n * @author Stefan George - @Georgi87\n * @author Richard Meissner - @rmeissner\n */\nabstract contract OwnerManager is SelfAuthorized {\n    event AddedOwner(address indexed owner);\n    event RemovedOwner(address indexed owner);\n    event ChangedThreshold(uint256 threshold);\n\n    address internal constant SENTINEL_OWNERS = address(0x1);\n\n    mapping(address => address) internal owners;\n    uint256 internal ownerCount;\n    uint256 internal threshold;\n\n    /**\n     * @notice Sets the initial storage of the contract.\n     * @param _owners List of Safe owners.\n     * @param _threshold Number of required confirmations for a Safe transaction.\n     */\n    function setupOwners(address[] memory _owners, uint256 _threshold) internal {\n        // Threshold can only be 0 at initialization.\n        // Check ensures that setup function can only be called once.\n        require(threshold == 0, \"GS200\");\n        // Validate that threshold is smaller than number of added owners.\n        require(_threshold <= _owners.length, \"GS201\");\n        // There has to be at least one Safe owner.\n        require(_threshold >= 1, \"GS202\");\n        // Initializing Safe owners.\n        address currentOwner = SENTINEL_OWNERS;\n        for (uint256 i = 0; i < _owners.length; i++) {\n            // Owner address cannot be null.\n            address owner = _owners[i];\n            require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this) && currentOwner != owner, \"GS203\");\n            // No duplicate owners allowed.\n            require(owners[owner] == address(0), \"GS204\");\n            owners[currentOwner] = owner;\n            currentOwner = owner;\n        }\n        owners[currentOwner] = SENTINEL_OWNERS;\n        ownerCount = _owners.length;\n        threshold = _threshold;\n    }\n\n    /**\n     * @notice Adds the owner `owner` to the Safe and updates the threshold to `_threshold`.\n     * @dev This can only be done via a Safe transaction.\n     * @param owner New owner address.\n     * @param _threshold New threshold.\n     */\n    function addOwnerWithThreshold(address owner, uint256 _threshold) public authorized {\n        // Owner address cannot be null, the sentinel or the Safe itself.\n        require(owner != address(0) && owner != SENTINEL_OWNERS && owner != address(this), \"GS203\");\n        // No duplicate owners allowed.\n        require(owners[owner] == address(0), \"GS204\");\n        owners[owner] = owners[SENTINEL_OWNERS];\n        owners[SENTINEL_OWNERS] = owner;\n        ownerCount++;\n        emit AddedOwner(owner);\n        // Change threshold if threshold was changed.\n        if (threshold != _threshold) changeThreshold(_threshold);\n    }\n\n    /**\n     * @notice Removes the owner `owner` from the Safe and updates the threshold to `_threshold`.\n     * @dev This can only be done via a Safe transaction.\n     * @param prevOwner Owner that pointed to the owner to be removed in the linked list\n     * @param owner Owner address to be removed.\n     * @param _threshold New threshold.\n     */\n    function removeOwner(address prevOwner, address owner, uint256 _threshold) public authorized {\n        // Only allow to remove an owner, if threshold can still be reached.\n        require(ownerCount - 1 >= _threshold, \"GS201\");\n        // Validate owner address and check that it corresponds to owner index.\n        require(owner != address(0) && owner != SENTINEL_OWNERS, \"GS203\");\n        require(owners[prevOwner] == owner, \"GS205\");\n        owners[prevOwner] = owners[owner];\n        owners[owner] = address(0);\n        ownerCount--;\n        emit RemovedOwner(owner);\n        // Change threshold if threshold was changed.\n        if (threshold != _threshold) changeThreshold(_threshold);\n    }\n\n    /**\n     * @notice Replaces the owner `oldOwner` in the Safe with `newOwner`.\n     * @dev This can only be done via a Safe transaction.\n     * @param prevOwner Owner that pointed to the owner to be replaced in the linked list\n     * @param oldOwner Owner address to be replaced.\n     * @param newOwner New owner address.\n     */\n    function swapOwner(address prevOwner, address oldOwner, address newOwner) public authorized {\n        // Owner address cannot be null, the sentinel or the Safe itself.\n        require(newOwner != address(0) && newOwner != SENTINEL_OWNERS && newOwner != address(this), \"GS203\");\n        // No duplicate owners allowed.\n        require(owners[newOwner] == address(0), \"GS204\");\n        // Validate oldOwner address and check that it corresponds to owner index.\n        require(oldOwner != address(0) && oldOwner != SENTINEL_OWNERS, \"GS203\");\n        require(owners[prevOwner] == oldOwner, \"GS205\");\n        owners[newOwner] = owners[oldOwner];\n        owners[prevOwner] = newOwner;\n        owners[oldOwner] = address(0);\n        emit RemovedOwner(oldOwner);\n        emit AddedOwner(newOwner);\n    }\n\n    /**\n     * @notice Changes the threshold of the Safe to `_threshold`.\n     * @dev This can only be done via a Safe transaction.\n     * @param _threshold New threshold.\n     */\n    function changeThreshold(uint256 _threshold) public authorized {\n        // Validate that threshold is smaller than number of owners.\n        require(_threshold <= ownerCount, \"GS201\");\n        // There has to be at least one Safe owner.\n        require(_threshold >= 1, \"GS202\");\n        threshold = _threshold;\n        emit ChangedThreshold(threshold);\n    }\n\n    /**\n     * @notice Returns the number of required confirmations for a Safe transaction aka the threshold.\n     * @return Threshold number.\n     */\n    function getThreshold() public view returns (uint256) {\n        return threshold;\n    }\n\n    /**\n     * @notice Returns if `owner` is an owner of the Safe.\n     * @return Boolean if owner is an owner of the Safe.\n     */\n    function isOwner(address owner) public view returns (bool) {\n        return owner != SENTINEL_OWNERS && owners[owner] != address(0);\n    }\n\n    /**\n     * @notice Returns a list of Safe owners.\n     * @return Array of Safe owners.\n     */\n    function getOwners() public view returns (address[] memory) {\n        address[] memory array = new address[](ownerCount);\n\n        // populate return array\n        uint256 index = 0;\n        address currentOwner = owners[SENTINEL_OWNERS];\n        while (currentOwner != SENTINEL_OWNERS) {\n            array[index] = currentOwner;\n            currentOwner = owners[currentOwner];\n            index++;\n        }\n        return array;\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/Enum.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title Enum - Collection of enums used in Safe contracts.\n * @author Richard Meissner - @rmeissner\n */\nabstract contract Enum {\n    enum Operation {\n        Call,\n        DelegateCall\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/NativeCurrencyPaymentFallback.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title NativeCurrencyPaymentFallback - A contract that has a fallback to accept native currency payments.\n * @author Richard Meissner - @rmeissner\n */\nabstract contract NativeCurrencyPaymentFallback {\n    event SafeReceived(address indexed sender, uint256 value);\n\n    /**\n     * @notice Receive function accepts native currency transactions.\n     * @dev Emits an event with sender and received value.\n     */\n    receive() external payable {\n        emit SafeReceived(msg.sender, msg.value);\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/SecuredTokenTransfer.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title SecuredTokenTransfer - Secure token transfer.\n * @author Richard Meissner - @rmeissner\n */\nabstract contract SecuredTokenTransfer {\n    /**\n     * @notice Transfers a token and returns a boolean if it was a success\n     * @dev It checks the return data of the transfer call and returns true if the transfer was successful.\n     *      It doesn't check if the `token` address is a contract or not.\n     * @param token Token that should be transferred\n     * @param receiver Receiver to whom the token should be transferred\n     * @param amount The amount of tokens that should be transferred\n     * @return transferred Returns true if the transfer was successful\n     */\n    function transferToken(address token, address receiver, uint256 amount) internal returns (bool transferred) {\n        // 0xa9059cbb - keccack(\"transfer(address,uint256)\")\n        bytes memory data = abi.encodeWithSelector(0xa9059cbb, receiver, amount);\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            // We write the return value to scratch space.\n            // See https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory\n            let success := call(sub(gas(), 10000), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            switch returndatasize()\n            case 0 {\n                transferred := success\n            }\n            case 0x20 {\n                transferred := iszero(or(iszero(success), iszero(mload(0))))\n            }\n            default {\n                transferred := 0\n            }\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/SelfAuthorized.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title SelfAuthorized - Authorizes current contract to perform actions to itself.\n * @author Richard Meissner - @rmeissner\n */\nabstract contract SelfAuthorized {\n    function requireSelfCall() private view {\n        require(msg.sender == address(this), \"GS031\");\n    }\n\n    modifier authorized() {\n        // Modifiers are copied around during compilation. This is a function call as it minimized the bytecode size\n        requireSelfCall();\n        _;\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/SignatureDecoder.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title SignatureDecoder - Decodes signatures encoded as bytes\n * @author Richard Meissner - @rmeissner\n */\nabstract contract SignatureDecoder {\n    /**\n     * @notice Splits signature bytes into `uint8 v, bytes32 r, bytes32 s`.\n     * @dev Make sure to perform a bounds check for @param pos, to avoid out of bounds access on @param signatures\n     *      The signature format is a compact form of {bytes32 r}{bytes32 s}{uint8 v}\n     *      Compact means uint8 is not padded to 32 bytes.\n     * @param pos Which signature to read.\n     *            A prior bounds check of this parameter should be performed, to avoid out of bounds access.\n     * @param signatures Concatenated {r, s, v} signatures.\n     * @return v Recovery ID or Safe signature type.\n     * @return r Output value r of the signature.\n     * @return s Output value s of the signature.\n     */\n    function signatureSplit(bytes memory signatures, uint256 pos) internal pure returns (uint8 v, bytes32 r, bytes32 s) {\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let signaturePos := mul(0x41, pos)\n            r := mload(add(signatures, add(signaturePos, 0x20)))\n            s := mload(add(signatures, add(signaturePos, 0x40)))\n            /**\n             * Here we are loading the last 32 bytes, including 31 bytes\n             * of 's'. There is no 'mload8' to do this.\n             * 'byte' is not working due to the Solidity parser, so lets\n             * use the second best option, 'and'\n             */\n            v := and(mload(add(signatures, add(signaturePos, 0x41))), 0xff)\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/Singleton.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title Singleton - Base for singleton contracts (should always be the first super contract)\n *        This contract is tightly coupled to our proxy contract (see `proxies/SafeProxy.sol`)\n * @author Richard Meissner - @rmeissner\n */\nabstract contract Singleton {\n    // singleton always has to be the first declared variable to ensure the same location as in the Proxy contract.\n    // It should also always be ensured the address is stored alone (uses a full word)\n    address private singleton;\n}\n"
      },
      "@safe-global/safe-contracts/contracts/common/StorageAccessible.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title StorageAccessible - A generic base contract that allows callers to access all internal storage.\n * @notice See https://github.com/gnosis/util-contracts/blob/bb5fe5fb5df6d8400998094fb1b32a178a47c3a1/contracts/StorageAccessible.sol\n *         It removes a method from the original contract not needed for the Safe contracts.\n * @author Gnosis Developers\n */\nabstract contract StorageAccessible {\n    /**\n     * @notice Reads `length` bytes of storage in the currents contract\n     * @param offset - the offset in the current contract's storage in words to start reading from\n     * @param length - the number of words (32 bytes) of data to read\n     * @return the bytes that were read.\n     */\n    function getStorageAt(uint256 offset, uint256 length) public view returns (bytes memory) {\n        bytes memory result = new bytes(length * 32);\n        for (uint256 index = 0; index < length; index++) {\n            // solhint-disable-next-line no-inline-assembly\n            assembly {\n                let word := sload(add(offset, index))\n                mstore(add(add(result, 0x20), mul(index, 0x20)), word)\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Performs a delegatecall on a targetContract in the context of self.\n     * Internally reverts execution to avoid side effects (making it static).\n     *\n     * This method reverts with data equal to `abi.encode(bool(success), bytes(response))`.\n     * Specifically, the `returndata` after a call to this method will be:\n     * `success:bool || response.length:uint256 || response:bytes`.\n     *\n     * @param targetContract Address of the contract containing the code to execute.\n     * @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments).\n     */\n    function simulateAndRevert(address targetContract, bytes memory calldataPayload) external {\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let success := delegatecall(gas(), targetContract, add(calldataPayload, 0x20), mload(calldataPayload), 0, 0)\n\n            mstore(0x00, success)\n            mstore(0x20, returndatasize())\n            returndatacopy(0x40, 0, returndatasize())\n            revert(0, add(returndatasize(), 0x40))\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/external/SafeMath.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title SafeMath\n * @notice Math operations with safety checks that revert on error (overflow/underflow)\n */\nlibrary SafeMath {\n    /**\n     * @notice Multiplies two numbers, reverts on overflow.\n     * @param a First number\n     * @param b Second number\n     * @return Product of a and b\n     */\n    function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n        // benefit is lost if 'b' is also tested.\n        // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n        if (a == 0) {\n            return 0;\n        }\n\n        uint256 c = a * b;\n        require(c / a == b);\n\n        return c;\n    }\n\n    /**\n     * @notice Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).\n     * @param a First number\n     * @param b Second number\n     * @return Difference of a and b\n     */\n    function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n        require(b <= a);\n        uint256 c = a - b;\n\n        return c;\n    }\n\n    /**\n     * @notice Adds two numbers, reverts on overflow.\n     * @param a First number\n     * @param b Second number\n     * @return Sum of a and b\n     */\n    function add(uint256 a, uint256 b) internal pure returns (uint256) {\n        uint256 c = a + b;\n        require(c >= a);\n\n        return c;\n    }\n\n    /**\n     * @notice Returns the largest of two numbers.\n     * @param a First number\n     * @param b Second number\n     * @return Largest of a and b\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a >= b ? a : b;\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/interfaces/IERC165.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by `interfaceId`.\n     * See the corresponding EIP section\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified\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"
      },
      "@safe-global/safe-contracts/contracts/interfaces/ISignatureValidator.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\ncontract ISignatureValidatorConstants {\n    // bytes4(keccak256(\"isValidSignature(bytes,bytes)\")\n    bytes4 internal constant EIP1271_MAGIC_VALUE = 0x20c13b0b;\n}\n\nabstract contract ISignatureValidator is ISignatureValidatorConstants {\n    /**\n     * @notice Legacy EIP1271 method to validate a signature.\n     * @param _data Arbitrary length data signed on the behalf of address(this).\n     * @param _signature Signature byte array associated with _data.\n     *\n     * MUST return the bytes4 magic value 0x20c13b0b when function passes.\n     * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)\n     * MUST allow external calls\n     */\n    function isValidSignature(bytes memory _data, bytes memory _signature) public view virtual returns (bytes4);\n}\n"
      },
      "@safe-global/safe-contracts/contracts/proxies/SafeProxy.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\n/**\n * @title IProxy - Helper interface to access the singleton address of the Proxy on-chain.\n * @author Richard Meissner - @rmeissner\n */\ninterface IProxy {\n    function masterCopy() external view returns (address);\n}\n\n/**\n * @title SafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.\n * @author Stefan George - <stefan@gnosis.io>\n * @author Richard Meissner - <richard@gnosis.io>\n */\ncontract SafeProxy {\n    // Singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.\n    // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`\n    address internal singleton;\n\n    /**\n     * @notice Constructor function sets address of singleton contract.\n     * @param _singleton Singleton address.\n     */\n    constructor(address _singleton) {\n        require(_singleton != address(0), \"Invalid singleton address provided\");\n        singleton = _singleton;\n    }\n\n    /// @dev Fallback function forwards all transactions and returns all received return data.\n    fallback() external payable {\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)\n            // 0xa619486e == keccak(\"masterCopy()\"). The value is right padded to 32-bytes with 0s\n            if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) {\n                mstore(0, _singleton)\n                return(0, 0x20)\n            }\n            calldatacopy(0, 0, calldatasize())\n            let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)\n            returndatacopy(0, 0, returndatasize())\n            if eq(success, 0) {\n                revert(0, returndatasize())\n            }\n            return(0, returndatasize())\n        }\n    }\n}\n"
      },
      "@safe-global/safe-contracts/contracts/Safe.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity >=0.7.0 <0.9.0;\n\nimport \"./base/ModuleManager.sol\";\nimport \"./base/OwnerManager.sol\";\nimport \"./base/FallbackManager.sol\";\nimport \"./base/GuardManager.sol\";\nimport \"./common/NativeCurrencyPaymentFallback.sol\";\nimport \"./common/Singleton.sol\";\nimport \"./common/SignatureDecoder.sol\";\nimport \"./common/SecuredTokenTransfer.sol\";\nimport \"./common/StorageAccessible.sol\";\nimport \"./interfaces/ISignatureValidator.sol\";\nimport \"./external/SafeMath.sol\";\n\n/**\n * @title Safe - A multisignature wallet with support for confirmations using signed messages based on EIP-712.\n * @dev Most important concepts:\n *      - Threshold: Number of required confirmations for a Safe transaction.\n *      - Owners: List of addresses that control the Safe. They are the only ones that can add/remove owners, change the threshold and\n *        approve transactions. Managed in `OwnerManager`.\n *      - Transaction Hash: Hash of a transaction is calculated using the EIP-712 typed structured data hashing scheme.\n *      - Nonce: Each transaction should have a different nonce to prevent replay attacks.\n *      - Signature: A valid signature of an owner of the Safe for a transaction hash.\n *      - Guard: Guard is a contract that can execute pre- and post- transaction checks. Managed in `GuardManager`.\n *      - Modules: Modules are contracts that can be used to extend the write functionality of a Safe. Managed in `ModuleManager`.\n *      - Fallback: Fallback handler is a contract that can provide additional read-only functional for Safe. Managed in `FallbackManager`.\n *      Note: This version of the implementation contract doesn't emit events for the sake of gas efficiency and therefore requires a tracing node for indexing/\n *      For the events-based implementation see `SafeL2.sol`.\n * @author Stefan George - @Georgi87\n * @author Richard Meissner - @rmeissner\n */\ncontract Safe is\n    Singleton,\n    NativeCurrencyPaymentFallback,\n    ModuleManager,\n    OwnerManager,\n    SignatureDecoder,\n    SecuredTokenTransfer,\n    ISignatureValidatorConstants,\n    FallbackManager,\n    StorageAccessible,\n    GuardManager\n{\n    using SafeMath for uint256;\n\n    string public constant VERSION = \"1.4.1\";\n\n    // keccak256(\n    //     \"EIP712Domain(uint256 chainId,address verifyingContract)\"\n    // );\n    bytes32 private constant DOMAIN_SEPARATOR_TYPEHASH = 0x47e79534a245952e8b16893a336b85a3d9ea9fa8c573f3d803afb92a79469218;\n\n    // keccak256(\n    //     \"SafeTx(address to,uint256 value,bytes data,uint8 operation,uint256 safeTxGas,uint256 baseGas,uint256 gasPrice,address gasToken,address refundReceiver,uint256 nonce)\"\n    // );\n    bytes32 private constant SAFE_TX_TYPEHASH = 0xbb8310d486368db6bd6f849402fdd73ad53d316b5a4b2644ad6efe0f941286d8;\n\n    event SafeSetup(address indexed initiator, address[] owners, uint256 threshold, address initializer, address fallbackHandler);\n    event ApproveHash(bytes32 indexed approvedHash, address indexed owner);\n    event SignMsg(bytes32 indexed msgHash);\n    event ExecutionFailure(bytes32 indexed txHash, uint256 payment);\n    event ExecutionSuccess(bytes32 indexed txHash, uint256 payment);\n\n    uint256 public nonce;\n    bytes32 private _deprecatedDomainSeparator;\n    // Mapping to keep track of all message hashes that have been approved by ALL REQUIRED owners\n    mapping(bytes32 => uint256) public signedMessages;\n    // Mapping to keep track of all hashes (message or transaction) that have been approved by ANY owners\n    mapping(address => mapping(bytes32 => uint256)) public approvedHashes;\n\n    // This constructor ensures that this contract can only be used as a singleton for Proxy contracts\n    constructor() {\n        /**\n         * By setting the threshold it is not possible to call setup anymore,\n         * so we create a Safe with 0 owners and threshold 1.\n         * This is an unusable Safe, perfect for the singleton\n         */\n        threshold = 1;\n    }\n\n    /**\n     * @notice Sets an initial storage of the Safe contract.\n     * @dev This method can only be called once.\n     *      If a proxy was created without setting up, anyone can call setup and claim the proxy.\n     * @param _owners List of Safe owners.\n     * @param _threshold Number of required confirmations for a Safe transaction.\n     * @param to Contract address for optional delegate call.\n     * @param data Data payload for optional delegate call.\n     * @param fallbackHandler Handler for fallback calls to this contract\n     * @param paymentToken Token that should be used for the payment (0 is ETH)\n     * @param payment Value that should be paid\n     * @param paymentReceiver Address that should receive the payment (or 0 if tx.origin)\n     */\n    function setup(\n        address[] calldata _owners,\n        uint256 _threshold,\n        address to,\n        bytes calldata data,\n        address fallbackHandler,\n        address paymentToken,\n        uint256 payment,\n        address payable paymentReceiver\n    ) external {\n        // setupOwners checks if the Threshold is already set, therefore preventing that this method is called twice\n        setupOwners(_owners, _threshold);\n        if (fallbackHandler != address(0)) internalSetFallbackHandler(fallbackHandler);\n        // As setupOwners can only be called if the contract has not been initialized we don't need a check for setupModules\n        setupModules(to, data);\n\n        if (payment > 0) {\n            // To avoid running into issues with EIP-170 we reuse the handlePayment function (to avoid adjusting code of that has been verified we do not adjust the method itself)\n            // baseGas = 0, gasPrice = 1 and gas = payment => amount = (payment + 0) * 1 = payment\n            handlePayment(payment, 0, 1, paymentToken, paymentReceiver);\n        }\n        emit SafeSetup(msg.sender, _owners, _threshold, to, fallbackHandler);\n    }\n\n    /** @notice Executes a `operation` {0: Call, 1: DelegateCall}} transaction to `to` with `value` (Native Currency)\n     *          and pays `gasPrice` * `gasLimit` in `gasToken` token to `refundReceiver`.\n     * @dev The fees are always transferred, even if the user transaction fails.\n     *      This method doesn't perform any sanity check of the transaction, such as:\n     *      - if the contract at `to` address has code or not\n     *      - if the `gasToken` is a contract or not\n     *      It is the responsibility of the caller to perform such checks.\n     * @param to Destination address of Safe transaction.\n     * @param value Ether value of Safe transaction.\n     * @param data Data payload of Safe transaction.\n     * @param operation Operation type of Safe transaction.\n     * @param safeTxGas Gas that should be used for the Safe transaction.\n     * @param baseGas Gas costs that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)\n     * @param gasPrice Gas price that should be used for the payment calculation.\n     * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n     * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n     * @param signatures Signature data that should be verified.\n     *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.\n     * @return success Boolean indicating transaction's success.\n     */\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    ) public payable virtual returns (bool success) {\n        bytes32 txHash;\n        // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n        {\n            bytes memory txHashData = encodeTransactionData(\n                // Transaction info\n                to,\n                value,\n                data,\n                operation,\n                safeTxGas,\n                // Payment info\n                baseGas,\n                gasPrice,\n                gasToken,\n                refundReceiver,\n                // Signature info\n                nonce\n            );\n            // Increase nonce and execute transaction.\n            nonce++;\n            txHash = keccak256(txHashData);\n            checkSignatures(txHash, txHashData, signatures);\n        }\n        address guard = getGuard();\n        {\n            if (guard != address(0)) {\n                Guard(guard).checkTransaction(\n                    // Transaction info\n                    to,\n                    value,\n                    data,\n                    operation,\n                    safeTxGas,\n                    // Payment info\n                    baseGas,\n                    gasPrice,\n                    gasToken,\n                    refundReceiver,\n                    // Signature info\n                    signatures,\n                    msg.sender\n                );\n            }\n        }\n        // We require some gas to emit the events (at least 2500) after the execution and some to perform code until the execution (500)\n        // We also include the 1/64 in the check that is not send along with a call to counteract potential shortings because of EIP-150\n        require(gasleft() >= ((safeTxGas * 64) / 63).max(safeTxGas + 2500) + 500, \"GS010\");\n        // Use scope here to limit variable lifetime and prevent `stack too deep` errors\n        {\n            uint256 gasUsed = gasleft();\n            // If the gasPrice is 0 we assume that nearly all available gas can be used (it is always more than safeTxGas)\n            // We only substract 2500 (compared to the 3000 before) to ensure that the amount passed is still higher than safeTxGas\n            success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas);\n            gasUsed = gasUsed.sub(gasleft());\n            // If no safeTxGas and no gasPrice was set (e.g. both are 0), then the internal tx is required to be successful\n            // This makes it possible to use `estimateGas` without issues, as it searches for the minimum gas where the tx doesn't revert\n            require(success || safeTxGas != 0 || gasPrice != 0, \"GS013\");\n            // We transfer the calculated tx costs to the tx.origin to avoid sending it to intermediate contracts that have made calls\n            uint256 payment = 0;\n            if (gasPrice > 0) {\n                payment = handlePayment(gasUsed, baseGas, gasPrice, gasToken, refundReceiver);\n            }\n            if (success) emit ExecutionSuccess(txHash, payment);\n            else emit ExecutionFailure(txHash, payment);\n        }\n        {\n            if (guard != address(0)) {\n                Guard(guard).checkAfterExecution(txHash, success);\n            }\n        }\n    }\n\n    /**\n     * @notice Handles the payment for a Safe transaction.\n     * @param gasUsed Gas used by the Safe transaction.\n     * @param baseGas Gas costs that are independent of the transaction execution (e.g. base transaction fee, signature check, payment of the refund).\n     * @param gasPrice Gas price that should be used for the payment calculation.\n     * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n     * @return payment The amount of payment made in the specified token.\n     */\n    function handlePayment(\n        uint256 gasUsed,\n        uint256 baseGas,\n        uint256 gasPrice,\n        address gasToken,\n        address payable refundReceiver\n    ) private returns (uint256 payment) {\n        // solhint-disable-next-line avoid-tx-origin\n        address payable receiver = refundReceiver == address(0) ? payable(tx.origin) : refundReceiver;\n        if (gasToken == address(0)) {\n            // For ETH we will only adjust the gas price to not be higher than the actual used gas price\n            payment = gasUsed.add(baseGas).mul(gasPrice < tx.gasprice ? gasPrice : tx.gasprice);\n            require(receiver.send(payment), \"GS011\");\n        } else {\n            payment = gasUsed.add(baseGas).mul(gasPrice);\n            require(transferToken(gasToken, receiver, payment), \"GS012\");\n        }\n    }\n\n    /**\n     * @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.\n     * @param dataHash Hash of the data (could be either a message hash or transaction hash)\n     * @param data That should be signed (this is passed to an external validator contract)\n     * @param signatures Signature data that should be verified.\n     *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.\n     */\n    function checkSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures) public view {\n        // Load threshold to avoid multiple storage loads\n        uint256 _threshold = threshold;\n        // Check that a threshold is set\n        require(_threshold > 0, \"GS001\");\n        checkNSignatures(dataHash, data, signatures, _threshold);\n    }\n\n    /**\n     * @notice Checks whether the signature provided is valid for the provided data and hash. Reverts otherwise.\n     * @dev Since the EIP-1271 does an external call, be mindful of reentrancy attacks.\n     * @param dataHash Hash of the data (could be either a message hash or transaction hash)\n     * @param data That should be signed (this is passed to an external validator contract)\n     * @param signatures Signature data that should be verified.\n     *                   Can be packed ECDSA signature ({bytes32 r}{bytes32 s}{uint8 v}), contract signature (EIP-1271) or approved hash.\n     * @param requiredSignatures Amount of required valid signatures.\n     */\n    function checkNSignatures(bytes32 dataHash, bytes memory data, bytes memory signatures, uint256 requiredSignatures) public view {\n        // Check that the provided signature data is not too short\n        require(signatures.length >= requiredSignatures.mul(65), \"GS020\");\n        // There cannot be an owner with address 0.\n        address lastOwner = address(0);\n        address currentOwner;\n        uint8 v;\n        bytes32 r;\n        bytes32 s;\n        uint256 i;\n        for (i = 0; i < requiredSignatures; i++) {\n            (v, r, s) = signatureSplit(signatures, i);\n            if (v == 0) {\n                require(keccak256(data) == dataHash, \"GS027\");\n                // If v is 0 then it is a contract signature\n                // When handling contract signatures the address of the contract is encoded into r\n                currentOwner = address(uint160(uint256(r)));\n\n                // Check that signature data pointer (s) is not pointing inside the static part of the signatures bytes\n                // This check is not completely accurate, since it is possible that more signatures than the threshold are send.\n                // Here we only check that the pointer is not pointing inside the part that is being processed\n                require(uint256(s) >= requiredSignatures.mul(65), \"GS021\");\n\n                // Check that signature data pointer (s) is in bounds (points to the length of data -> 32 bytes)\n                require(uint256(s).add(32) <= signatures.length, \"GS022\");\n\n                // Check if the contract signature is in bounds: start of data is s + 32 and end is start + signature length\n                uint256 contractSignatureLen;\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    contractSignatureLen := mload(add(add(signatures, s), 0x20))\n                }\n                require(uint256(s).add(32).add(contractSignatureLen) <= signatures.length, \"GS023\");\n\n                // Check signature\n                bytes memory contractSignature;\n                // solhint-disable-next-line no-inline-assembly\n                assembly {\n                    // The signature data for contract signatures is appended to the concatenated signatures and the offset is stored in s\n                    contractSignature := add(add(signatures, s), 0x20)\n                }\n                require(ISignatureValidator(currentOwner).isValidSignature(data, contractSignature) == EIP1271_MAGIC_VALUE, \"GS024\");\n            } else if (v == 1) {\n                // If v is 1 then it is an approved hash\n                // When handling approved hashes the address of the approver is encoded into r\n                currentOwner = address(uint160(uint256(r)));\n                // Hashes are automatically approved by the sender of the message or when they have been pre-approved via a separate transaction\n                require(msg.sender == currentOwner || approvedHashes[currentOwner][dataHash] != 0, \"GS025\");\n            } else if (v > 30) {\n                // If v > 30 then default va (27,28) has been adjusted for eth_sign flow\n                // To support eth_sign and similar we adjust v and hash the messageHash with the Ethereum message prefix before applying ecrecover\n                currentOwner = ecrecover(keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n32\", dataHash)), v - 4, r, s);\n            } else {\n                // Default is the ecrecover flow with the provided data hash\n                // Use ecrecover with the messageHash for EOA signatures\n                currentOwner = ecrecover(dataHash, v, r, s);\n            }\n            require(currentOwner > lastOwner && owners[currentOwner] != address(0) && currentOwner != SENTINEL_OWNERS, \"GS026\");\n            lastOwner = currentOwner;\n        }\n    }\n\n    /**\n     * @notice Marks hash `hashToApprove` as approved.\n     * @dev This can be used with a pre-approved hash transaction signature.\n     *      IMPORTANT: The approved hash stays approved forever. There's no revocation mechanism, so it behaves similarly to ECDSA signatures\n     * @param hashToApprove The hash to mark as approved for signatures that are verified by this contract.\n     */\n    function approveHash(bytes32 hashToApprove) external {\n        require(owners[msg.sender] != address(0), \"GS030\");\n        approvedHashes[msg.sender][hashToApprove] = 1;\n        emit ApproveHash(hashToApprove, msg.sender);\n    }\n\n    /**\n     * @notice Returns the ID of the chain the contract is currently deployed on.\n     * @return The ID of the current chain as a uint256.\n     */\n    function getChainId() public view returns (uint256) {\n        uint256 id;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            id := chainid()\n        }\n        return id;\n    }\n\n    /**\n     * @dev Returns the domain separator for this contract, as defined in the EIP-712 standard.\n     * @return bytes32 The domain separator hash.\n     */\n    function domainSeparator() public view returns (bytes32) {\n        return keccak256(abi.encode(DOMAIN_SEPARATOR_TYPEHASH, getChainId(), this));\n    }\n\n    /**\n     * @notice Returns the pre-image of the transaction hash (see getTransactionHash).\n     * @param to Destination address.\n     * @param value Ether value.\n     * @param data Data payload.\n     * @param operation Operation type.\n     * @param safeTxGas Gas that should be used for the safe transaction.\n     * @param baseGas Gas costs for that are independent of the transaction execution(e.g. base transaction fee, signature check, payment of the refund)\n     * @param gasPrice Maximum gas price that should be used for this transaction.\n     * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n     * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n     * @param _nonce Transaction nonce.\n     * @return Transaction hash bytes.\n     */\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    ) public view returns (bytes memory) {\n        bytes32 safeTxHash = keccak256(\n            abi.encode(\n                SAFE_TX_TYPEHASH,\n                to,\n                value,\n                keccak256(data),\n                operation,\n                safeTxGas,\n                baseGas,\n                gasPrice,\n                gasToken,\n                refundReceiver,\n                _nonce\n            )\n        );\n        return abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator(), safeTxHash);\n    }\n\n    /**\n     * @notice Returns transaction hash to be signed by owners.\n     * @param to Destination address.\n     * @param value Ether value.\n     * @param data Data payload.\n     * @param operation Operation type.\n     * @param safeTxGas Fas that should be used for the safe transaction.\n     * @param baseGas Gas costs for data used to trigger the safe transaction.\n     * @param gasPrice Maximum gas price that should be used for this transaction.\n     * @param gasToken Token address (or 0 if ETH) that is used for the payment.\n     * @param refundReceiver Address of receiver of gas payment (or 0 if tx.origin).\n     * @param _nonce Transaction nonce.\n     * @return Transaction hash.\n     */\n    function getTransactionHash(\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    ) public view returns (bytes32) {\n        return keccak256(encodeTransactionData(to, value, data, operation, safeTxGas, baseGas, gasPrice, gasToken, refundReceiver, _nonce));\n    }\n}\n"
      },
      "contracts/BitcoinSafeOwner.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.25;\n\nimport {ERC1271} from \"./ERC1271.sol\";\nimport {LegacyERC1271} from \"./LegacyERC1271.sol\";\nimport {EmergencyGovernance} from \"./EmergencyGovernance.sol\";\n\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\n\n/// @title BitcoinSafeOwner\n/// @notice A contract to validate Bitcoin transaction signatures against an\n///         Ethereum address derived from a Bitcoin public key.\n/// @dev This contract implements ERC1271 and LegacyERC1271 to validate signatures\n///      for Bitcoin messages, accommodating both current and legacy versions of\n///      Safe contracts.\ncontract BitcoinSafeOwner is ERC1271, LegacyERC1271 {\n    // Singleton always has to be the first declared variable to ensure the same\n    // location as in the Proxy contract. It should also always be ensured the\n    // address is stored alone (uses a full word). We add a one word gap to be\n    // absolutely sure about it, no matter what fields will come next.\n    // slither-disable-start constable-states\n    // slither-disable-start unused-state\n    address internal singleton;\n    bytes32 internal __gap;\n    // slither-disable-end constable-states\n    // slither-disable-end unused-state\n\n    /// @notice Version of the contract.\n    /// @dev Must be increased for each new contract version to ensure off-chain\n    ///      upgrade signatures can be used only one time.\n    string public version;\n\n    /// @notice Represents the main part of a decoded Bitcoin address, excluding\n    ///         the network byte and checksum.\n    /// @dev It captures the RIPEMD-160 hash of the SHA-256 hash of the public\n    ///      key or redeem script hash, which is derived from a Bitcoin address\n    ///      after removing its network byte and checksum.\n    ///      This value is used for Bitcoin message signatures validation from\n    ///      the Bitcoin account associated with this contract.\n    bytes20 public truncatedBitcoinAddress;\n\n    /// @notice Indicates if the setup function was already called for the contract.\n    // slither-disable-next-line immutable-states\n    bool public initialized;\n\n    /// @notice Reference to the emergency governance contract holding the\n    ///         emergency upgrader address that can execute upgrades of the\n    ///         singleton address if the emergency upgrades were not disabled.\n    EmergencyGovernance public emergencyGovernance;\n\n    /// @notice Magic value for an invalid signature, indicating a failed validation.\n    bytes4 internal constant INVALID_SIGNATURE_VALUE = 0xffffffff;\n\n    /// @notice Typehash of a message signed off-chain to upgrade the singleton.\n    bytes32 public constant UPGRADE_SINGLETON_TYPEHASH =\n        keccak256(\"UpgradeSingleton(address newSingleton,bytes initData)\");\n\n    event SingletonUpgraded(address oldSingleton, address newSingleton);\n\n    /// Reverts when the contract was already initialized and another\n    /// initialization attempt is made.\n    error ContractAlreadyInitialized();\n\n    /// Reverts when truncated Bitcoin address is incorrect.\n    error InvalidTruncatedBitcoinAddress();\n\n    /// Reverts when emergency governance contract address is zero.\n    error EmergencyGovernanceAddressZero();\n\n    /// Reverts when provided signature is not 65-bytes long.\n    error InvalidSignatureLength(uint256 actualLength);\n\n    /// Reverts when the singleton was already upgraded to the given new version.\n    error SingletonAlreadyUpgraded();\n\n    /// Reverts when the new singleton address is incorrect.\n    error InvalidNewSingletonAddress();\n\n    /// Reverts when the upgrade order signature was incorrect.\n    error InvalidUpgradeSignature();\n\n    /// Reverts if the new version init data provided in the upgrade order\n    /// are empty.\n    error InvalidUpgradeInitData();\n\n    /// Reverts when the address calling the function is not the authorized\n    /// emergency governance upgrader.\n    error InvalidEmergencyGovernanceCaller();\n\n    constructor() {\n        // Prevent singleton contract initialization.\n        initialized = true;\n    }\n\n    /// @notice Initializes the BitcoinSafeOwner contract with the Ethereum\n    ///         address derived from a Bitcoin public key and the address\n    ///         of the contract holding the emergency governance settings.\n    function setup(\n        bytes20 _truncatedBitcoinAddress,\n        address _emergencyGovernance\n    ) external {\n        if (initialized) {\n            revert ContractAlreadyInitialized();\n        }\n\n        if (_truncatedBitcoinAddress == bytes20(0)) {\n            revert InvalidTruncatedBitcoinAddress();\n        }\n\n        if (_emergencyGovernance == address(0)) {\n            revert EmergencyGovernanceAddressZero();\n        }\n\n        initialized = true;\n        emergencyGovernance = EmergencyGovernance(_emergencyGovernance);\n        truncatedBitcoinAddress = _truncatedBitcoinAddress;\n\n        // IMPORTANT: The contract version is a part of the DOMAIN_SEPARATOR.\n        // The new singleton implementation MUST increase the version number\n        // to protect against replaying signatures.\n        version = \"v1.0.0\";\n    }\n\n    /// @notice Returns the hash of EIP712 domain separator struct. Used to\n    ///         verify off-chain signatures to this contract, such as the\n    ///         signature for upgrading the singleton.\n    function DOMAIN_SEPARATOR() public view returns (bytes32) {\n        return\n            keccak256(\n                abi.encode(\n                    keccak256(\n                        \"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"\n                    ),\n                    keccak256(bytes(\"BitcoinSafeOwner\")),\n                    keccak256(bytes(version)),\n                    block.chainid,\n                    address(this)\n                )\n            );\n    }\n\n    /// @notice Upgrades the singleton address based on the signature of the\n    ///         upgrade order prepared off-chain.\n    /// @dev IMPORTANT: The contract version is a part of the DOMAIN_SEPARATOR.\n    ///      The new singleton implementation MUST increase the version number\n    ///      to protect against replaying signatures.\n    /// @param newSingleton The new singleton contract address.\n    /// @param initData Encoded call to the setup function that will be called\n    ///        on the proxy after switching the singleton.\n    /// @param signature The signature from the Bitcoin signer attesting the\n    ///        upgrade order.\n    function upgradeSingleton(\n        address newSingleton,\n        bytes memory initData,\n        bytes memory signature\n    ) external {\n        if (newSingleton == address(0) || newSingleton == address(this)) {\n            revert InvalidNewSingletonAddress();\n        }\n        if (singleton == newSingleton) {\n            revert SingletonAlreadyUpgraded();\n        }\n\n        bytes32 digest = keccak256(\n            abi.encodePacked(\n                \"\\x19\\x01\",\n                DOMAIN_SEPARATOR(),\n                keccak256(\n                    abi.encode(\n                        UPGRADE_SINGLETON_TYPEHASH,\n                        newSingleton,\n                        initData\n                    )\n                )\n            )\n        );\n\n        if (!validateSignature(digest, signature)) {\n            revert InvalidUpgradeSignature();\n        }\n\n        emit SingletonUpgraded(singleton, newSingleton);\n\n        singleton = newSingleton;\n\n        if (initData.length == 0) {\n            revert InvalidUpgradeInitData();\n        }\n        // The init function should return no data.\n        // slither-disable-next-line unused-return\n        Address.functionCall(address(this), initData);\n    }\n\n    /// @notice Upgrades the singleton address in an emergency mode.\n    /// @dev Only callable by the governance upgrader set in the\n    ///      EmergencyGovernance contract.\n    /// @param newSingleton The new singleton contract address.\n    /// @param initData Encoded call to the setup function that will be called\n    ///        on the proxy after switching the singleton.\n    function emergencyUpgradeSingleton(\n        address newSingleton,\n        bytes memory initData\n    ) external {\n        if (newSingleton == address(0) || newSingleton == address(this)) {\n            revert InvalidNewSingletonAddress();\n        }\n        if (singleton == newSingleton) {\n            revert SingletonAlreadyUpgraded();\n        }\n\n        if (msg.sender != emergencyGovernance.emergencyUpgrader()) {\n            revert InvalidEmergencyGovernanceCaller();\n        }\n\n        emit SingletonUpgraded(singleton, newSingleton);\n\n        singleton = newSingleton;\n\n        if (initData.length == 0) {\n            revert InvalidUpgradeInitData();\n        }\n        // The init function should return no data.\n        // slither-disable-next-line unused-return\n        Address.functionCall(address(this), initData);\n    }\n\n    /// @notice Validates a signature against a hash digest, adhering to the latest\n    ///         ERC-1271 standard.\n    /// @param digest The hash of the data that was signed.\n    /// @param signature The signature bytes to be validated.\n    /// @return magicValue A magic value indicating the result of the validation.\n    /// @dev This method is intended to comply with the most recent version of\n    ///      Safe contracts.\n    function isValidSignature(\n        bytes32 digest,\n        bytes memory signature\n    ) external view returns (bytes4 magicValue) {\n        return\n            validateSignature(digest, signature)\n                ? ERC1271_MAGIC_VALUE\n                : INVALID_SIGNATURE_VALUE;\n    }\n\n    /// @notice Validates a signature against data bytes, following the legacy\n    ///         Safe contract expectations.\n    /// @param data Arbitrary length data that was signed.\n    /// @param signature The signature bytes to be validated.\n    /// @return magicValue A magic value indicating the result of the validation.\n    /// @dev This method is compatible with Safe contracts up to version 1.4.1.\n    function isValidSignature(\n        bytes memory data,\n        bytes memory signature\n    ) public view override returns (bytes4 magicValue) {\n        bytes32 digest = keccak256(data);\n\n        return\n            validateSignature(digest, signature)\n                ? LEGACY_SAFE_ERC1271_MAGIC_VALUE\n                : INVALID_SIGNATURE_VALUE;\n    }\n\n    /// @notice Internal function to validate a signature against a digest.\n    /// @dev By adjusting the recovery byte (`v`) it supports various types of\n    ///      Bitcoin truncated addresses that this contract could be initialized\n    ///      with, including uncompressed P2PKH, compressed P2PKH, compressed\n    ///      P2WPKH, and compressed P2SH-P2WPKH.\n    ///      The function returns `true` if the signature is successfully verified\n    ///      against the `digest` and the `truncatedBitcoinAddress` stored in the\n    ///      contract.\n    /// @param digest The hash of the data that was signed.\n    /// @param signature The signature bytes to be validated, which must be 129\n    ///        bytes long and include the `v`, `r`, `s` values of the\n    ///        ECDSA signature, and the `x`, `y` coordinates of the public key\n    ///        used for signing. The `v` value should be adjusted to indicate\n    ///        which signature validation function should be executed for the given\n    ///        truncated Bitcoin address type.\n    /// @return A boolean indicating whether the signature is valid.\n    function validateSignature(\n        bytes32 digest,\n        bytes memory signature\n    ) internal view returns (bool) {\n        if (truncatedBitcoinAddress == bytes20(0))\n            revert InvalidTruncatedBitcoinAddress();\n\n        if (signature.length != 129)\n            revert InvalidSignatureLength(signature.length);\n\n        uint8 v;\n        bytes32 r;\n        bytes32 s;\n        bytes32 x;\n        bytes32 y;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            // first 32 bytes, after the length prefix.\n            r := mload(add(signature, 32))\n            // second 32 bytes.\n            s := mload(add(signature, 64))\n            // 65th byte (first byte of the next 32 bytes).\n            v := byte(0, mload(add(signature, 96)))\n            // next 32 bytes starting from 65\n            x := mload(add(signature, 97))\n            // last 32 bytes\n            y := mload(add(signature, 129))\n        }\n\n        bytes32 signedMessage = sha256(\n            abi.encodePacked(\n                sha256(\n                    abi.encodePacked(\n                        \"\\x18Bitcoin Signed Message:\\n\",\n                        uint8(32),\n                        digest\n                    )\n                )\n            )\n        );\n\n        // The v value must be 27 or 28 for ECRECOVER to accept the signatures.\n        // In the case of uncompressed P2PKH addresses this is achieved as long\n        // as the signature's r value is less than the curve order n.\n        // When the v value is used to encode a different signature type,\n        // we need to subtract the difference to get 27 or 28.\n        // Signatures with r greater than n, corresponding to the v values\n        // 29, 30, 33, 34, 37, 38, 41 or 42 cannot be accepted by ECRECOVER.\n        // Signature's V value is used to determine signature verification path\n        // according to BIP-137.\n        if (v == 27 || v == 28) {\n            // v is either 27 or 28, so pass it straight to ECRECOVER\n            return validateUncompressedP2PKH(signedMessage, v, r, s, x, y);\n        } else if (v == 31 || v == 32) {\n            // v is either 31 or 32, so subtract 4 to get 27 or 28\n            return validateCompressedP2PKH(signedMessage, v - 4, r, s, x, y);\n        } else if (v == 35 || v == 36) {\n            // v is either 35 or 36, so subtract 8 to get 27 or 28\n            return validateP2SH_P2WPKH(signedMessage, v - 8, r, s, x, y);\n        } else if (v == 39 || v == 40) {\n            // v is either 39 or 40, so subtract 12 to get 27 or 28\n            return validateP2WPKH(signedMessage, v - 12, r, s, x, y);\n        } else {\n            return false;\n        }\n    }\n\n    /// @notice Validates a signature for truncated Bitcoin address derived from\n    ///         a P2PKH address of an uncompressed public key.\n    /// @param signedMessage The SHA-256 hash of the message that was signed,\n    ///        prefixed according to the Bitcoin signed message standard.\n    /// @param v The recovery byte.\n    /// @param r The first component of the ECDSA signature.\n    /// @param s The second component of the ECDSA signature.\n    /// @param x The x-coordinate of the public key.\n    /// @param y The y-coordinate of the public key.\n    /// @return A boolean indicating whether the signature is valid.\n    function validateUncompressedP2PKH(\n        bytes32 signedMessage,\n        uint8 v,\n        bytes32 r,\n        bytes32 s,\n        bytes32 x,\n        bytes32 y\n    ) internal view returns (bool) {\n        uint8 prefix = uint8(4);\n        bytes20 publicKeyHash = hash160(abi.encodePacked(prefix, x, y));\n\n        return\n            ecrecover(signedMessage, v, r, s) ==\n            publicKeyToEthereumAddress(x, y) &&\n            truncatedBitcoinAddress == publicKeyHash;\n    }\n\n    /// @notice Validates a signature for truncated Bitcoin address derived from\n    ///         a P2PKH address of a compressed public key.\n    /// @param signedMessage The SHA-256 hash of the message that was signed,\n    ///        prefixed according to the Bitcoin signed message standard.\n    /// @param v The recovery byte.\n    /// @param r The first component of the ECDSA signature.\n    /// @param s The second component of the ECDSA signature.\n    /// @param x The x-coordinate of the public key.\n    /// @param y The y-coordinate of the public key.\n    /// @return A boolean indicating whether the signature is valid.\n    function validateCompressedP2PKH(\n        bytes32 signedMessage,\n        uint8 v,\n        bytes32 r,\n        bytes32 s,\n        bytes32 x,\n        bytes32 y\n    ) internal view returns (bool) {\n        uint8 prefix = uint8(uint256(y) & 1) + uint8(2);\n        bytes20 publicKeyHash = hash160(abi.encodePacked(prefix, x));\n\n        return\n            ecrecover(signedMessage, v, r, s) ==\n            publicKeyToEthereumAddress(x, y) &&\n            truncatedBitcoinAddress == publicKeyHash;\n    }\n\n    /// @notice Validates a signature for truncated Bitcoin address derived from\n    ///         a P2SH-P2WPKH address of a compressed public key.\n    /// @param signedMessage The SHA-256 hash of the message that was signed,\n    ///        prefixed according to the Bitcoin signed message standard.\n    /// @param v The recovery byte.\n    /// @param r The first component of the ECDSA signature.\n    /// @param s The second component of the ECDSA signature.\n    /// @param x The x-coordinate of the public key.\n    /// @param y The y-coordinate of the public key.\n    /// @return A boolean indicating whether the signature is valid.\n    function validateP2SH_P2WPKH(\n        bytes32 signedMessage,\n        uint8 v,\n        bytes32 r,\n        bytes32 s,\n        bytes32 x,\n        bytes32 y\n    ) internal view returns (bool) {\n        uint8 prefix = uint8(uint256(y) & 1) + uint8(2);\n        bytes20 publicKeyHash = hash160(abi.encodePacked(prefix, x));\n\n        bytes20 redeemScriptHash = hash160(\n            abi.encodePacked(bytes2(hex\"0014\"), publicKeyHash)\n        );\n\n        return\n            ecrecover(signedMessage, v, r, s) ==\n            publicKeyToEthereumAddress(x, y) &&\n            truncatedBitcoinAddress == redeemScriptHash;\n    }\n\n    /// @notice Validates a signature for truncated Bitcoin address derived from\n    ///         a PW2PKH address of a compressed public key.\n    /// @param signedMessage The SHA-256 hash of the message that was signed,\n    ///        prefixed according to the Bitcoin signed message standard.\n    /// @param v The recovery byte.\n    /// @param r The first component of the ECDSA signature.\n    /// @param s The second component of the ECDSA signature.\n    /// @param x The x-coordinate of the public key.\n    /// @param y The y-coordinate of the public key.\n    /// @return A boolean indicating whether the signature is valid.\n    function validateP2WPKH(\n        bytes32 signedMessage,\n        uint8 v,\n        bytes32 r,\n        bytes32 s,\n        bytes32 x,\n        bytes32 y\n    ) internal view returns (bool) {\n        uint8 prefix = uint8(uint256(y) & 1) + uint8(2);\n        bytes20 publicKeyHash = hash160(abi.encodePacked(prefix, x));\n\n        return\n            ecrecover(signedMessage, v, r, s) ==\n            publicKeyToEthereumAddress(x, y) &&\n            truncatedBitcoinAddress == publicKeyHash;\n    }\n\n    /// @notice Converts a public key (x, y coordinates) to an Ethereum address\n    /// @dev Computes the Ethereum address by performing a keccak256 hash on the\n    ///      concatenated x and y coordinates of the public key, then taking the\n    ///      last 20 bytes of the hash (as per Ethereum's address format).\n    /// @param x The x-coordinate of the public key.\n    /// @param y The y-coordinate of the public key.\n    /// @return The Ethereum address derived from the public key.\n    function publicKeyToEthereumAddress(\n        bytes32 x,\n        bytes32 y\n    ) internal pure returns (address) {\n        return address(uint160(uint256(keccak256(abi.encodePacked(x, y)))));\n    }\n\n    /// @notice Calculate hash160 for the given input bytes.\n    /// @dev This function combines SHA-256 and RIPEMD-160 hashing to produce a\n    ///      hash commonly used in Bitcoin addressing.\n    /// @param input The bytes array to be hashed.\n    /// @return The hash160 (RIPEMD-160 of a SHA-256 hash) of the input.\n    function hash160(bytes memory input) internal pure returns (bytes20) {\n        return ripemd160(abi.encodePacked(sha256(input)));\n    }\n}\n"
      },
      "contracts/EmergencyGovernance.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.25;\n\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\n/// @title Emergency Governance\n/// @notice This contract holds the emergency upgrader address responsible for\n///         executing emergency governance actions in case of unforeseen\n///         circumstances. Only the contract owner can set or change the\n///         emergency upgrader address. This contract will STOP working after\n///         the governance decides to disable emergency upgrades.\ncontract EmergencyGovernance is Ownable2Step {\n    bool public disabled;\n    address internal _emergencyUpgrader;\n\n    event Disabled();\n\n    /// @notice Event fired when the emergency upgrader address is changed.\n    event EmergencyUpgraderChanged(\n        address oldEmergencyUpgrader,\n        address newEmergencyUpgrader\n    );\n\n    /// @notice Error thrown when an invalid emergency upgrader address is\n    ///         provided.\n    error InvalidEmergencyUpgraderAddress(address addr);\n\n    error EmergencyUpgradesDisabled();\n\n    constructor(\n        address emergencyUpgraderAddress\n    ) Ownable(emergencyUpgraderAddress) {\n        _setEmergencyUpgrader(emergencyUpgraderAddress);\n    }\n\n    modifier whenEnabled() {\n        if (disabled) {\n            revert EmergencyUpgradesDisabled();\n        }\n        _;\n    }\n\n    /// @notice Returns the emergency upgrader address.\n    function emergencyUpgrader() external view whenEnabled returns (address) {\n        return _emergencyUpgrader;\n    }\n\n    function disable() external onlyOwner whenEnabled {\n        emit Disabled();\n        disabled = true;\n    }\n\n    /// @notice Sets the emergency upgrader address.\n    /// @dev Only callable by the contract owner.\n    /// @param newEmergencyUpgrader The address of the new emergency upgrader.\n    function setEmergencyUpgrader(\n        address newEmergencyUpgrader\n    ) external onlyOwner whenEnabled {\n        _setEmergencyUpgrader(newEmergencyUpgrader);\n    }\n\n    function _setEmergencyUpgrader(address newEmergencyUpgrader) internal {\n        if (newEmergencyUpgrader == address(0)) {\n            revert InvalidEmergencyUpgraderAddress(newEmergencyUpgrader);\n        }\n\n        emit EmergencyUpgraderChanged(_emergencyUpgrader, newEmergencyUpgrader);\n        _emergencyUpgrader = newEmergencyUpgrader;\n    }\n}\n"
      },
      "contracts/ERC1271.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.25;\n\n/// @title ERC-1271 Signature Validation Standard Interface\n/// @dev Interface of the ERC-1271 standard for signature validation by contracts.\n///      This standard allows contracts to implement a function to validate signatures\n///      in a generic way, facilitating interactions with external contracts that\n///      expect a contract to sign messages or transactions.\n///      The standard is defined in EIP-1271, which can be found at https://eips.ethereum.org/EIPS/eip-1271.\ninterface IERC1271 {\n    /// @notice Validates a signature for a given data hash.\n    /// @dev This method returns a magic value if the signature is valid for the\n    ///      provided data hash and signature.\n    ///      Contracts implementing this interface can use this function to provide\n    ///      custom signature validation logic.\n    /// @param hash The hash of the data that was signed.\n    /// @param signature The signature bytes that need to be validated against the\n    ///        data hash.\n    /// @return magicValue A constant magic value (`0x1626ba7e`) if the signature\n    ///         is valid, indicating compliance with the ERC-1271 standard.\n    function isValidSignature(\n        bytes32 hash,\n        bytes memory signature\n    ) external view returns (bytes4 magicValue);\n}\n\n/// @title ERC-1271 Signature Validation Standard Abstract Contract\n/// @dev Provides a basic implementation of the ERC-1271 standard, including the\n///      magic value constant.\n///      This abstract contract can be extended to create custom implementations\n///      of the ERC-1271 standard, defining the specific logic required to validate\n///      signatures in the context of the extending contract.\nabstract contract ERC1271 is IERC1271 {\n    /// @notice The magic value to be returned by `isValidSignature` when the\n    ///         signature is valid.\n    /// @dev This constant represents `bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")`.\n    ///      It is used to indicate that a signature is valid according to the\n    ///      ERC-1271 standard.\n    bytes4 internal constant ERC1271_MAGIC_VALUE = 0x1626ba7e;\n}\n"
      },
      "contracts/LegacyERC1271.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.25;\n\n// This file contains Legacy ERC-1271 signatures validator that assumes `isValidSignature`\n// function to require data bytes, which is incompatible with the standard which\n// expects bytes32 hash digest.\n// This validator is used by Safe contract up to version v1.4.1.\n//\n// The abstract contract was build with the ISignatureValidator taken from\n// Safe's v1.4.1-build.0:\n// https://github.com/safe-global/safe-smart-account/blob/192c7dc67290940fcbc75165522bb86a37187069/contracts/interfaces/ISignatureValidator.sol\n\n/// @title LegacyERC1271\n/// @notice Abstract contract for legacy Safe signature validation.\n/// @dev This contract implements Safe's v1.4.1 `ISignatureValidator` without\n///      adding additional functionality, serving as a base for specific legacy\n///      Safe-compatible signature validation implementations.\nabstract contract LegacyERC1271 {\n    // bytes4(keccak256(\"isValidSignature(bytes,bytes)\")\n    bytes4 internal constant LEGACY_SAFE_ERC1271_MAGIC_VALUE = 0x20c13b0b;\n\n    /**\n     * @notice Legacy EIP1271 method to validate a signature.\n     * @param _data Arbitrary length data signed on the behalf of address(this).\n     * @param _signature Signature byte array associated with _data.\n     *\n     * MUST return the bytes4 magic value 0x20c13b0b when function passes.\n     * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)\n     * MUST allow external calls\n     */\n    function isValidSignature(\n        bytes memory _data,\n        bytes memory _signature\n    ) public view virtual returns (bytes4);\n}\n"
      },
      "contracts/OrangeKitSafeFactory.sol": {
        "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity 0.8.25;\n\nimport \"@safe-global/safe-contracts/contracts/proxies/SafeProxy.sol\";\nimport \"@safe-global/safe-contracts/contracts/Safe.sol\";\nimport \"./Proxy.sol\";\nimport \"./BitcoinSafeOwner.sol\";\n\n/// @title OrangeKitSafeFactory\n/// @notice The OrangeKitSafeFactory is the central deployer of the OrangeKit\n///         responsible for deploying two contracts: a proxy for the Safe and\n///         a proxy for the BitcoinSafeOwner which will be the owner of the\n///         Safe. Proxies are deployed using CREATE2 and the addresses of the\n///         contracts can be deterministically obtained based on the Ethereum\n///         address derived from the public key used for signing.\n///         The BitcoinSafeOwner is ERC-1271 compatible contract capable of\n///         validating Bitcoin signatures.\ncontract OrangeKitSafeFactory {\n    // Singleton always has to be the first declared variable to ensure the same\n    // location as in the Proxy contract. It should also always be ensured the\n    // address is stored alone (uses a full word). We add a one word gap to be\n    // absolutely sure about it, no matter what fields will come next.\n    // slither-disable-start constable-states\n    // slither-disable-start unused-state\n    address internal singleton;\n    bytes32 internal __gap;\n    // slither-disable-end constable-states\n    // slither-disable-end unused-state\n\n    address public safeSingleton;\n    address public safeOwnerSingleton;\n\n    address public emergencyGovernance;\n\n    address public owner;\n\n    bool public initialized;\n\n    event SingletonUpgraded(address oldSingleton, address newSingleton);\n    event OwnershipTransferred(address previousOwner, address newOwner);\n    event SafeDeployed(\n        address indexed safe,\n        address indexed bitcoinSafeOwner,\n        bytes20 indexed truncatedBitcoinAddress\n    );\n\n    error InvalidSingletonAddress(address singleton);\n    error InvalidEmergencyGovernanceAddress(address addr);\n    error InvalidTruncatedBitcoinAddress();\n    error AlreadyInitialized();\n    error NotAuthorized();\n    error SingletonAlreadyUpgraded();\n    error InvalidNewSingletonAddress();\n    error InvalidUpgradeInitData();\n    error InvalidNewOwnerAddress();\n\n    modifier onlyOwner() {\n        if (msg.sender != owner) {\n            revert NotAuthorized();\n        }\n        _;\n    }\n\n    constructor() {\n        // Prevent singleton contract initialization.\n        initialized = true;\n    }\n\n    /// @notice Initializes the contract.\n    function initialize(\n        address _safeSingleton,\n        address _safeOwnerSingleton,\n        address _emergencyGovernance\n    ) external {\n        if (initialized) {\n            revert AlreadyInitialized();\n        }\n\n        initialized = true;\n        if (!isContract(_safeSingleton)) {\n            revert InvalidSingletonAddress(_safeSingleton);\n        }\n        if (!isContract(_safeOwnerSingleton)) {\n            revert InvalidSingletonAddress(_safeOwnerSingleton);\n        }\n        if (!isContract(_emergencyGovernance)) {\n            revert InvalidEmergencyGovernanceAddress(_emergencyGovernance);\n        }\n\n        owner = msg.sender;\n        safeSingleton = _safeSingleton;\n        safeOwnerSingleton = _safeOwnerSingleton;\n        emergencyGovernance = _emergencyGovernance;\n    }\n\n    /// @dev Allows to retrieve the creation code used for the SafeProxy\n    ///      deployment. With this it is easily possible to calculate predicted\n    ///      address.\n    function safeProxyCreationCode() public pure returns (bytes memory) {\n        return type(SafeProxy).creationCode;\n    }\n\n    /// @dev Allows to retrieve the creation code used for the BitcoinSafeOwner\n    ///      proxy deployment. With this it is easily possible to calculate\n    ///      predicted address.\n    function bitcoinSafeOwnerProxyCreationCode()\n        public\n        pure\n        returns (bytes memory)\n    {\n        return type(Proxy).creationCode;\n    }\n\n    /// @notice Deploys two proxy contracts: Safe proxy and BitcoinSafeOwner\n    ///         proxy being a single owner of the deployed Safe. The proxies use\n    ///         an implementation code of the two singletons the deployer is\n    ///         pointing to. The address of both proxies can be obtained\n    ///         deterministically based on the Ethereum address derived from the\n    ///         public key used for signing.\n    /// @param truncatedBitcoinAddress The main part of a decoded Bitcoin address\n    ///        used for BitcoinSafeOwner initialization.\n    function deploySafe(\n        bytes20 truncatedBitcoinAddress\n    ) external returns (SafeProxy safe, Proxy bitcoinSafeOwner) {\n        if (truncatedBitcoinAddress == bytes20(0)) {\n            revert InvalidTruncatedBitcoinAddress();\n        }\n\n        bytes32 salt = keccak256(abi.encodePacked(truncatedBitcoinAddress));\n\n        bitcoinSafeOwner = deployBitcoinSafeOwnerProxy(\n            truncatedBitcoinAddress,\n            salt\n        );\n        safe = deploySafeProxy(address(bitcoinSafeOwner), salt);\n\n        emit SafeDeployed(\n            address(safe),\n            address(bitcoinSafeOwner),\n            truncatedBitcoinAddress\n        );\n    }\n\n    /// @notice Predicts the addresses of the Safe proxy and the BitcoinSafeOwner\n    ///         proxy before deployment.\n    /// @dev This function calculates the addresses based on the CREATE2 opcode,\n    ///      allowing the determination of the addresses before actual deployment.\n    /// @param truncatedBitcoinAddress The main part of a decoded Bitcoin address\n    ///        used for BitcoinSafeOwner initialization.\n    /// @return safe The predicted address of the Safe proxy.\n    /// @return bitcoinSafeOwner The predicted address of the BitcoinSafeOwner\n    ///         proxy.\n    function predictAddresses(\n        bytes20 truncatedBitcoinAddress\n    ) external view returns (address safe, address bitcoinSafeOwner) {\n        bytes32 salt = keccak256(abi.encodePacked(truncatedBitcoinAddress));\n\n        safe = predictSafeAddress(salt);\n        bitcoinSafeOwner = predictBitcoinSafeOwnerAddress(salt);\n    }\n\n    /// @notice Upgrades the singleton address.\n    /// @dev Only callable by the owner.\n    /// @param newSingleton The new singleton contract address.\n    /// @param initData Encoded call to the setup function that will be called\n    ///        on the proxy after switching the singleton.\n    function upgradeSingleton(\n        address newSingleton,\n        bytes memory initData\n    ) external onlyOwner {\n        if (newSingleton == address(0) || newSingleton == address(this)) {\n            revert InvalidNewSingletonAddress();\n        }\n        if (singleton == newSingleton) {\n            revert SingletonAlreadyUpgraded();\n        }\n\n        emit SingletonUpgraded(singleton, newSingleton);\n\n        singleton = newSingleton;\n\n        if (initData.length == 0) {\n            revert InvalidUpgradeInitData();\n        }\n        // The init function should return no data.\n        // slither-disable-next-line unused-return\n        Address.functionCall(address(this), initData);\n    }\n\n    /// @notice Transfers ownership of the contract to a new address.\n    /// @dev Can only be called by the current owner.\n    function transferOwnership(address newOwner) external onlyOwner {\n        if (newOwner == address(0)) {\n            revert InvalidNewOwnerAddress();\n        }\n\n        emit OwnershipTransferred(owner, newOwner);\n        owner = newOwner;\n    }\n\n    /// @notice Deploys the Safe proxy for the given salt and previously\n    ///         deployed BitcoinSafeOwner proxy. The BitcoinSafeOwner proxy is\n    ///         the sole owner of the deployed Safe. The deployed safe is a\n    ///         vanilla safe with no additional modules.\n    /// @param ownerProxy Instance of a BitcoinSafeOwner proxy contract that\n    ///        is supposed to own the safe.\n    /// @param salt The salt determining the deployed proxy address.\n    function deploySafeProxy(\n        address ownerProxy,\n        bytes32 salt\n    ) internal returns (SafeProxy proxy) {\n        bytes memory deploymentData = abi.encodePacked(\n            type(SafeProxy).creationCode,\n            uint256(uint160(safeSingleton))\n        );\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            proxy := create2(\n                0x0,\n                add(0x20, deploymentData),\n                mload(deploymentData),\n                salt\n            )\n        }\n        require(address(proxy) != address(0), \"Safe Proxy Create2 call failed\");\n\n        address[] memory owners = new address[](1);\n        owners[0] = address(ownerProxy);\n\n        bytes memory initializer = abi.encodeCall(\n            Safe.setup,\n            (\n                owners, // owners\n                1, // threshold\n                address(0), // to\n                hex\"\", // data\n                address(0), // fallbackHandler\n                address(0), // paymentToken\n                0, // payment\n                payable(0) // paymentReceiver\n            )\n        );\n\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            if eq(\n                call(\n                    gas(),\n                    proxy,\n                    0,\n                    add(initializer, 0x20),\n                    mload(initializer),\n                    0,\n                    0\n                ),\n                0\n            ) {\n                revert(0, 0)\n            }\n        }\n    }\n\n    /// @notice Deploys the BitcoinSafeOwner proxy for the given salt and\n    ///         Bitcoin owner Ethereum address.\n    /// @dev The code was borrowed from SafeProxyFactory.deployProxy at version\n    ///      1.4.1-build.0 with small modifications.\n    /// @param truncatedBitcoinAddress The main part of a decoded Bitcoin address\n    ///        used for BitcoinSafeOwner initialization.\n    /// @param salt The salt determining the deployed proxy address.\n    function deployBitcoinSafeOwnerProxy(\n        bytes20 truncatedBitcoinAddress,\n        bytes32 salt\n    ) internal returns (Proxy proxy) {\n        bytes memory deploymentData = abi.encodePacked(\n            type(Proxy).creationCode,\n            uint256(uint160(safeOwnerSingleton))\n        );\n\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            proxy := create2(\n                0x0,\n                add(0x20, deploymentData),\n                mload(deploymentData),\n                salt\n            )\n        }\n        require(\n            address(proxy) != address(0),\n            \"BitcoinSafeOwner Proxy Create2 call failed\"\n        );\n\n        bytes memory initializer = abi.encodeCall(\n            BitcoinSafeOwner.setup,\n            (truncatedBitcoinAddress, emergencyGovernance)\n        );\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            if eq(\n                call(\n                    gas(),\n                    proxy,\n                    0,\n                    add(initializer, 0x20),\n                    mload(initializer),\n                    0,\n                    0\n                ),\n                0\n            ) {\n                revert(0, 0)\n            }\n        }\n    }\n\n    /// @notice Predicts the address of the Safe proxy using the provided salt.\n    /// @dev Utilizes the keccak256 hash of the contract creation bytecode, combined\n    ///      with the salt, to compute the address using the CREATE2 rules.\n    /// @param salt The unique salt used for the Safe proxy deployment, derived\n    ///        from the `truncatedBitcoinAddress`.\n    /// @return The predicted address of the Safe proxy based on the provided salt.\n    function predictSafeAddress(bytes32 salt) internal view returns (address) {\n        bytes memory deploymentData = abi.encodePacked(\n            type(SafeProxy).creationCode,\n            uint256(uint160(safeSingleton))\n        );\n\n        return computeAddress(salt, keccak256(deploymentData));\n    }\n\n    /// @notice Predicts the address of the BitcoinSafeOwner proxy using the\n    ///         provided salt.\n    /// @dev Uses the keccak256 hash of the BitcoinSafeOwner proxy creation bytecode\n    ///      and the salt to calculate the CREATE2 deployment address.\n    /// @param salt The unique salt used for the BitcoinSafeOwner proxy deployment,\n    ///        derived from the `truncatedBitcoinAddress`.\n    /// @return The predicted address of the BitcoinSafeOwner proxy based on the\n    ///         provided salt.\n    function predictBitcoinSafeOwnerAddress(\n        bytes32 salt\n    ) internal view returns (address) {\n        bytes memory deploymentData = abi.encodePacked(\n            type(Proxy).creationCode,\n            uint256(uint160(safeOwnerSingleton))\n        );\n\n        return computeAddress(salt, keccak256(deploymentData));\n    }\n\n    /// @notice Computes the expected address for a contract deployed using `create2`.\n    /// @dev This function calculates the address where a contract will be deployed\n    ///      through the `create2` opcode, based on a provided `salt` and the hash\n    ///      of the contract's bytecode (`bytecodeHash`). Changes in either `salt`\n    ///      or `bytecodeHash` will lead to a different resultant address.\n    /// @param salt A bytes32 value used as a salt in the `create2`.\n    /// @param bytecodeHash The keccak256 hash of the contract's bytecode.\n    /// @return addr The computed address where a contract would be stored if\n    ///         deployed using `create2` with the specified `salt` and `bytecodeHash`.\n    function computeAddress(\n        bytes32 salt,\n        bytes32 bytecodeHash\n    ) internal view returns (address addr) {\n        address deployer = address(this);\n\n        // Implementation below is borrowed from the OpenZeppelin's Create2 contract.\n        // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/976a3d53624849ecaef1231019d2052a16a39ce4/contracts/utils/Create2.sol\n\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let ptr := mload(0x40) // Get free memory pointer\n\n            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |\n            // | salt              |                                      BBBBBBBBBBBBB...BB                   |\n            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |\n            // | 0xFF              |            FF                                                             |\n            // |-------------------|---------------------------------------------------------------------------|\n            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n            mstore(add(ptr, 0x40), bytecodeHash)\n            mstore(add(ptr, 0x20), salt)\n            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n            mstore8(start, 0xff)\n            addr := keccak256(start, 85)\n        }\n    }\n\n    /// @notice Returns true if `account` is a contract.\n    /// @dev This function will return false if invoked during the constructor of a contract,\n    ///      as the code is not actually created until after the constructor finishes.\n    /// @param account The address being queried\n    /// @return True if `account` is a contract\n    function isContract(address account) internal view returns (bool) {\n        // Implementation below is borrowed from the Safe Global's SafeProfyFactory contract.\n        // Source: https://github.com/safe-global/safe-smart-account/blob/192c7dc67290940fcbc75165522bb86a37187069/contracts/proxies/SafeProxyFactory.sol#L104\n\n        uint256 size;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            size := extcodesize(account)\n        }\n        return size > 0;\n    }\n}\n"
      },
      "contracts/Proxy.sol": {
        "content": "// SPDX-License-Identifier: LGPL-3.0-only\npragma solidity 0.8.25;\n\n// This code was borrowed from Safe's v1.4.1-build.0:\n// https://github.com/safe-global/safe-smart-account/blob/8b9023d9a2627ecbb5c40592e762857980f8e880/contracts/proxies/SafeProxy.sol\n//\n// The only changes applied were the rename of the interface and the contract.\n\n/**\n * @title IProxyWithMasterCopy - Helper interface to access the singleton address of the Proxy on-chain.\n * @author Richard Meissner - @rmeissner\n */\ninterface IProxyWithMasterCopy {\n    function masterCopy() external view returns (address);\n}\n\n/**\n * @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.\n * @author Stefan George - <stefan@gnosis.io>\n * @author Richard Meissner - <richard@gnosis.io>\n */\n// slither-disable-next-line locked-ether\ncontract Proxy {\n    // Singleton always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated.\n    // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt`\n    // slither-disable-next-line immutable-states\n    address internal singleton;\n\n    /**\n     * @notice Constructor function sets address of singleton contract.\n     * @param _singleton Singleton address.\n     */\n    constructor(address _singleton) {\n        require(_singleton != address(0), \"Invalid singleton address provided\");\n        singleton = _singleton;\n    }\n\n    /// @dev Fallback function forwards all transactions and returns all received return data.\n    fallback() external payable {\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            let _singleton := and(\n                sload(0),\n                0xffffffffffffffffffffffffffffffffffffffff\n            )\n            // 0xa619486e == keccak(\"masterCopy()\"). The value is right padded to 32-bytes with 0s\n            if eq(\n                calldataload(0),\n                0xa619486e00000000000000000000000000000000000000000000000000000000\n            ) {\n                mstore(0, _singleton)\n                return(0, 0x20)\n            }\n            calldatacopy(0, 0, calldatasize())\n            let success := delegatecall(\n                gas(),\n                _singleton,\n                0,\n                calldatasize(),\n                0,\n                0\n            )\n            returndatacopy(0, 0, returndatasize())\n            if eq(success, 0) {\n                revert(0, returndatasize())\n            }\n            return(0, returndatasize())\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 10000
      },
      "evmVersion": "paris",
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "metadata": {
        "useLiteralContent": true
      },
      "libraries": {}
    }
  }}