{
    "Function": "createSystemInstance",
    "File": "src/InstanceDeployer.sol",
    "Parent Contracts": [],
    "High-Level Calls": [
        "Timelock",
        "Timelock",
        "Safe",
        "Timelock",
        "Safe",
        "TimelockFactory",
        "Safe",
        "SafeProxyFactory",
        "SafeProxyFactory"
    ],
    "Internal Calls": [
        "abi.encodeWithSelector()",
        "calculateCreate2Address",
        "code(address)",
        "assert(bool)",
        "abi.encodeWithSelector()",
        "abi.encodeWithSignature()",
        "abi.encode()",
        "mload(uint256)",
        "abi.encodeWithSelector()",
        "mstore(uint256,uint256)",
        "assert(bool)",
        "abi.encodeWithSelector()",
        "mstore(uint256,uint256)",
        "keccak256(bytes)",
        "keccak256(bytes)",
        "abi.encodeWithSelector()",
        "assert(bool)",
        "require(bool,string)",
        "assert(bool)",
        "mstore(uint256,uint256)",
        "code(address)",
        "abi.encodePacked()",
        "require(bool,string)",
        "keccak256(bytes)",
        "assert(bool)",
        "mstore8(uint256,uint256)",
        "abi.encodeWithSelector()",
        "abi.encodeWithSelector()",
        "abi.encode()"
    ],
    "Library Calls": [],
    "Low-Level Calls": [],
    "Code": "function createSystemInstance(NewInstance memory instance)\n        external\n        returns (SystemInstance memory walletInstance)\n    {\n        address[] memory factoryOwner = new address[](1);\n        factoryOwner[0] = address(this);\n\n        bytes memory safeInitdata = abi.encodeWithSignature(\n            \"setup(address[],uint256,address,bytes,address,address,uint256,address)\",\n            factoryOwner,\n            1,\n            /// no to address because there are no external actions on\n            /// initialization\n            address(0),\n            /// no data because there are no external actions on initialization\n            \"\",\n            /// no fallback handler allowed by Guard\n            address(0),\n            /// no payment token\n            address(0),\n            /// no payment amount\n            0,\n            /// no payment receiver because no payment amount\n            address(0)\n        );\n\n        uint256 creationSalt = uint256(\n            keccak256(\n                abi.encode(\n                    instance.owners,\n                    instance.threshold,\n                    instance.timelockParams.minDelay,\n                    instance.timelockParams.expirationPeriod,\n                    instance.timelockParams.pauser,\n                    instance.timelockParams.pauseDuration,\n                    instance.timelockParams.hotSigners\n                )\n            )\n        );\n\n        /// timelock salt is the result of the all params, so no one can\n        /// front-run creation of the timelock with the same address on other\n        /// chains\n        instance.timelockParams.salt = bytes32(creationSalt);\n\n        /// safe guard against front-running safe creation with the same\n        /// address, init data and creation salt on other chains\n        try SafeProxyFactory(safeProxyFactory).createProxyWithNonce(\n            safeProxyLogic, safeInitdata, creationSalt\n        ) returns (SafeProxy safeProxy) {\n            walletInstance.safe = safeProxy;\n        } catch {\n            /// calculate salt just like the safe proxy factory does\n            bytes32 salt = keccak256(\n                abi.encodePacked(keccak256(safeInitdata), creationSalt)\n            );\n            walletInstance.safe = SafeProxy(\n                payable(\n                    calculateCreate2Address(\n                        safeProxyFactory,\n                        SafeProxyFactory(safeProxyFactory).proxyCreationCode(),\n                        abi.encode(safeProxyLogic),\n                        salt\n                    )\n                )\n            );\n\n            emit SafeCreationFailed(\n                msg.sender,\n                block.timestamp,\n                address(walletInstance.safe),\n                safeInitdata,\n                creationSalt\n            );\n        }\n\n        /// if front-running occurred, there should be no way for the safe to\n        /// be created without the exact same address, which means init data\n        /// set the owner of the safe to be this factory address.\n        assert(Safe(payable(walletInstance.safe)).isOwner(address(this)));\n        assert(Safe(payable(walletInstance.safe)).getOwners().length == 1);\n\n        /// the factory uses the msg.sender for creating its salt, so there is\n        /// no way to front-run the timelock creation\n        walletInstance.timelock = Timelock(\n            payable(\n                TimelockFactory(timelockFactory).createTimelock(\n                    address(walletInstance.safe), instance.timelockParams\n                )\n            )\n        );\n\n        require(\n            walletInstance.timelock.hasRole(\n                walletInstance.timelock.HOT_SIGNER_ROLE(), msg.sender\n            ),\n            \"InstanceDeployer: sender must be hot signer\"\n        );\n\n        walletInstance.timelock.initialize(\n            instance.timelockParams.contractAddresses,\n            instance.timelockParams.selectors,\n            instance.timelockParams.startIndexes,\n            instance.timelockParams.endIndexes,\n            instance.timelockParams.datas\n        );\n\n        /// checks that contracts successfully deployed\n        assert(address(walletInstance.timelock).code.length != 0);\n        assert(address(walletInstance.safe).code.length != 0);\n\n        /// 1. setGuard\n        /// 2. enable timelock as a module in the safe\n        IMulticall3.Call3[] memory calls3 = new IMulticall3.Call3[](\n            2 + instance.recoverySpells.length + instance.owners.length\n        );\n        {\n            uint256 index = 0;\n\n            for (uint256 i = 0; i < calls3.length; i++) {\n                calls3[i].target = address(walletInstance.safe);\n                calls3[i].allowFailure = false;\n            }\n\n            calls3[index++].callData =\n                abi.encodeWithSelector(GuardManager.setGuard.selector, guard);\n\n            /// add the timelock as a module to the safe\n            /// this enables the timelock to execute calls + delegate calls through\n            /// the safe\n            calls3[index++].callData = abi.encodeWithSelector(\n                ModuleManager.enableModule.selector,\n                address(walletInstance.timelock)\n            );\n\n            /// enable all recovery spells in the safe by adding them as modules\n            for (uint256 i = 0; i < instance.recoverySpells.length; i++) {\n                /// all recovery spells should be private at the time of safe\n                /// creation, however we cannot enforce this except by excluding\n                /// recovery spells that are not private.\n\n                /// We cannot have a check here that recovery spells are private\n                /// because if we did, and a recovery spell got activated, and it\n                /// was activated on another chain where the system instance was\n                /// deployed, and then the system instance was not deployed on this\n                /// chain, then a malicious user could deploy the recovery spell\n                /// before the system instance to block the instance from ever\n                /// being deployed to this chain.\n                calls3[index++].callData = abi.encodeWithSelector(\n                    ModuleManager.enableModule.selector,\n                    instance.recoverySpells[i]\n                );\n            }\n\n            calls3[index++].callData = abi.encodeWithSelector(\n                OwnerManager.swapOwner.selector,\n                /// previous owner\n                address(1),\n                /// old owner (this address)\n                address(this),\n                /// new owner, the first owner the caller wants to add\n                instance.owners[0]\n            );\n\n            /// - add owners with threshold of 1\n            /// - only cover indexes 1 through newOwners.length - 1\n            /// - leave the last index for the final owner which will adjust the\n            /// threshold\n            for (uint256 i = 1; i < instance.owners.length - 1; i++) {\n                calls3[index++].callData = abi.encodeWithSelector(\n                    OwnerManager.addOwnerWithThreshold.selector,\n                    instance.owners[i],\n                    1\n                );\n            }\n\n            /// if there is only one owner, the threshold is set to 1\n            /// if there are more than one owner, add the final owner with the\n            /// updated threshold\n            if (instance.owners.length > 1) {\n                /// add final owner with the updated threshold\n                /// if threshold is greater than the number of owners, that\n                /// will be caught in the addOwnerWithThreshold function with\n                /// error \"GS201\"\n                calls3[index++].callData = abi.encodeWithSelector(\n                    OwnerManager.addOwnerWithThreshold.selector,\n                    instance.owners[instance.owners.length - 1],\n                    instance.threshold\n                );\n            }\n\n            /// ensure that the number of calls is equal to the index\n            /// this is a safety check and should never be false\n            assert(calls3.length == index);\n        }\n\n        bytes memory signature;\n        /// craft the signature singing off on all of the multicall\n        /// operations\n        {\n            bytes32 r = bytes32(uint256(uint160(address(this))));\n            uint8 v = 1;\n\n            assembly (\"memory-safe\") {\n                /// Load free memory location\n                let ptr := mload(0x40)\n\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\n                ///         4 -> 82\n                mstore(0x40, add(ptr, 97))\n                ///         4 -> 179\n\n                /// Store the size of the signature in the first 32 bytes:\n                /// 65 (r + s + v)\n                mstore(ptr, 65)\n\n                ///\n                ///                              Data Offsets\n                ///\n                ///                 --------------------------------------\n                ///  bytes length   |      32     |   32  |  32   |   1  |\n                ///                 --------------------------------------\n                ///      bytes      |     0-31    | 32-63 | 64-95 |  96  |\n                ///                 --------------------------------------\n                ///      data       | length = 65 |   r   |   s   |   v  |\n                ///                 --------------------------------------\n                ///\n\n                /// store r at offset 32 to 64 in the allocated pointer\n                mstore(add(ptr, 0x20), r)\n\n                /// no need to store s, this should be 0 bytes\n\n                /// store v at offset 96 to 97 in the allocated pointer\n                mstore8(add(ptr, 0x60), v)\n\n                /// Point the signature data to the correct memory location\n                signature := ptr\n            }\n        }\n\n        require(\n            Safe(payable(walletInstance.safe)).execTransaction(\n                multicall3,\n                0,\n                abi.encodeWithSelector(IMulticall3.aggregate3.selector, calls3),\n                Enum.Operation.DelegateCall,\n                0,\n                0,\n                0,\n                address(0),\n                payable(0),\n                signature\n            ),\n            \"InstanceDeployer: Safe delegate call failed\"\n        );\n\n        emit SystemInstanceCreated(\n            address(walletInstance.safe),\n            address(walletInstance.timelock),\n            msg.sender,\n            block.timestamp\n        );\n    }"
}