diff --git a/Makefile b/Makefile index ad51512e..689b815f 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ PROJECT_DIR = $(network)/$(shell date +'%Y-%m-%d')-$(task) GAS_INCREASE_DIR = $(network)/$(shell date +'%Y-%m-%d')-increase-gas-limit GAS_AND_ELASTICITY_INCREASE_DIR = $(network)/$(shell date +'%Y-%m-%d')-increase-gas-and-elasticity-limit FAULT_PROOF_UPGRADE_DIR = $(network)/$(shell date +'%Y-%m-%d')-upgrade-fault-proofs -SAFE_MANAGEMENT_DIR = $(network)/$(shell date +'%Y-%m-%d')-safe-swap-owner +SAFE_MANAGEMENT_DIR = $(network)/$(shell date +'%Y-%m-%d')-safe-management FUNDING_DIR = $(network)/$(shell date +'%Y-%m-%d')-funding SET_BASE_BRIDGE_PARTNER_THRESHOLD_DIR = $(network)/$(shell date +'%Y-%m-%d')-pause-bridge-base PAUSE_BRIDGE_BASE_DIR = $(network)/$(shell date +'%Y-%m-%d')-pause-bridge-base diff --git a/README.md b/README.md index 1df636c8..6fa6d7a5 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ To execute a new task, run one of the following commands (depending on the type - For funding: `make setup-funding network=` - For fault proof upgrade: `make setup-upgrade-fault-proofs network=` - For safe management tasks: `make setup-safe-management network=` +- For funding tasks: `make setup-funding network=` - For updating the partner threshold in Base Bridge: `make setup-bridge-partner-threshold network=` - For pausing / un-pausing Base Bridge: `make setup-bridge-pause network=` @@ -129,17 +130,19 @@ This template is used to upgrade the fault proof contracts. This is commonly don 1. Check in the task when it's ready to sign and collect signatures from signers 1. Once executed, check in the records files and mark the task `EXECUTED` in the README. -## Using the swap owner template +## Using the safe management template -This template is used to perform ownership management on a Gnosis Safe multisig, specifically it can swap owners on the multisig. +This template is used to perform ownership management on a Gnosis Safe, like the incident multisig, specifically it can be used to change the owners of the multisig. -1. Ensure you have followed the instructions above in `setup`. -1. Run `make setup-safe-management network=` and go to the folder that was created by this command. +1. Ensure you have followed the instructions above in `setup`, including running `make setup-safe-management network=` and go to the folder that was created by this command. 1. Specify the commit of [Optimism code](https://github.com/ethereum-optimism/optimism) and [Base contracts code](https://github.com/base-org/contracts) you intend to use in the `.env` file. -1. Run `make deps`. -1. Specify the `OWNER_SAFE`, which is the safe multisig where an owner will be replaced, the `OLD_SIGNER` (current owner) to remove, and the `NEW_SIGNER` (new owner) to be added in the `.env` file. +1. Enter the directory that was generated for the task (in the first step) and then run `make deps`. +1. Specify the `OWNER_SAFE`, which is the safe multisig where an owner will be replaced and the `SENDER` which should be the address of a current signer of the multisig. +1. Fill in the `OwnerDiff.json` inside the task's directory with the addresses to add to, and remove from, the multisig in their respective fields. +1. Ensure that the `EXISTING_OWNERS_LENGTH` constant value inside the `script/UpdateSigners.s.sol` script is set appropriately, in particular that it equals the exact number of current members of the Incident Multisig Safe (prior to running the task). 1. Build the contracts with `forge build`. -1. Simulate the task with `make sign` and update the generic validations in `VALIDATION.md` with the real values. +1. Generate the validation file for signers with `make gen-validation`. +1. Double check the `cmd` field at the top of the generated validation file at `validations/base-signer.json` and ensure that the value passed to the `--sender` flag matches the `SENDER` env var already defined in the `.env` file. 1. Check in the task when it's ready to sign and request the facilitators to collect signatures from signers. 1. Once executed, check in the records files and mark the task `EXECUTED` in the README. diff --git a/setup-templates/template-safe-management/.env b/setup-templates/template-safe-management/.env index 1d054d17..cc384517 100644 --- a/setup-templates/template-safe-management/.env +++ b/setup-templates/template-safe-management/.env @@ -1,7 +1,10 @@ -OP_COMMIT= -BASE_CONTRACTS_COMMIT= +OP_COMMIT=TODO # Recommend using the version of https://github.com/ethereum-optimism/optimism that the current SystemConfig contract is on +BASE_CONTRACTS_COMMIT=TODO # Recommend using the latest version of https://github.com/base-org/contracts -OWNER_SAFE= +# TODO: ensure `OWNER_SAFE` is correct on the given network +OWNER_SAFE=TODO -OLD_SIGNER= -NEW_SIGNER= +# TODO: ensure `SENDER` is a signer for `OWNER_SAFE` on the given network and is ALSO the same sender defined in the validations/base-signer.json file +SENDER=TODO + +RECORD_STATE_DIFF=true diff --git a/setup-templates/template-safe-management/Makefile b/setup-templates/template-safe-management/Makefile index a459b8af..679d3644 100644 --- a/setup-templates/template-safe-management/Makefile +++ b/setup-templates/template-safe-management/Makefile @@ -1,22 +1,33 @@ include ../../Makefile include ../../Multisig.mk - include ../.env include .env +RPC_URL = $(L1_RPC_URL) +SCRIPT = UpdateSigners + ifndef LEDGER_ACCOUNT -override LEDGER_ACCOUNT = 0 +override LEDGER_ACCOUNT = 1 endif -# OWNER_SAFE/ -# └── Signers +.PHONY: deps +deps: new-forge-deps -RPC_URL = $(L1_RPC_URL) -SCRIPT_NAME = SwapOwner +.PHONY: new-forge-deps +new-forge-deps: + forge install --no-git safe-global/safe-smart-account@186a21a74b327f17fc41217a927dea7064f74604 + +.PHONY: gen-validation +gen-validation: checkout-signer-tool run-script -.PHONY: sign -sign: - $(call MULTISIG_SIGN,) +.PHONY: run-script +run-script: + mkdir validations; \ + cd $(SIGNER_TOOL_PATH); \ + npm ci; \ + bun run scripts/genValidationFile.ts --rpc-url $(L1_RPC_URL) \ + --workdir .. --forge-cmd 'forge script --rpc-url $(L1_RPC_URL) \ + $(SCRIPT) --sig "sign(address[])" [] --sender $(SENDER)' --out ../validations/base-signer.json; .PHONY: execute execute: diff --git a/setup-templates/template-safe-management/OwnerDiff.json b/setup-templates/template-safe-management/OwnerDiff.json new file mode 100644 index 00000000..f2321928 --- /dev/null +++ b/setup-templates/template-safe-management/OwnerDiff.json @@ -0,0 +1,8 @@ +{ + "OwnersToAdd": [ + "0x0000000000000000000000000000000000000000" + ], + "OwnersToRemove": [ + "0x0000000000000000000000000000000000000001" + ] +} diff --git a/setup-templates/template-safe-management/README.md b/setup-templates/template-safe-management/README.md index c94ef3f4..2b643aaf 100644 --- a/setup-templates/template-safe-management/README.md +++ b/setup-templates/template-safe-management/README.md @@ -1,149 +1,52 @@ -# Swap Owner on Gnosis Safe +# Update Sepolia Incident Multisig Signers -Status: PENDING +Status: TODO[READY TO SIGN|EXECUTED] ## Description -This task contains a single script that can be used to swap an owner in a Gnosis Safe. +We wish to update the owners of our Incident Multisig to be consistent with the current state of our Base Chain Eng team. This involves removing signers that are no longer closely involved with the team, and adding new team members as signers. The exact signer changes are outlined in the [OwnerDiff.json](./OwnerDiff.json) file. -## Procedure +## Install dependencies -### 1. Update repo: +### 1. Update foundry ```bash -cd contract-deployments -git pull -make setup-safe-management network= -cd /safe-swap-owner -make deps +foundryup ``` -### 2. Setup Ledger - -Your Ledger needs to be connected and unlocked. The Ethereum -application needs to be opened on Ledger with the message "Application -is ready". - -### 3. Simulate, Validate, and Sign +### 2. Install Node.js if needed -#### 3.1. Simulate and validate the transaction - -Make sure your ledger is still unlocked and run the following. +First, check if you have node installed ```bash -make sign +node --version ``` -You will see a "Simulation link" from the output. - -Paste this URL in your browser. A prompt may ask you to choose a -project, any project will do. You can create one if necessary. - -Click "Simulate Transaction". - -We will be performing 3 validations and extract the domain hash and -message hash to approve on your Ledger: - -1. Validate integrity of the simulation. -2. Validate correctness of the state diff. -3. Validate and extract domain hash and message hash to approve. - -##### 3.1.1. Validate integrity of the simulation. - -Make sure you are on the "Summary" tab of the tenderly simulation, to -validate integrity of the simulation, we need to check the following: - -1. "Network": Check the network is ``. -2. "Timestamp": Check the simulation is performed on a block with a - recent timestamp (i.e. close to when you run the script). -3. "Sender": Check the address shown is your signer account. - -##### 3.1.2. Validate correctness of the state diff. - -Now click on the "State" tab, and refer to the [State Validations](./VALIDATION.md) instructions for the transaction you are signing. -Once complete return to this document to complete the signing. - -### 4. Extract the domain hash and the message hash to approve. - -Now that we have verified the transaction performs the right -operation, we need to extract the domain hash and the message hash to -approve. - -Go back to the "Summary" tab, and find the -`Safe.checkSignatures` call. This call's `data` parameter -contains both the domain hash and the message hash that will show up -in your Ledger. - -It will be a concatenation of `0x1901`, the domain hash, and the -message hash: `0x1901[domain hash][message hash]`. +If you see a version output from the above command, you can move on. Otherwise, install node -Note down this value. You will need to compare it with the ones -displayed on the Ledger screen at signing. - -Once the validations are done, it's time to actually sign the -transaction. - -> [!WARNING] -> This is the most security critical part of the playbook: make sure the -> domain hash and message hash in the following three places match: -> -> 1. On your Ledger screen. -> 2. In the terminal output. -> 3. In the Tenderly simulation. You should use the same Tenderly -> simulation as the one you used to verify the state diffs, instead -> of opening the new one printed in the console. -> - -After verification, sign the transaction. You will see the `Data`, -`Signer` and `Signature` printed in the console. Format should be -something like this: - -```shell -Data: -Signer:
-Signature: +```bash +brew install node ``` -Double check the signer address is the right one. - -#### 4.1. Send the output to Facilitator(s) - -Nothing has occurred onchain - these are offchain signatures which -will be collected by Facilitators for execution. Execution can occur -by anyone once a threshold of signatures are collected, so a -Facilitator will do the final execution for convenience. - -Share the `Data`, `Signer` and `Signature` with the Facilitator, and -congrats, you are done! - -### [For Facilitator ONLY] How to execute +## Approving Signers Update -#### Execute the transaction +### 1. Update repo: -1. Collect outputs from all participating signers. -1. Concatenate all signatures and export it as the `SIGNATURES` - environment variable, i.e. `export -SIGNATURES="[SIGNATURE1][SIGNATURE2]..."`. -1. Run the `make execute` command as described below to execute the transaction. +```bash +cd contract-deployments +git pull +``` -For example, if the quorum is 2 and you get the following outputs: +### 2. Run the signing tool (NOTE: do not enter the task directory. Run this command from the project's root). -```shell -Data: 0xDEADBEEF -Signer: 0xC0FFEE01 -Signature: AAAA +```bash +make sign-task ``` -```shell -Data: 0xDEADBEEF -Signer: 0xC0FFEE02 -Signature: BBBB -``` +### 3. Open the UI at [http://localhost:3000](http://localhost:3000) -Then you should run: +Be sure to select the correct task from the list of available tasks to sign. -Coinbase facilitator: +### 4. Send signature to facilitator -```bash -SIGNATURES=AAAABBBB make execute -``` +You may now kill the Signer Tool process in your terminal window by running `Ctrl + C`. diff --git a/setup-templates/template-safe-management/VALIDATION.md b/setup-templates/template-safe-management/VALIDATION.md deleted file mode 100644 index 3c649fcb..00000000 --- a/setup-templates/template-safe-management/VALIDATION.md +++ /dev/null @@ -1,78 +0,0 @@ -# Validation - -This document can be used to validate the state diff resulting from the execution of the swap owner transaction. - -For each contract listed in the state diff, please verify that no contracts or state changes shown in the Tenderly diff are missing from this document. Additionally, please verify that for each contract: - -- The following state changes (and no others) are made to that contract. This validates that no unexpected state changes occur. -- All addresses (in section headers and storage values) match the provided name, using the Etherscan links provided. This validates the bytecode deployed at the addresses contains the correct logic. -- All key values match the semantic meaning provided, which can be validated using the storage layout links provided. - -## State Changes - -### `` (Base `GnosisSafeProxy`) - -- **Key**: `owners[newOwner]`
- **Before**: `0x0000000000000000000000000000000000000000000000000000000000000000`
- **After**: `Next address in the list returned by getOwners()`
- **Meaning**: Sets the address value at the mapping key `owners[newOwner]` to the next address in the list returned by `getOwners()`. This is the first step required to replace the `oldOwner` address in the linked list data structure of owners.
- **Verify**: You can verify the key derivation by running `cast index address 2` in your terminal. See the following section for an explanation of the storage and value calculations. -- **Key**: `owners[prevOwner]`
- **Before**: `oldOwner address`
- **After**: `newOwner address`
- **Meaning**: Points the address value at mapping key `owners[prevOwner]` to the `newOwner` address. This is the second step required to replace the `oldOwner` address in the linked list data structure of owners.
- **Verify**: You can verify the key derivation by running `cast index address 2` in your terminal. See the following section for an explanation of the storage and value calculations. -- **Key**: `owners[oldOwner]`
- **Before**: `Next address in the list returned by getOwners()`
- **After**: `0x0000000000000000000000000000000000000000000000000000000000000000`
- **Meaning**: Clears the address value at the mapping key `owners[oldOwner]`. This removes the final reference to the `oldOwner` from the `owners` linked list.
- **Verify**: You can verify the key derivation by running `cast index address 2` in your terminal. See the following section for an explanation of the storage and value calculations. -- **Key**: `0x0000000000000000000000000000000000000000000000000000000000000005`
- **Before**: `Current nonce value (in hexadecimal)`
- **After**: `Current nonce value + 1 (in hexadecimal)`
- **Meaning**: Increments the `nonce` value of the Gnosis Safe.
- **Verify**: You can verify the value by running `cast storage 5 -r ` in your terminal. This value represents the _current_ nonce value. - -### `SwapOwner` Storage Calculations - -The [`swapOwner`](https://github.com/safe-global/safe-smart-account/blob/8823fa3e44936e2aecf23bb97662eb0ffeff2f93/contracts/base/OwnerManager.sol#L94) function in the Gnosis Safe implementation will perform [three storage changes](https://github.com/safe-global/safe-smart-account/blob/8823fa3e44936e2aecf23bb97662eb0ffeff2f93/contracts/base/OwnerManager.sol#L106-L108): - -- Point the `newOwner` address to the owner address that was previously pointed to by the `oldOwner` that is being removed. -- Point the `prevOwner` address to the `newOwner` address. -- Remove the pointer value stored at the mapping of the `oldOwner` address. - -These changes are needed on account of the data structure that holds the owners in the Gnosis Safe implementation being a singly-linked list. To calculate the expected storage locations of these mapping values, we can perform the following: - -#### Calculating `prevOwner` - -The `prevOwner` is identified by the script, but can be manually checked by running the cast command: - -```sh -cast call "getOwners()(address[])" -r - -[0x6CD3850756b7894774Ab715D136F9dD02837De50, 0x3cd692eCE8b6573A2220ae00d0dEb98f0DfFA9a1, 0x5FbEFA105bbd53b43bf537Cbc5cD30804Dd0c993, 0x3Dad2200849925Bb46d9bF05aFa5f7F213F4c18E, 0xB011a32ED8b4F70D9943A2199F539bbeCd7b62F7, 0xf9e320f3dA12E68af219d9E2A490Dd649f6B177c] -``` - -The order that the owner addresses are returned in indicates who the `prevOwner` and next owner values of the address to remove is. If the owner to remove is the 0th value, its `prevOwner` would be the special sentinel node value [`SENTINEL_OWNERS`](https://github.com/safe-global/safe-smart-account/blob/f9cc387f72640eb2c1d6ae8abe9d6ff25ca1ed3b/contracts/base/OwnerManager.sol#L17). Otherwise, if the owner to remove is the last value in the array, its next owner address would be the special sentinel node value [`SENTINEL_OWNERS`](https://github.com/safe-global/safe-smart-account/blob/f9cc387f72640eb2c1d6ae8abe9d6ff25ca1ed3b/contracts/base/OwnerManager.sol#L17). - -#### Calculating storage locations and values - -With the order of the owners identified, we can calculate the expected storage mapping locations and their values. For the first change, the expected storage slot and value will be the following: - -**Storage Slot**: `cast index address 2` - -**Value**: The address immediately following `oldOwner` in the `getOwners` list, or the `SENTINEL_OWNERS` special value if the address is the last in the array. - -For the second change, it will be: - -**Storage Slot**: `cast index address 2` - -**Value**: `newOwner` address - -For the final storage change, it will be: - -**Storage Slot**: `cast index address 2` - -**Value**: `address(0)` - -Note that for all the above storage calculations, we used storage slot 2 as that is the location of the `owners` mapping in the Gnosis Safe storage layout. This can be confirmed with the following command: `cast storage -r -e `. Also note that while the storage changes may not appear in the same order in the Tenderly simulation, there should still be 3 storage changes related to the `owner` linked list and one change for the `nonce` value on the `GnosisSafeProxy`. There should be no additional changes to the proxy besides these ones! diff --git a/setup-templates/template-safe-management/foundry.toml b/setup-templates/template-safe-management/foundry.toml index 1f932186..14499ab0 100644 --- a/setup-templates/template-safe-management/foundry.toml +++ b/setup-templates/template-safe-management/foundry.toml @@ -3,7 +3,7 @@ src = 'src' out = 'out' libs = ['lib'] broadcast = 'records' -fs_permissions = [ {access = "read-write", path = "./"} ] +fs_permissions = [{ access = "read-write", path = "./" }] optimizer = true optimizer_runs = 999999 solc_version = "0.8.15" @@ -14,7 +14,7 @@ remappings = [ '@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts', '@rari-capital/solmate/=lib/solmate/', '@base-contracts/=lib/base-contracts', - '@solady/=lib/solady/src/' + 'solady/=lib/solady/src/', ] -# See more config options https://github.com/foundry-rs/foundry/tree/master/config \ No newline at end of file +# See more config options https://github.com/foundry-rs/foundry/tree/master/config diff --git a/setup-templates/template-safe-management/script/SwapOwner.s.sol b/setup-templates/template-safe-management/script/SwapOwner.s.sol deleted file mode 100644 index 0dbbb6ee..00000000 --- a/setup-templates/template-safe-management/script/SwapOwner.s.sol +++ /dev/null @@ -1,67 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity 0.8.15; - -import {Vm} from "forge-std/Vm.sol"; -import {IMulticall3} from "forge-std/interfaces/IMulticall3.sol"; - -import {IGnosisSafe} from "@base-contracts/script/universal/IGnosisSafe.sol"; -import {MultisigScript} from "@base-contracts/script/universal/MultisigScript.sol"; -import {Simulation} from "@base-contracts/script/universal/Simulation.sol"; - -contract SwapOwner is MultisigScript { - address internal OWNER_SAFE = vm.envAddress("OWNER_SAFE"); - address internal OLD_SIGNER = vm.envAddress("OLD_SIGNER"); - address internal NEW_SIGNER = vm.envAddress("NEW_SIGNER"); - - address internal constant SENTINEL_OWNERS = address(0x1); - - address[] internal safeOwners; // The list of all owners of the safe - address internal prevOwnerLinked; // The previous owner in Safe's linked list of owners - - function setUp() public { - safeOwners = IGnosisSafe(OWNER_SAFE).getOwners(); - _precheck(); - - // We need to locate the previous owner in the linked list of owners to properly swap out the target signer - for (uint256 i = 0; i < safeOwners.length; i++) { - if (safeOwners[i] == OLD_SIGNER) { - // There is a sentinel node as the head of the linked list, so we need to handle the first owner separately - if (i == 0) { - prevOwnerLinked = SENTINEL_OWNERS; - } else { - prevOwnerLinked = safeOwners[i - 1]; - } - break; - } - } - } - - function _precheck() internal view { - // Sanity checks on the current owner state of the safe - require(IGnosisSafe(OWNER_SAFE).isOwner(OLD_SIGNER), "Signer to swap is not an owner"); - require(!IGnosisSafe(OWNER_SAFE).isOwner(NEW_SIGNER), "New signer is already an owner"); - } - - function _buildCalls() internal view override returns (IMulticall3.Call3Value[] memory) { - IMulticall3.Call3Value[] memory calls = new IMulticall3.Call3Value[](1); - - // While more roundabout then simply calling execTransaction with a swapOwner call, this still works and lets us use our existing tooling - calls[0] = IMulticall3.Call3Value({ - target: OWNER_SAFE, - allowFailure: false, - callData: abi.encodeCall(IGnosisSafe.swapOwner, (prevOwnerLinked, OLD_SIGNER, NEW_SIGNER)), - value: 0 - }); - - return calls; - } - - function _postCheck(Vm.AccountAccess[] memory, Simulation.Payload memory) internal view override { - require(IGnosisSafe(OWNER_SAFE).isOwner(NEW_SIGNER), "New signer was not added as an owner"); - require(!IGnosisSafe(OWNER_SAFE).isOwner(OLD_SIGNER), "Old signer was not removed as an owner"); - } - - function _ownerSafe() internal view override returns (address) { - return OWNER_SAFE; - } -} diff --git a/setup-templates/template-safe-management/script/UpdateSigners.s.sol b/setup-templates/template-safe-management/script/UpdateSigners.s.sol new file mode 100644 index 00000000..4bb1481c --- /dev/null +++ b/setup-templates/template-safe-management/script/UpdateSigners.s.sol @@ -0,0 +1,136 @@ +// SPDX-License-Identifier: MIT +pragma solidity 0.8.15; + +import {Vm} from "forge-std/Vm.sol"; +import {stdJson} from "forge-std/StdJson.sol"; +import {Simulation} from "@base-contracts/script/universal/Simulation.sol"; +import {IMulticall3} from "forge-std/interfaces/IMulticall3.sol"; + +import {MultisigScript} from "@base-contracts/script/universal/MultisigScript.sol"; +import {GnosisSafe} from "safe-smart-account/GnosisSafe.sol"; +import {OwnerManager} from "safe-smart-account/base/OwnerManager.sol"; + +contract UpdateSigners is MultisigScript { + using stdJson for string; + + address public constant SENTINEL_OWNERS = address(0x1); + + // TODO: replace with the current number of members of the incident multisig + uint256 public constant EXISTING_OWNERS_LENGTH = TODO; + + address public immutable OWNER_SAFE; + uint256 public immutable THRESHOLD; + address[] public EXISTING_OWNERS; + + address[] public OWNERS_TO_ADD; + address[] public OWNERS_TO_REMOVE; + + mapping(address => address) public ownerToPrevOwner; + mapping(address => address) public ownerToNextOwner; + mapping(address => bool) public expectedOwner; + + constructor() { + OWNER_SAFE = vm.envAddress("OWNER_SAFE"); + + GnosisSafe ownerSafe = GnosisSafe(payable(OWNER_SAFE)); + THRESHOLD = ownerSafe.getThreshold(); + EXISTING_OWNERS = ownerSafe.getOwners(); + + string memory rootPath = vm.projectRoot(); + string memory path = string.concat(rootPath, "/OwnerDiff.json"); + string memory jsonData = vm.readFile(path); + + OWNERS_TO_ADD = abi.decode(jsonData.parseRaw(".OwnersToAdd"), (address[])); + OWNERS_TO_REMOVE = abi.decode(jsonData.parseRaw(".OwnersToRemove"), (address[])); + } + + function setUp() external { + require(OWNERS_TO_ADD.length > 0, "Precheck 00"); + require(OWNERS_TO_REMOVE.length > 0, "Precheck 01"); + require(EXISTING_OWNERS.length == EXISTING_OWNERS_LENGTH, "Precheck 02"); + + GnosisSafe ownerSafe = GnosisSafe(payable(OWNER_SAFE)); + address prevOwner = SENTINEL_OWNERS; + + for (uint256 i = OWNERS_TO_ADD.length; i > 0; i--) { + uint256 index = i - 1; + // Make sure owners to add are not already owners + require(!ownerSafe.isOwner(OWNERS_TO_ADD[index]), "Precheck 03"); + // Prevent duplicates + require(!expectedOwner[OWNERS_TO_ADD[index]], "Precheck 04"); + + ownerToPrevOwner[OWNERS_TO_ADD[index]] = prevOwner; + ownerToNextOwner[prevOwner] = OWNERS_TO_ADD[index]; + prevOwner = OWNERS_TO_ADD[index]; + expectedOwner[OWNERS_TO_ADD[index]] = true; + } + + for (uint256 i; i < EXISTING_OWNERS.length; i++) { + ownerToPrevOwner[EXISTING_OWNERS[i]] = prevOwner; + ownerToNextOwner[prevOwner] = EXISTING_OWNERS[i]; + prevOwner = EXISTING_OWNERS[i]; + expectedOwner[EXISTING_OWNERS[i]] = true; + } + + for (uint256 i; i < OWNERS_TO_REMOVE.length; i++) { + // Make sure owners to remove are owners + require(ownerSafe.isOwner(OWNERS_TO_REMOVE[i]), "Precheck 05"); + // Prevent duplicates + require(expectedOwner[OWNERS_TO_REMOVE[i]], "Precheck 06"); + expectedOwner[OWNERS_TO_REMOVE[i]] = false; + + // Remove from linked list to keep ownerToPrevOwner up to date + // Note: This works as long as the order of OWNERS_TO_REMOVE does not change during `_buildCalls()` + address nextOwner = ownerToNextOwner[OWNERS_TO_REMOVE[i]]; + address prevPtr = ownerToPrevOwner[OWNERS_TO_REMOVE[i]]; + ownerToPrevOwner[nextOwner] = prevPtr; + ownerToNextOwner[prevPtr] = nextOwner; + } + } + + function _postCheck(Vm.AccountAccess[] memory, Simulation.Payload memory) internal view override { + GnosisSafe ownerSafe = GnosisSafe(payable(OWNER_SAFE)); + address[] memory postCheckOwners = ownerSafe.getOwners(); + uint256 postCheckThreshold = ownerSafe.getThreshold(); + + uint256 expectedLength = EXISTING_OWNERS.length + OWNERS_TO_ADD.length - OWNERS_TO_REMOVE.length; + + require(postCheckThreshold == THRESHOLD, "Postcheck 00"); + require(postCheckOwners.length == expectedLength, "Postcheck 01"); + + for (uint256 i; i < postCheckOwners.length; i++) { + require(expectedOwner[postCheckOwners[i]], "Postcheck 02"); + } + } + + function _buildCalls() internal view override returns (IMulticall3.Call3Value[] memory) { + IMulticall3.Call3Value[] memory calls = + new IMulticall3.Call3Value[](OWNERS_TO_ADD.length + OWNERS_TO_REMOVE.length); + + for (uint256 i; i < OWNERS_TO_ADD.length; i++) { + calls[i] = IMulticall3.Call3Value({ + target: OWNER_SAFE, + allowFailure: false, + callData: abi.encodeCall(OwnerManager.addOwnerWithThreshold, (OWNERS_TO_ADD[i], THRESHOLD)), + value: 0 + }); + } + + for (uint256 i; i < OWNERS_TO_REMOVE.length; i++) { + calls[OWNERS_TO_ADD.length + i] = IMulticall3.Call3Value({ + target: OWNER_SAFE, + allowFailure: false, + callData: abi.encodeCall( + OwnerManager.removeOwner, (ownerToPrevOwner[OWNERS_TO_REMOVE[i]], OWNERS_TO_REMOVE[i], THRESHOLD) + ), + value: 0 + }); + } + + return calls; + } + + function _ownerSafe() internal view override returns (address) { + return OWNER_SAFE; + } +} \ No newline at end of file