diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c7a547c2f..8a4281ed0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,15 @@ jobs: - uses: actions/checkout@v4 - uses: foundry-rs/foundry-toolchain@v1 - run: forge --version - - run: forge build --skip test --deny-warnings ${{ matrix.flags }} + - run: | + case "${{ matrix.flags }}" in + *"solc:0.8.0"* | *"solc:0.7"* | *"solc:0.6"*) + forge build --skip test --skip Config --skip StdConfig --skip LibVariable --deny-warnings ${{ matrix.flags }} + ;; + *) + forge build --skip test --deny-warnings ${{ matrix.flags }} + ;; + esac # via-ir compilation time checks. - if: contains(matrix.flags, '--via-ir') run: forge build --skip test --deny-warnings ${{ matrix.flags }} --contracts 'test/compilation/*' @@ -48,7 +56,12 @@ jobs: with: version: ${{ matrix.toolchain }} - run: forge --version - - run: forge test -vvv + - run: | + if [ "${{ matrix.toolchain }}" = "stable" ]; then + forge test -vvv --no-match-path "test/Config.t.sol" + else + forge test -vvv + fi fmt: runs-on: ubuntu-latest diff --git a/foundry.toml b/foundry.toml index 62ca21a6e..b68bd546c 100644 --- a/foundry.toml +++ b/foundry.toml @@ -1,12 +1,16 @@ [profile.default] -fs_permissions = [{ access = "read-write", path = "./"}] +fs_permissions = [{ access = "read-write", path = "./" }] optimizer = true optimizer_runs = 200 +# A list of solidity error codes to ignore. +# 3860 = init-code-size +ignored_error_codes = [3860] + [rpc_endpoints] # The RPC URLs are modified versions of the default for testing initialization. -mainnet = "https://eth.merkle.io" # Different API key. -optimism_sepolia = "https://sepolia.optimism.io/" # Adds a trailing slash. +mainnet = "https://eth.merkle.io" # Different API key. +optimism_sepolia = "https://sepolia.optimism.io/" # Adds a trailing slash. arbitrum_one_sepolia = "https://sepolia-rollup.arbitrum.io/rpc/" # Adds a trailing slash. needs_undefined_env_var = "${UNDEFINED_RPC_URL_PLACEHOLDER}" @@ -20,4 +24,4 @@ multiline_func_header = 'attributes_first' quote_style = 'double' number_underscore = 'preserve' single_line_statement_blocks = 'preserve' -ignore = ["src/console.sol", "src/console2.sol"] \ No newline at end of file +ignore = ["src/console.sol", "src/console2.sol"] diff --git a/src/Base.sol b/src/Base.sol index 5b618c67c..52a508210 100644 --- a/src/Base.sol +++ b/src/Base.sol @@ -8,22 +8,28 @@ abstract contract CommonBase { /// @dev Cheat code address. /// Calculated as `address(uint160(uint256(keccak256("hevm cheat code"))))`. address internal constant VM_ADDRESS = 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D; + /// @dev console.sol and console2.sol work by executing a staticcall to this address. /// Calculated as `address(uint160(uint88(bytes11("console.log"))))`. address internal constant CONSOLE = 0x000000000000000000636F6e736F6c652e6c6f67; + /// @dev Used when deploying with create2. /// Taken from https://github.com/Arachnid/deterministic-deployment-proxy. address internal constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C; + /// @dev The default address for tx.origin and msg.sender. /// Calculated as `address(uint160(uint256(keccak256("foundry default caller"))))`. address internal constant DEFAULT_SENDER = 0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38; + /// @dev The address of the first contract `CREATE`d by a running test contract. /// When running tests, each test contract is `CREATE`d by `DEFAULT_SENDER` with nonce 1. /// Calculated as `VM.computeCreateAddress(VM.computeCreateAddress(DEFAULT_SENDER, 1), 1)`. address internal constant DEFAULT_TEST_CONTRACT = 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f; + /// @dev Deterministic deployment address of the Multicall3 contract. /// Taken from https://www.multicall3.com. address internal constant MULTICALL3_ADDRESS = 0xcA11bde05977b3631167028862bE2a173976CA11; + /// @dev The order of the secp256k1 curve. uint256 internal constant SECP256K1_ORDER = 115792089237316195423570985008687907852837564279074904382605163141518161494337; diff --git a/src/Config.sol b/src/Config.sol new file mode 100644 index 000000000..1c63c8721 --- /dev/null +++ b/src/Config.sol @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +import {console} from "./console.sol"; +import {StdConfig} from "./StdConfig.sol"; +import {CommonBase} from "./Base.sol"; + +/// @notice Boilerplate to streamline the setup of multi-chain environments. +abstract contract Config is CommonBase { + // -- STORAGE (CONFIG + CHAINS + FORKS) ------------------------------------ + + /// @dev Contract instance holding the data from the TOML config file. + StdConfig internal config; + + /// @dev Array of chain IDs for which forks have been created. + uint256[] internal chainIds; + + /// @dev A mapping from a chain ID to its initialized fork ID. + mapping(uint256 => uint256) internal forkOf; + + // -- HELPER FUNCTIONS ----------------------------------------------------- + + /// @notice Loads configuration from a file. + /// + /// @dev This function instantiates a `Config` contract, caching all its config variables. + /// + /// @param filePath: the path to the TOML configuration file. + /// @param writeToFile: whether updates are written back to the TOML file. + function _loadConfig(string memory filePath, bool writeToFile) internal { + console.log("----------"); + console.log(string.concat("Loading config from '", filePath, "'")); + config = new StdConfig(filePath, writeToFile); + vm.makePersistent(address(config)); + console.log("Config successfully loaded"); + console.log("----------"); + } + + /// @notice Loads configuration from a file and creates forks for each specified chain. + /// + /// @dev This function instantiates a `Config` contract, caching all its config variables, + /// reads the configured chain ids, and iterates through them to create a fork for each one. + /// It also creates a map `forkOf[chainId] -> forkId` to easily switch between forks. + /// + /// @param filePath: the path to the TOML configuration file. + /// @param writeToFile: whether updates are written back to the TOML file. + function _loadConfigAndForks(string memory filePath, bool writeToFile) internal { + _loadConfig(filePath, writeToFile); + + console.log("Setting up forks for the configured chains..."); + uint256[] memory chains = config.getChainIds(); + for (uint256 i = 0; i < chains.length; i++) { + uint256 chainId = chains[i]; + uint256 forkId = vm.createFork(config.getRpcUrl(chainId)); + forkOf[chainId] = forkId; + chainIds.push(chainId); + } + console.log("Forks successfully created"); + console.log("----------"); + } +} diff --git a/src/LibVariable.sol b/src/LibVariable.sol new file mode 100644 index 000000000..c46b15328 --- /dev/null +++ b/src/LibVariable.sol @@ -0,0 +1,477 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +// Enable globally. +using LibVariable for Variable global; + +struct Variable { + Type ty; + bytes data; +} + +struct Type { + TypeKind kind; + bool isArray; +} + +enum TypeKind { + None, + Bool, + Address, + Bytes32, + Uint256, + Int256, + String, + Bytes +} + +/// @notice Library for type-safe coercion of the `Variable` struct to concrete types. +/// +/// @dev Ensures that when a `Variable` is cast to a concrete Solidity type, the operation is safe and the +/// underlying type matches what is expected. +/// Provides functions to check types, convert them to strings, and coerce `Variable` instances into +/// both single values and arrays of various types. +/// +/// Usage example: +/// ```solidity +/// import {LibVariable} from "./LibVariable.sol"; +/// +/// contract MyContract { +/// using LibVariable for Variable; +/// StdConfig config; // Assume 'config' is an instance of `StdConfig` and has already been loaded. +/// +/// function readValues() public { +/// // Retrieve a 'uint256' value from the config. +/// uint256 myNumber = config.get("important_number").toUint256(); +/// +/// // Would revert with `TypeMismatch` as 'important_number' isn't a `uint256` in the config file. +/// // string memory notANumber = config.get("important_number").toString(); +/// +/// // Retrieve a address array from the config. +/// string[] memory admins = config.get("whitelisted_admins").toAddressArray(); +/// } +/// } +/// ``` +library LibVariable { + error NotInitialized(); + error TypeMismatch(string expected, string actual); + error UnsafeCast(string message); + + // -- TYPE HELPERS ---------------------------------------------------- + + /// @notice Compares two Type instances for equality. + function isEqual(Type memory self, Type memory other) internal pure returns (bool) { + return self.kind == other.kind && self.isArray == other.isArray; + } + + /// @notice Compares two Type instances for equality. Reverts if they are not equal. + function assertEq(Type memory self, Type memory other) internal pure { + if (!isEqual(self, other)) { + revert TypeMismatch(toString(other), toString(self)); + } + } + + /// @notice Converts a Type struct to its full string representation (i.e. "uint256[]"). + function toString(Type memory self) internal pure returns (string memory) { + string memory tyStr = toString(self.kind); + if (!self.isArray || self.kind == TypeKind.None) { + return tyStr; + } else { + return string.concat(tyStr, "[]"); + } + } + + /// @dev Converts a `TypeKind` enum to its base string representation. + function toString(TypeKind self) internal pure returns (string memory) { + if (self == TypeKind.Bool) return "bool"; + if (self == TypeKind.Address) return "address"; + if (self == TypeKind.Bytes32) return "bytes32"; + if (self == TypeKind.Uint256) return "uint256"; + if (self == TypeKind.Int256) return "int256"; + if (self == TypeKind.String) return "string"; + if (self == TypeKind.Bytes) return "bytes"; + return "none"; + } + + /// @dev Converts a `TypeKind` enum to its base string representation. + function toTomlKey(TypeKind self) internal pure returns (string memory) { + if (self == TypeKind.Bool) return "bool"; + if (self == TypeKind.Address) return "address"; + if (self == TypeKind.Bytes32) return "bytes32"; + if (self == TypeKind.Uint256) return "uint"; + if (self == TypeKind.Int256) return "int"; + if (self == TypeKind.String) return "string"; + if (self == TypeKind.Bytes) return "bytes"; + return "none"; + } + + // -- VARIABLE HELPERS ---------------------------------------------------- + + /// @dev Checks if a `Variable` has been initialized and matches the expected type reverting if not. + modifier check(Variable memory self, Type memory expected) { + assertExists(self); + assertEq(self.ty, expected); + _; + } + + /// @dev Checks if a `Variable` has been initialized, reverting if not. + function assertExists(Variable memory self) public pure { + if (self.ty.kind == TypeKind.None) { + revert NotInitialized(); + } + } + + // -- VARIABLE COERCION FUNCTIONS (SINGLE VALUES) -------------------------- + + /// @notice Coerces a `Variable` to a `bool` value. + function toBool(Variable memory self) internal pure check(self, Type(TypeKind.Bool, false)) returns (bool) { + return abi.decode(self.data, (bool)); + } + + /// @notice Coerces a `Variable` to an `address` value. + function toAddress(Variable memory self) + internal + pure + check(self, Type(TypeKind.Address, false)) + returns (address) + { + return abi.decode(self.data, (address)); + } + + /// @notice Coerces a `Variable` to a `bytes32` value. + function toBytes32(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes32, false)) + returns (bytes32) + { + return abi.decode(self.data, (bytes32)); + } + + /// @notice Coerces a `Variable` to a `uint256` value. + function toUint256(Variable memory self) + internal + pure + check(self, Type(TypeKind.Uint256, false)) + returns (uint256) + { + return abi.decode(self.data, (uint256)); + } + + /// @notice Coerces a `Variable` to a `uint128` value, checking for overflow. + function toUint128(Variable memory self) internal pure returns (uint128) { + uint256 value = self.toUint256(); + if (value > type(uint128).max) { + revert UnsafeCast("value does not fit in 'uint128'"); + } + return uint128(value); + } + + /// @notice Coerces a `Variable` to a `uint64` value, checking for overflow. + function toUint64(Variable memory self) internal pure returns (uint64) { + uint256 value = self.toUint256(); + if (value > type(uint64).max) { + revert UnsafeCast("value does not fit in 'uint64'"); + } + return uint64(value); + } + + /// @notice Coerces a `Variable` to a `uint32` value, checking for overflow. + function toUint32(Variable memory self) internal pure returns (uint32) { + uint256 value = self.toUint256(); + if (value > type(uint32).max) { + revert UnsafeCast("value does not fit in 'uint32'"); + } + return uint32(value); + } + + /// @notice Coerces a `Variable` to a `uint16` value, checking for overflow. + function toUint16(Variable memory self) internal pure returns (uint16) { + uint256 value = self.toUint256(); + if (value > type(uint16).max) { + revert UnsafeCast("value does not fit in 'uint16'"); + } + return uint16(value); + } + + /// @notice Coerces a `Variable` to a `uint8` value, checking for overflow. + function toUint8(Variable memory self) internal pure returns (uint8) { + uint256 value = self.toUint256(); + if (value > type(uint8).max) { + revert UnsafeCast("value does not fit in 'uint8'"); + } + return uint8(value); + } + + /// @notice Coerces a `Variable` to an `int256` value. + function toInt256(Variable memory self) internal pure check(self, Type(TypeKind.Int256, false)) returns (int256) { + return abi.decode(self.data, (int256)); + } + + /// @notice Coerces a `Variable` to an `int128` value, checking for overflow/underflow. + function toInt128(Variable memory self) internal pure returns (int128) { + int256 value = self.toInt256(); + if (value > type(int128).max || value < type(int128).min) { + revert UnsafeCast("value does not fit in 'int128'"); + } + return int128(value); + } + + /// @notice Coerces a `Variable` to an `int64` value, checking for overflow/underflow. + function toInt64(Variable memory self) internal pure returns (int64) { + int256 value = self.toInt256(); + if (value > type(int64).max || value < type(int64).min) { + revert UnsafeCast("value does not fit in 'int64'"); + } + return int64(value); + } + + /// @notice Coerces a `Variable` to an `int32` value, checking for overflow/underflow. + function toInt32(Variable memory self) internal pure returns (int32) { + int256 value = self.toInt256(); + if (value > type(int32).max || value < type(int32).min) { + revert UnsafeCast("value does not fit in 'int32'"); + } + return int32(value); + } + + /// @notice Coerces a `Variable` to an `int16` value, checking for overflow/underflow. + function toInt16(Variable memory self) internal pure returns (int16) { + int256 value = self.toInt256(); + if (value > type(int16).max || value < type(int16).min) { + revert UnsafeCast("value does not fit in 'int16'"); + } + return int16(value); + } + + /// @notice Coerces a `Variable` to an `int8` value, checking for overflow/underflow. + function toInt8(Variable memory self) internal pure returns (int8) { + int256 value = self.toInt256(); + if (value > type(int8).max || value < type(int8).min) { + revert UnsafeCast("value does not fit in 'int8'"); + } + return int8(value); + } + + /// @notice Coerces a `Variable` to a `string` value. + function toString(Variable memory self) + internal + pure + check(self, Type(TypeKind.String, false)) + returns (string memory) + { + return abi.decode(self.data, (string)); + } + + /// @notice Coerces a `Variable` to a `bytes` value. + function toBytes(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes, false)) + returns (bytes memory) + { + return abi.decode(self.data, (bytes)); + } + + // -- VARIABLE COERCION FUNCTIONS (ARRAYS) --------------------------------- + + /// @notice Coerces a `Variable` to a `bool` array. + function toBoolArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bool, true)) + returns (bool[] memory) + { + return abi.decode(self.data, (bool[])); + } + + /// @notice Coerces a `Variable` to an `address` array. + function toAddressArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Address, true)) + returns (address[] memory) + { + return abi.decode(self.data, (address[])); + } + + /// @notice Coerces a `Variable` to a `bytes32` array. + function toBytes32Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes32, true)) + returns (bytes32[] memory) + { + return abi.decode(self.data, (bytes32[])); + } + + /// @notice Coerces a `Variable` to a `uint256` array. + function toUint256Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Uint256, true)) + returns (uint256[] memory) + { + return abi.decode(self.data, (uint256[])); + } + + /// @notice Coerces a `Variable` to a `uint128` array, checking for overflow. + function toUint128Array(Variable memory self) internal pure returns (uint128[] memory) { + uint256[] memory values = self.toUint256Array(); + uint128[] memory result = new uint128[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint128).max) { + revert UnsafeCast("value in array does not fit in 'uint128'"); + } + result[i] = uint128(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint64` array, checking for overflow. + function toUint64Array(Variable memory self) internal pure returns (uint64[] memory) { + uint256[] memory values = self.toUint256Array(); + uint64[] memory result = new uint64[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint64).max) { + revert UnsafeCast("value in array does not fit in 'uint64'"); + } + result[i] = uint64(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint32` array, checking for overflow. + function toUint32Array(Variable memory self) internal pure returns (uint32[] memory) { + uint256[] memory values = self.toUint256Array(); + uint32[] memory result = new uint32[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint32).max) { + revert UnsafeCast("value in array does not fit in 'uint32'"); + } + result[i] = uint32(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint16` array, checking for overflow. + function toUint16Array(Variable memory self) internal pure returns (uint16[] memory) { + uint256[] memory values = self.toUint256Array(); + uint16[] memory result = new uint16[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint16).max) { + revert UnsafeCast("value in array does not fit in 'uint16'"); + } + result[i] = uint16(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `uint8` array, checking for overflow. + function toUint8Array(Variable memory self) internal pure returns (uint8[] memory) { + uint256[] memory values = self.toUint256Array(); + uint8[] memory result = new uint8[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(uint8).max) { + revert UnsafeCast("value in array does not fit in 'uint8'"); + } + result[i] = uint8(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to an `int256` array. + function toInt256Array(Variable memory self) + internal + pure + check(self, Type(TypeKind.Int256, true)) + returns (int256[] memory) + { + return abi.decode(self.data, (int256[])); + } + + /// @notice Coerces a `Variable` to a `int128` array, checking for overflow/underflow. + function toInt128Array(Variable memory self) internal pure returns (int128[] memory) { + int256[] memory values = self.toInt256Array(); + int128[] memory result = new int128[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int128).max || values[i] < type(int128).min) { + revert UnsafeCast("value in array does not fit in 'int128'"); + } + result[i] = int128(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int64` array, checking for overflow/underflow. + function toInt64Array(Variable memory self) internal pure returns (int64[] memory) { + int256[] memory values = self.toInt256Array(); + int64[] memory result = new int64[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int64).max || values[i] < type(int64).min) { + revert UnsafeCast("value in array does not fit in 'int64'"); + } + result[i] = int64(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int32` array, checking for overflow/underflow. + function toInt32Array(Variable memory self) internal pure returns (int32[] memory) { + int256[] memory values = self.toInt256Array(); + int32[] memory result = new int32[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int32).max || values[i] < type(int32).min) { + revert UnsafeCast("value in array does not fit in 'int32'"); + } + result[i] = int32(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int16` array, checking for overflow/underflow. + function toInt16Array(Variable memory self) internal pure returns (int16[] memory) { + int256[] memory values = self.toInt256Array(); + int16[] memory result = new int16[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int16).max || values[i] < type(int16).min) { + revert UnsafeCast("value in array does not fit in 'int16'"); + } + result[i] = int16(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `int8` array, checking for overflow/underflow. + function toInt8Array(Variable memory self) internal pure returns (int8[] memory) { + int256[] memory values = self.toInt256Array(); + int8[] memory result = new int8[](values.length); + for (uint256 i = 0; i < values.length; i++) { + if (values[i] > type(int8).max || values[i] < type(int8).min) { + revert UnsafeCast("value in array does not fit in 'int8'"); + } + result[i] = int8(values[i]); + } + return result; + } + + /// @notice Coerces a `Variable` to a `string` array. + function toStringArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.String, true)) + returns (string[] memory) + { + return abi.decode(self.data, (string[])); + } + + /// @notice Coerces a `Variable` to a `bytes` array. + function toBytesArray(Variable memory self) + internal + pure + check(self, Type(TypeKind.Bytes, true)) + returns (bytes[] memory) + { + return abi.decode(self.data, (bytes[])); + } +} diff --git a/src/StdChains.sol b/src/StdChains.sol index 0a872e7b9..3bc5f43af 100644 --- a/src/StdChains.sol +++ b/src/StdChains.sol @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.9.0; +pragma experimental ABIEncoderV2; import {VmSafe} from "./Vm.sol"; diff --git a/src/StdConfig.sol b/src/StdConfig.sol new file mode 100644 index 000000000..288fc3881 --- /dev/null +++ b/src/StdConfig.sol @@ -0,0 +1,612 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +import {VmSafe} from "./Vm.sol"; +import {Variable, Type, TypeKind, LibVariable} from "./LibVariable.sol"; + +/// @notice A contract that parses a toml configuration file and load its +/// variables into storage, automatically casting them, on deployment. +/// +/// @dev This contract assumes a toml structure where top-level keys +/// represent chain ids or aliases. Under each chain key, variables are +/// organized by type in separate sub-tables like `[.]`, where +/// type must be: `bool`, `address`, `bytes32`, `uint`, `ìnt`, `string`, or `bytes`. +/// +/// Supported format: +/// ``` +/// [mainnet] +/// endpoint_url = "${MAINNET_RPC}" +/// +/// [mainnet.bool] +/// is_live = true +/// +/// [mainnet.address] +/// weth = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" +/// whitelisted_admins = [ +/// "${MAINNET_ADMIN}", +/// "0x00000000000000000000000000000000deadbeef", +/// "0x000000000000000000000000000000c0ffeebabe" +/// ] +/// +/// [mainnet.uint] +/// important_number = 123 +/// ``` +contract StdConfig { + using LibVariable for Type; + using LibVariable for TypeKind; + + VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code"))))); + + /// @dev Types: `bool`, `address`, `bytes32`, `uint`, `ìnt`, `string`, `bytes`. + uint8 private constant NUM_TYPES = 7; + + // -- ERRORS --------------------------------------------------------------- + + error AlreadyInitialized(string key); + error InvalidChainKey(string aliasOrId); + error ChainNotInitialized(uint256 chainId); + error UnableToParseVariable(string key); + error WriteToFileInForbiddenCtxt(); + + // -- STORAGE (CACHE FROM CONFIG FILE) ------------------------------------ + + /// @dev Path to the loaded TOML configuration file. + string private _filePath; + + /// @dev List of top-level keys found in the TOML file, assumed to be chain names/aliases. + string[] private _chainKeys; + + /// @dev Storage for the configured RPC URL for each chain. + mapping(uint256 => string) private _rpcOf; + + /// @dev Storage for values, organized by chain ID and variable key. + mapping(uint256 => mapping(string => bytes)) private _dataOf; + + /// @dev Type cache for runtime checking when casting. + mapping(uint256 => mapping(string => Type)) private _typeOf; + + /// @dev When enabled, `set` will always write updates back to the configuration file. + /// Can only be enabled in a scripting context to prevent file corruption from + /// concurrent I/O access, as tests run in parallel. + bool private _writeToFile; + + // -- CONSTRUCTOR ---------------------------------------------------------- + + /// @notice Reads the TOML file and iterates through each top-level key, which is + /// assumed to be a chain name or ID. For each chain, it caches its RPC + /// endpoint and all variables defined in typed sub-tables like `[.]`, + /// where type must be: `bool`, `address`, `uint`, `bytes32`, `string`, or `bytes`. + /// + /// The constructor attempts to parse each variable first as a single value, + /// and if that fails, as an array of that type. If a variable cannot be + /// parsed as either, the constructor will revert with an error. + /// + /// @param configFilePath: The local path to the TOML configuration file. + /// @param writeToFile: Whether to write updates back to the TOML file. Only for scrips. + constructor(string memory configFilePath, bool writeToFile) { + if (writeToFile && !vm.isContext(VmSafe.ForgeContext.ScriptGroup)) { + revert WriteToFileInForbiddenCtxt(); + } + + _filePath = configFilePath; + _writeToFile = writeToFile; + string memory content = vm.resolveEnv(vm.readFile(configFilePath)); + string[] memory chain_keys = vm.parseTomlKeys(content, "$"); + + // Cache the entire configuration to storage + for (uint256 i = 0; i < chain_keys.length; i++) { + string memory chain_key = chain_keys[i]; + // Ignore top-level keys that are not tables + if (vm.parseTomlKeys(content, string.concat("$.", chain_key)).length == 0) { + continue; + } + uint256 chainId = resolveChainId(chain_key); + _chainKeys.push(chain_key); + + // Cache the configure rpc endpoint for that chain. + // Falls back to `[rpc_endpoints]`. Panics if no rpc endpoint is configured. + try vm.parseTomlString(content, string.concat("$.", chain_key, ".endpoint_url")) returns (string memory url) + { + _rpcOf[chainId] = vm.resolveEnv(url); + } catch { + _rpcOf[chainId] = vm.resolveEnv(vm.rpcUrl(chain_key)); + } + + // Iterate through all the available `TypeKind`s (except `None`) to create the sub-section paths + for (uint8 t = 1; t <= NUM_TYPES; t++) { + TypeKind ty = TypeKind(t); + string memory typePath = string.concat("$.", chain_key, ".", ty.toTomlKey()); + + try vm.parseTomlKeys(content, typePath) returns (string[] memory keys) { + for (uint256 j = 0; j < keys.length; j++) { + string memory key = keys[j]; + if (_typeOf[chainId][key].kind == TypeKind.None) { + _loadAndCacheValue(content, string.concat(typePath, ".", key), chainId, key, ty); + } else { + revert AlreadyInitialized(key); + } + } + } catch {} // Section does not exist, ignore. + } + } + } + + function _loadAndCacheValue( + string memory content, + string memory path, + uint256 chainId, + string memory key, + TypeKind ty + ) private { + bool success = false; + if (ty == TypeKind.Bool) { + try vm.parseTomlBool(content, path) returns (bool val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bool, false); + success = true; + } catch { + try vm.parseTomlBoolArray(content, path) returns (bool[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bool, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Address) { + try vm.parseTomlAddress(content, path) returns (address val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Address, false); + success = true; + } catch { + try vm.parseTomlAddressArray(content, path) returns (address[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Address, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Bytes32) { + try vm.parseTomlBytes32(content, path) returns (bytes32 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes32, false); + success = true; + } catch { + try vm.parseTomlBytes32Array(content, path) returns (bytes32[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes32, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Uint256) { + try vm.parseTomlUint(content, path) returns (uint256 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Uint256, false); + success = true; + } catch { + try vm.parseTomlUintArray(content, path) returns (uint256[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Uint256, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Int256) { + try vm.parseTomlInt(content, path) returns (int256 val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Int256, false); + success = true; + } catch { + try vm.parseTomlIntArray(content, path) returns (int256[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Int256, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.Bytes) { + try vm.parseTomlBytes(content, path) returns (bytes memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes, false); + success = true; + } catch { + try vm.parseTomlBytesArray(content, path) returns (bytes[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.Bytes, true); + success = true; + } catch {} + } + } else if (ty == TypeKind.String) { + try vm.parseTomlString(content, path) returns (string memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.String, false); + success = true; + } catch { + try vm.parseTomlStringArray(content, path) returns (string[] memory val) { + _dataOf[chainId][key] = abi.encode(val); + _typeOf[chainId][key] = Type(TypeKind.String, true); + success = true; + } catch {} + } + } + + if (!success) { + revert UnableToParseVariable(key); + } + } + + // -- HELPER FUNCTIONS ----------------------------------------------------- + + /// @notice Enable or disable automatic writing to the TOML file on `set`. + /// Can only be enabled when scripting. + function writeUpdatesBackToFile(bool enabled) public { + if (enabled && !vm.isContext(VmSafe.ForgeContext.ScriptGroup)) { + revert WriteToFileInForbiddenCtxt(); + } + + _writeToFile = enabled; + } + + /// @notice Resolves a chain alias or a chain id string to its numerical chain id. + /// @param aliasOrId The string representing the chain alias (i.e. "mainnet") or a numerical ID (i.e. "1"). + /// @return The numerical chain ID. + /// @dev It first attempts to parse the input as a number. If that fails, it uses `vm.getChain` to resolve a named alias. + /// Reverts if the alias is not valid or not a number. + function resolveChainId(string memory aliasOrId) public view returns (uint256) { + try vm.parseUint(aliasOrId) returns (uint256 chainId) { + return chainId; + } catch { + try vm.getChain(aliasOrId) returns (VmSafe.Chain memory chainInfo) { + return chainInfo.chainId; + } catch { + revert InvalidChainKey(aliasOrId); + } + } + } + + /// @dev Retrieves the chain key/alias from the configuration based on the chain ID. + function _getChainKeyFromId(uint256 chainId) private view returns (string memory) { + for (uint256 i = 0; i < _chainKeys.length; i++) { + if (resolveChainId(_chainKeys[i]) == chainId) { + return _chainKeys[i]; + } + } + revert ChainNotInitialized(chainId); + } + + /// @dev Ensures type consistency when setting a value - prevents changing types unless uninitialized. + /// Updates type only when the previous type was `None`. + function _ensureTypeConsistency(uint256 chainId, string memory key, Type memory ty) private { + Type memory current = _typeOf[chainId][key]; + + if (current.kind == TypeKind.None) { + _typeOf[chainId][key] = ty; + } else { + current.assertEq(ty); + } + } + + /// @dev Wraps a string in double quotes for JSON compatibility. + function _quote(string memory s) private pure returns (string memory) { + return string.concat('"', s, '"'); + } + + /// @dev Writes a JSON-formatted value to a specific key in the TOML file. + /// @param chainId The chain id to write under. + /// @param ty The type category ('bool', 'address', 'uint', 'bytes32', 'string', or 'bytes'). + /// @param key The variable key name. + /// @param jsonValue The JSON-formatted value to write. + function _writeToToml(uint256 chainId, string memory ty, string memory key, string memory jsonValue) private { + string memory chainKey = _getChainKeyFromId(chainId); + string memory valueKey = string.concat("$.", chainKey, ".", ty, ".", key); + vm.writeToml(jsonValue, _filePath, valueKey); + } + + // -- GETTER FUNCTIONS ----------------------------------------------------- + + /// @dev Reads a variable for a given chain id and key, and returns it in a generic container. + /// The caller should use `LibVariable` to safely coerce the type. + /// Example: `uint256 myVar = config.get("my_key").toUint256();` + /// + /// @param chain_id The chain ID to read from. + /// @param key The key of the variable to retrieve. + /// @return `Variable` struct containing the type and the ABI-encoded value. + function get(uint256 chain_id, string memory key) public view returns (Variable memory) { + return Variable(_typeOf[chain_id][key], _dataOf[chain_id][key]); + } + + /// @dev Reads a variable for the current chain and a given key, and returns it in a generic container. + /// The caller should use `LibVariable` to safely coerce the type. + /// Example: `uint256 myVar = config.get("my_key").toUint256();` + /// + /// @param key The key of the variable to retrieve. + /// @return `Variable` struct containing the type and the ABI-encoded value. + function get(string memory key) public view returns (Variable memory) { + return get(vm.getChainId(), key); + } + + /// @notice Returns the numerical chain ids for all configured chains. + function getChainIds() public view returns (uint256[] memory) { + string[] memory keys = _chainKeys; + + uint256[] memory ids = new uint256[](keys.length); + for (uint256 i = 0; i < keys.length; i++) { + ids[i] = resolveChainId(keys[i]); + } + + return ids; + } + + /// @notice Reads the RPC URL for a specific chain id. + function getRpcUrl(uint256 chainId) public view returns (string memory) { + return _rpcOf[chainId]; + } + + /// @notice Reads the RPC URL for the current chain. + function getRpcUrl() public view returns (string memory) { + return _rpcOf[vm.getChainId()]; + } + + // -- SETTER FUNCTIONS (SINGLE VALUES) ------------------------------------- + + /// @notice Sets a boolean value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bool value) public { + Type memory ty = Type(TypeKind.Bool, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets a boolean value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bool value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an address value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, address value) public { + Type memory ty = Type(TypeKind.Address, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets an address value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, address value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes32 value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes32 value) public { + Type memory ty = Type(TypeKind.Bytes32, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets a bytes32 value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes32 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a uint256 value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, uint256 value) public { + Type memory ty = Type(TypeKind.Uint256, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets a uint256 value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, uint256 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an int256 value for a given key and chain ID. + function set(uint256 chainId, string memory key, int256 value) public { + Type memory ty = Type(TypeKind.Int256, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, vm.toString(value)); + } + + /// @notice Sets an int256 value for a given key on the current chain. + function set(string memory key, int256 value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a string value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, string memory value) public { + Type memory ty = Type(TypeKind.String, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(value)); + } + + /// @notice Sets a string value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, string memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes value for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes memory value) public { + Type memory ty = Type(TypeKind.Bytes, false); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) _writeToToml(chainId, ty.kind.toTomlKey(), key, _quote(vm.toString(value))); + } + + /// @notice Sets a bytes value for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes memory value) public { + set(vm.getChainId(), key, value); + } + + // -- SETTER FUNCTIONS (ARRAYS) -------------------------------------------- + + /// @notice Sets a boolean array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bool[] memory value) public { + Type memory ty = Type(TypeKind.Bool, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a boolean array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bool[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets an address array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, address[] memory value) public { + Type memory ty = Type(TypeKind.Address, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets an address array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, address[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes32 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes32[] memory value) public { + Type memory ty = Type(TypeKind.Bytes32, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a bytes32 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes32[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a uint256 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, uint256[] memory value) public { + Type memory ty = Type(TypeKind.Uint256, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a uint256 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, uint256[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a int256 array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, int256[] memory value) public { + Type memory ty = Type(TypeKind.Int256, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, vm.toString(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a int256 array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, int256[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a string array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, string[] memory value) public { + Type memory ty = Type(TypeKind.String, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(value[i])); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a string array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, string[] memory value) public { + set(vm.getChainId(), key, value); + } + + /// @notice Sets a bytes array for a given key and chain ID. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(uint256 chainId, string memory key, bytes[] memory value) public { + Type memory ty = Type(TypeKind.Bytes, true); + _ensureTypeConsistency(chainId, key, ty); + _dataOf[chainId][key] = abi.encode(value); + if (_writeToFile) { + string memory json = "["; + for (uint256 i = 0; i < value.length; i++) { + json = string.concat(json, _quote(vm.toString(value[i]))); + if (i < value.length - 1) json = string.concat(json, ","); + } + json = string.concat(json, "]"); + _writeToToml(chainId, ty.kind.toTomlKey(), key, json); + } + } + + /// @notice Sets a bytes array for a given key on the current chain. + /// @dev Sets the cached value in storage and writes the change back to the TOML file if `autoWrite` is enabled. + function set(string memory key, bytes[] memory value) public { + set(vm.getChainId(), key, value); + } +} diff --git a/src/Vm.sol b/src/Vm.sol index 4a2fede80..cd883706a 100644 --- a/src/Vm.sol +++ b/src/Vm.sol @@ -602,13 +602,16 @@ interface VmSafe { /// Returns true if `forge` command was executed in given context. function isContext(ForgeContext context) external view returns (bool result); + /// Resolves the env variable placeholders of a given input string. + function resolveEnv(string calldata input) external returns (string memory); + /// Sets environment variables. function setEnv(string calldata name, string calldata value) external; // ======== EVM ======== /// Gets all accessed reads and write slot from a `vm.record` session, for a given address. - function accesses(address target) external returns (bytes32[] memory readSlots, bytes32[] memory writeSlots); + function accesses(address target) external view returns (bytes32[] memory readSlots, bytes32[] memory writeSlots); /// Gets the address for a given private key. function addr(uint256 privateKey) external pure returns (address keyAddr); @@ -616,6 +619,7 @@ interface VmSafe { /// Gets all the logs according to specified filter. function eth_getLogs(uint256 fromBlock, uint256 toBlock, address target, bytes32[] calldata topics) external + view returns (EthGetLogs[] memory logs); /// Gets the current `block.blobbasefee`. @@ -636,30 +640,37 @@ interface VmSafe { /// See https://github.com/foundry-rs/foundry/issues/6180 function getBlockTimestamp() external view returns (uint256 timestamp); + /// Gets the current `block.chainid` of the currently selected environment. + /// You should use this instead of `block.chainid` if you use `vm.selectFork` or `vm.createSelectFork`, as `block.chainid` could be assumed + /// to be constant across a transaction, and as a result will get optimized out by the compiler. + /// See https://github.com/foundry-rs/foundry/issues/6180 + function getChainId() external view returns (uint256 blockChainId); + /// Gets the map key and parent of a mapping at a given slot, for a given address. function getMappingKeyAndParentOf(address target, bytes32 elementSlot) external + view returns (bool found, bytes32 key, bytes32 parent); /// Gets the number of elements in the mapping at the given slot, for a given address. - function getMappingLength(address target, bytes32 mappingSlot) external returns (uint256 length); + function getMappingLength(address target, bytes32 mappingSlot) external view returns (uint256 length); /// Gets the elements at index idx of the mapping at the given slot, for a given address. The /// index must be less than the length of the mapping (i.e. the number of keys in the mapping). - function getMappingSlotAt(address target, bytes32 mappingSlot, uint256 idx) external returns (bytes32 value); + function getMappingSlotAt(address target, bytes32 mappingSlot, uint256 idx) external view returns (bytes32 value); /// Gets the nonce of an account. function getNonce(address account) external view returns (uint64 nonce); /// Get the nonce of a `Wallet`. - function getNonce(Wallet calldata wallet) external returns (uint64 nonce); + function getNonce(Wallet calldata wallet) external view returns (uint64 nonce); /// Gets the RLP encoded block header for a given block number. /// Returns the block header in the same format as `cast block --raw`. function getRawBlockHeader(uint256 blockNumber) external view returns (bytes memory rlpHeader); /// Gets all the recorded logs. - function getRecordedLogs() external returns (Log[] memory logs); + function getRecordedLogs() external view returns (Log[] memory logs); /// Returns state diffs from current `vm.startStateDiffRecording` session. function getStateDiff() external view returns (string memory diff); @@ -1118,6 +1129,7 @@ interface VmSafe { /// Write a serialized JSON object to an **existing** JSON file, replacing a value with key = /// This is useful to replace a specific value of a JSON file, without having to parse the entire thing. + /// This cheatcode will create new keys if they didn't previously exist. function writeJson(string calldata json, string calldata path, string calldata valueKey) external; /// Checks if `key` exists in a JSON object @@ -1154,7 +1166,7 @@ interface VmSafe { function broadcast(uint256 privateKey) external; /// Returns addresses of available unlocked wallets in the script environment. - function getWallets() external returns (address[] memory wallets); + function getWallets() external view returns (address[] memory wallets); /// Sign an EIP-7702 authorization and designate the next call as an EIP-7702 transaction function signAndAttachDelegation(address implementation, uint256 privateKey) @@ -1207,7 +1219,7 @@ interface VmSafe { // ======== String ======== /// Returns true if `search` is found in `subject`, false otherwise. - function contains(string calldata subject, string calldata search) external returns (bool result); + function contains(string calldata subject, string calldata search) external pure returns (bool result); /// Returns the index of the first occurrence of a `key` in an `input` string. /// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `key` is not found. @@ -1843,10 +1855,17 @@ interface VmSafe { /// Takes serialized JSON, converts to TOML and write a serialized TOML table to an **existing** TOML file, replacing a value with key = /// This is useful to replace a specific value of a TOML file, without having to parse the entire thing. + /// This cheatcode will create new keys if they didn't previously exist. function writeToml(string calldata json, string calldata path, string calldata valueKey) external; // ======== Utilities ======== + /// Returns an uint256 value bounded in given range and different from the current one. + function bound(uint256 current, uint256 min, uint256 max) external view returns (uint256); + + /// Returns an int256 value bounded in given range and different from the current one. + function bound(int256 current, int256 min, int256 max) external view returns (int256); + /// Compute the address of a contract created with CREATE2 using the given CREATE2 deployer. function computeCreate2Address(bytes32 salt, bytes32 initCodeHash, address deployer) external @@ -2171,7 +2190,7 @@ interface Vm is VmSafe { function prevrandao(uint256 newPrevrandao) external; /// Reads the current `msg.sender` and `tx.origin` from state and reports if there is any active caller modification. - function readCallers() external returns (CallerMode callerMode, address msgSender, address txOrigin); + function readCallers() external view returns (CallerMode callerMode, address msgSender, address txOrigin); /// Resets the nonce of an account to 0 for EOAs and 1 for contract accounts. function resetNonce(address account) external; diff --git a/test/Config.t.sol b/test/Config.t.sol new file mode 100644 index 000000000..8e2342cad --- /dev/null +++ b/test/Config.t.sol @@ -0,0 +1,352 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +import {Test} from "../src/Test.sol"; +import {Config} from "../src/Config.sol"; +import {StdConfig} from "../src/StdConfig.sol"; + +contract ConfigTest is Test, Config { + function setUp() public { + vm.setEnv("MAINNET_RPC", "https://eth.llamarpc.com"); + vm.setEnv("WETH_MAINNET", "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"); + vm.setEnv("OPTIMISM_RPC", "https://mainnet.optimism.io"); + vm.setEnv("WETH_OPTIMISM", "0x4200000000000000000000000000000000000006"); + } + + function test_loadConfig() public { + // Deploy the config contract with the test fixture. + _loadConfig("./test/fixtures/config.toml", false); + + // -- MAINNET -------------------------------------------------------------- + + // Read and assert RPC URL for Mainnet (chain ID 1) + assertEq(config.getRpcUrl(1), "https://eth.llamarpc.com"); + + // Read and assert boolean values + assertTrue(config.get(1, "is_live").toBool()); + bool[] memory bool_array = config.get(1, "bool_array").toBoolArray(); + assertTrue(bool_array[0]); + assertFalse(bool_array[1]); + + // Read and assert address values + assertEq(config.get(1, "weth").toAddress(), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); + address[] memory address_array = config.get(1, "deps").toAddressArray(); + assertEq(address_array[0], 0x0000000000000000000000000000000000000000); + assertEq(address_array[1], 0x1111111111111111111111111111111111111111); + + // Read and assert bytes32 values + assertEq(config.get(1, "word").toBytes32(), bytes32(uint256(1234))); + bytes32[] memory bytes32_array = config.get(1, "word_array").toBytes32Array(); + assertEq(bytes32_array[0], bytes32(uint256(5678))); + assertEq(bytes32_array[1], bytes32(uint256(9999))); + + // Read and assert uint values + assertEq(config.get(1, "number").toUint256(), 1234); + uint256[] memory uint_array = config.get(1, "number_array").toUint256Array(); + assertEq(uint_array[0], 5678); + assertEq(uint_array[1], 9999); + + // Read and assert int values + assertEq(config.get(1, "signed_number").toInt256(), -1234); + int256[] memory int_array = config.get(1, "signed_number_array").toInt256Array(); + assertEq(int_array[0], -5678); + assertEq(int_array[1], 9999); + + // Read and assert bytes values + assertEq(config.get(1, "b").toBytes(), hex"abcd"); + bytes[] memory bytes_array = config.get(1, "b_array").toBytesArray(); + assertEq(bytes_array[0], hex"dead"); + assertEq(bytes_array[1], hex"beef"); + + // Read and assert string values + assertEq(config.get(1, "str").toString(), "foo"); + string[] memory string_array = config.get(1, "str_array").toStringArray(); + assertEq(string_array[0], "bar"); + assertEq(string_array[1], "baz"); + + // -- OPTIMISM ------------------------------------------------------------ + + // Read and assert RPC URL for Optimism (chain ID 10) + assertEq(config.getRpcUrl(10), "https://mainnet.optimism.io"); + + // Read and assert boolean values + assertFalse(config.get(10, "is_live").toBool()); + bool_array = config.get(10, "bool_array").toBoolArray(); + assertFalse(bool_array[0]); + assertTrue(bool_array[1]); + + // Read and assert address values + assertEq(config.get(10, "weth").toAddress(), 0x4200000000000000000000000000000000000006); + address_array = config.get(10, "deps").toAddressArray(); + assertEq(address_array[0], 0x2222222222222222222222222222222222222222); + assertEq(address_array[1], 0x3333333333333333333333333333333333333333); + + // Read and assert bytes32 values + assertEq(config.get(10, "word").toBytes32(), bytes32(uint256(9999))); + bytes32_array = config.get(10, "word_array").toBytes32Array(); + assertEq(bytes32_array[0], bytes32(uint256(1234))); + assertEq(bytes32_array[1], bytes32(uint256(5678))); + + // Read and assert uint values + assertEq(config.get(10, "number").toUint256(), 9999); + uint_array = config.get(10, "number_array").toUint256Array(); + assertEq(uint_array[0], 1234); + assertEq(uint_array[1], 5678); + + // Read and assert int values + assertEq(config.get(10, "signed_number").toInt256(), 9999); + int_array = config.get(10, "signed_number_array").toInt256Array(); + assertEq(int_array[0], -1234); + assertEq(int_array[1], -5678); + + // Read and assert bytes values + assertEq(config.get(10, "b").toBytes(), hex"dcba"); + bytes_array = config.get(10, "b_array").toBytesArray(); + assertEq(bytes_array[0], hex"c0ffee"); + assertEq(bytes_array[1], hex"babe"); + + // Read and assert string values + assertEq(config.get(10, "str").toString(), "alice"); + string_array = config.get(10, "str_array").toStringArray(); + assertEq(string_array[0], "bob"); + assertEq(string_array[1], "charlie"); + } + + function test_loadConfigAndForks() public { + _loadConfigAndForks("./test/fixtures/config.toml", false); + + // assert that the map of chain id and fork ids is created and that the chain ids actually match + assertEq(forkOf[1], 0); + vm.selectFork(forkOf[1]); + assertEq(vm.getChainId(), 1); + + assertEq(forkOf[10], 1); + vm.selectFork(forkOf[10]); + assertEq(vm.getChainId(), 10); + } + + function test_writeConfig() public { + // Create a temporary copy of the config file to avoid modifying the original. + string memory originalConfig = "./test/fixtures/config.toml"; + string memory testConfig = "./test/fixtures/config.t.toml"; + vm.copyFile(originalConfig, testConfig); + + // Deploy the config contract with the temporary fixture. + _loadConfig(testConfig, false); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + { + // Update a single boolean value and verify the change. + config.set(1, "is_live", false); + + assertFalse(config.get(1, "is_live").toBool()); + + string memory content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live")); + + // Update a single address value and verify the change. + address new_addr = 0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF; + config.set(1, "weth", new_addr); + + assertEq(config.get(1, "weth").toAddress(), new_addr); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlAddress(content, "$.mainnet.address.weth"), new_addr); + + // Update a uint array and verify the change. + uint256[] memory new_numbers = new uint256[](3); + new_numbers[0] = 1; + new_numbers[1] = 2; + new_numbers[2] = 3; + config.set(10, "number_array", new_numbers); + + uint256[] memory updated_numbers_mem = config.get(10, "number_array").toUint256Array(); + assertEq(updated_numbers_mem.length, 3); + assertEq(updated_numbers_mem[0], 1); + assertEq(updated_numbers_mem[1], 2); + assertEq(updated_numbers_mem[2], 3); + + content = vm.readFile(testConfig); + uint256[] memory updated_numbers_disk = vm.parseTomlUintArray(content, "$.optimism.uint.number_array"); + assertEq(updated_numbers_disk.length, 3); + assertEq(updated_numbers_disk[0], 1); + assertEq(updated_numbers_disk[1], 2); + assertEq(updated_numbers_disk[2], 3); + + // Update a string array and verify the change. + string[] memory new_strings = new string[](2); + new_strings[0] = "hello"; + new_strings[1] = "world"; + config.set(1, "str_array", new_strings); + + string[] memory updated_strings_mem = config.get(1, "str_array").toStringArray(); + assertEq(updated_strings_mem.length, 2); + assertEq(updated_strings_mem[0], "hello"); + assertEq(updated_strings_mem[1], "world"); + + content = vm.readFile(testConfig); + string[] memory updated_strings_disk = vm.parseTomlStringArray(content, "$.mainnet.string.str_array"); + assertEq(updated_strings_disk.length, 2); + assertEq(updated_strings_disk[0], "hello"); + assertEq(updated_strings_disk[1], "world"); + + // Create a new uint variable and verify the change. + config.set(1, "new_uint", uint256(42)); + + assertEq(config.get(1, "new_uint").toUint256(), 42); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlUint(content, "$.mainnet.uint.new_uint"), 42); + + // Create a new int variable and verify the change. + config.set(1, "new_int", int256(-42)); + + assertEq(config.get(1, "new_int").toInt256(), -42); + + content = vm.readFile(testConfig); + assertEq(vm.parseTomlInt(content, "$.mainnet.int.new_int"), -42); + + // Create a new int array and verify the change. + int256[] memory new_ints = new int256[](2); + new_ints[0] = -100; + new_ints[1] = 200; + config.set(10, "new_ints", new_ints); + + int256[] memory updated_ints_mem = config.get(10, "new_ints").toInt256Array(); + assertEq(updated_ints_mem.length, 2); + assertEq(updated_ints_mem[0], -100); + assertEq(updated_ints_mem[1], 200); + + content = vm.readFile(testConfig); + int256[] memory updated_ints_disk = vm.parseTomlIntArray(content, "$.optimism.int.new_ints"); + assertEq(updated_ints_disk.length, 2); + assertEq(updated_ints_disk[0], -100); + assertEq(updated_ints_disk[1], 200); + + // Create a new bytes32 array and verify the change. + bytes32[] memory new_words = new bytes32[](2); + new_words[0] = bytes32(uint256(0xDEAD)); + new_words[1] = bytes32(uint256(0xBEEF)); + config.set(10, "new_words", new_words); + + bytes32[] memory updated_words_mem = config.get(10, "new_words").toBytes32Array(); + assertEq(updated_words_mem.length, 2); + assertEq(updated_words_mem[0], new_words[0]); + assertEq(updated_words_mem[1], new_words[1]); + + content = vm.readFile(testConfig); + bytes32[] memory updated_words_disk = vm.parseTomlBytes32Array(content, "$.optimism.bytes32.new_words"); + assertEq(updated_words_disk.length, 2); + assertEq(vm.toString(updated_words_disk[0]), vm.toString(new_words[0])); + assertEq(vm.toString(updated_words_disk[1]), vm.toString(new_words[1])); + } + + // Clean up the temporary file. + vm.removeFile(testConfig); + } + + function test_writeUpdatesBackToFile() public { + // Create a temporary copy of the config file to avoid modifying the original. + string memory originalConfig = "./test/fixtures/config.toml"; + string memory testConfig = "./test/fixtures/write_config.t.toml"; + vm.copyFile(originalConfig, testConfig); + + // Deploy the config contract with `writeToFile = false` (disabled). + _loadConfig(testConfig, false); + + // Update a single boolean value and verify the file is NOT changed. + config.set(1, "is_live", false); + string memory content = vm.readFile(testConfig); + assertTrue(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should not be updated yet"); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + // Update the value again and verify the file IS changed. + config.set(1, "is_live", false); + content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should be updated now"); + + // Disable writing to file. + config.writeUpdatesBackToFile(false); + + // Update the value again and verify the file is NOT changed. + config.set(1, "is_live", true); + content = vm.readFile(testConfig); + assertFalse(vm.parseTomlBool(content, "$.mainnet.bool.is_live"), "File should not be updated again"); + + // Clean up the temporary file. + vm.removeFile(testConfig); + } + + function testRevert_WriteToFileInForbiddenCtxt() public { + // Cannot initialize enabling writing to file unless we are in SCRIPT mode. + vm.expectRevert(StdConfig.WriteToFileInForbiddenCtxt.selector); + _loadConfig("./test/fixtures/config.toml", true); + + // Initialize with `writeToFile = false`. + _loadConfig("./test/fixtures/config.toml", false); + + // Cannot enable writing to file unless we are in SCRIPT mode. + vm.expectRevert(StdConfig.WriteToFileInForbiddenCtxt.selector); + config.writeUpdatesBackToFile(true); + } + + function testRevert_InvalidChainKey() public { + // Create a fixture with an invalid chain key + string memory invalidChainConfig = "./test/fixtures/config_invalid_chain.toml"; + vm.writeFile( + invalidChainConfig, + string.concat( + "[mainnet]\n", + "endpoint_url = \"https://eth.llamarpc.com\"\n", + "\n", + "[mainnet.uint]\n", + "valid_number = 123\n", + "\n", + "# Invalid chain key (not a number and not a valid alias)\n", + "[invalid_chain]\n", + "endpoint_url = \"https://invalid.com\"\n", + "\n", + "[invalid_chain_9999.uint]\n", + "some_value = 456\n" + ) + ); + + vm.expectRevert(abi.encodeWithSelector(StdConfig.InvalidChainKey.selector, "invalid_chain")); + new StdConfig(invalidChainConfig, false); + vm.removeFile(invalidChainConfig); + } + + function testRevert_ChainNotInitialized() public { + _loadConfig("./test/fixtures/config.toml", false); + + // Enable writing to file bypassing the context check. + vm.store(address(config), bytes32(uint256(5)), bytes32(uint256(1))); + + // Try to write a value for a non-existent chain ID + vm.expectRevert(abi.encodeWithSelector(StdConfig.ChainNotInitialized.selector, uint256(999999))); + config.set(999999, "some_key", uint256(123)); + } + + function testRevert_UnableToParseVariable() public { + // Create a temporary fixture with an unparsable variable + string memory badParseConfig = "./test/fixtures/config_bad_parse.toml"; + vm.writeFile( + badParseConfig, + string.concat( + "[mainnet]\n", + "endpoint_url = \"https://eth.llamarpc.com\"\n", + "\n", + "[mainnet.uint]\n", + "bad_value = \"not_a_number\"\n" + ) + ); + + vm.expectRevert(abi.encodeWithSelector(StdConfig.UnableToParseVariable.selector, "bad_value")); + new StdConfig(badParseConfig, false); + vm.removeFile(badParseConfig); + } +} diff --git a/test/LibVariable.t.sol b/test/LibVariable.t.sol new file mode 100644 index 000000000..2fc00a91a --- /dev/null +++ b/test/LibVariable.t.sol @@ -0,0 +1,434 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.13; + +import {Test} from "../src/Test.sol"; +import {Variable, Type, TypeKind, LibVariable} from "../src/LibVariable.sol"; + +contract LibVariableTest is Test { + using LibVariable for Type; + using LibVariable for TypeKind; + + LibVariableHelper internal helper; + + bytes internal expectedErr; + Variable internal uninitVar; + Variable internal boolVar; + Variable internal addressVar; + Variable internal bytes32Var; + Variable internal uintVar; + Variable internal intVar; + Variable internal stringVar; + Variable internal bytesVar; + Variable internal boolArrayVar; + Variable internal addressArrayVar; + Variable internal bytes32ArrayVar; + Variable internal uintArrayVar; + Variable internal intArrayVar; + Variable internal stringArrayVar; + Variable internal bytesArrayVar; + + function setUp() public { + helper = new LibVariableHelper(); + + // UNINITIALIZED + uninitVar = Variable(Type(TypeKind.None, false), ""); + + // SINGLE VALUES + boolVar = Variable(Type(TypeKind.Bool, false), abi.encode(true)); + addressVar = Variable(Type(TypeKind.Address, false), abi.encode(address(0xdeadbeef))); + bytes32Var = Variable(Type(TypeKind.Bytes32, false), abi.encode(bytes32(uint256(42)))); + uintVar = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(123))); + intVar = Variable(Type(TypeKind.Int256, false), abi.encode(int256(-123))); + stringVar = Variable(Type(TypeKind.String, false), abi.encode("hello world")); + bytesVar = Variable(Type(TypeKind.Bytes, false), abi.encode(hex"c0ffee")); + + // ARRAY VALUES + bool[] memory bools = new bool[](2); + bools[0] = true; + bools[1] = false; + boolArrayVar = Variable(Type(TypeKind.Bool, true), abi.encode(bools)); + + address[] memory addrs = new address[](2); + addrs[0] = address(0x1); + addrs[1] = address(0x2); + addressArrayVar = Variable(Type(TypeKind.Address, true), abi.encode(addrs)); + + bytes32[] memory b32s = new bytes32[](2); + b32s[0] = bytes32(uint256(1)); + b32s[1] = bytes32(uint256(2)); + bytes32ArrayVar = Variable(Type(TypeKind.Bytes32, true), abi.encode(b32s)); + + uint256[] memory uints = new uint256[](2); + uints[0] = 1; + uints[1] = 2; + uintArrayVar = Variable(Type(TypeKind.Uint256, true), abi.encode(uints)); + + int256[] memory ints = new int256[](2); + ints[0] = -1; + ints[1] = 2; + intArrayVar = Variable(Type(TypeKind.Int256, true), abi.encode(ints)); + + string[] memory strings = new string[](2); + strings[0] = "one"; + strings[1] = "two"; + stringArrayVar = Variable(Type(TypeKind.String, true), abi.encode(strings)); + + bytes[] memory b = new bytes[](2); + b[0] = hex"01"; + b[1] = hex"02"; + bytesArrayVar = Variable(Type(TypeKind.Bytes, true), abi.encode(b)); + } + + // -- SUCCESS CASES -------------------------------------------------------- + + function test_TypeHelpers() public view { + // TypeKind.toString() + assertEq(TypeKind.None.toString(), "none"); + assertEq(TypeKind.Bool.toString(), "bool"); + assertEq(TypeKind.Address.toString(), "address"); + assertEq(TypeKind.Bytes32.toString(), "bytes32"); + assertEq(TypeKind.Uint256.toString(), "uint256"); + assertEq(TypeKind.Int256.toString(), "int256"); + assertEq(TypeKind.String.toString(), "string"); + assertEq(TypeKind.Bytes.toString(), "bytes"); + + // TypeKind.toTomlKey() + assertEq(TypeKind.Uint256.toTomlKey(), "uint"); + assertEq(TypeKind.Int256.toTomlKey(), "int"); + assertEq(TypeKind.Bytes32.toTomlKey(), "bytes32"); + + // Type.toString() + assertEq(boolVar.ty.toString(), "bool"); + assertEq(boolArrayVar.ty.toString(), "bool[]"); + assertEq(uintVar.ty.toString(), "uint256"); + assertEq(uintArrayVar.ty.toString(), "uint256[]"); + assertEq(uninitVar.ty.toString(), "none"); + + // Type.isEqual() + assertTrue(boolVar.ty.isEqual(Type(TypeKind.Bool, false))); + assertFalse(boolVar.ty.isEqual(Type(TypeKind.Bool, true))); + assertFalse(boolVar.ty.isEqual(Type(TypeKind.Address, false))); + + // Type.assertEq() + boolVar.ty.assertEq(Type(TypeKind.Bool, false)); + uintArrayVar.ty.assertEq(Type(TypeKind.Uint256, true)); + } + + function test_Coercion() public view { + // Single values + assertTrue(helper.toBool(boolVar)); + assertEq(helper.toAddress(addressVar), address(0xdeadbeef)); + assertEq(helper.toBytes32(bytes32Var), bytes32(uint256(42))); + assertEq(helper.toUint256(uintVar), 123); + assertEq(helper.toInt256(intVar), -123); + assertEq(helper.toString(stringVar), "hello world"); + assertEq(helper.toBytes(bytesVar), hex"c0ffee"); + + // Bool array + bool[] memory bools = helper.toBoolArray(boolArrayVar); + assertEq(bools.length, 2); + assertTrue(bools[0]); + assertFalse(bools[1]); + + // Address array + address[] memory addrs = helper.toAddressArray(addressArrayVar); + assertEq(addrs.length, 2); + assertEq(addrs[0], address(0x1)); + assertEq(addrs[1], address(0x2)); + + // String array + string[] memory strings = helper.toStringArray(stringArrayVar); + assertEq(strings.length, 2); + assertEq(strings[0], "one"); + assertEq(strings[1], "two"); + } + + function test_Downcasting() public view { + // Uint downcasting + Variable memory v_uint_small = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(100))); + assertEq(helper.toUint128(v_uint_small), 100); + assertEq(helper.toUint64(v_uint_small), 100); + assertEq(helper.toUint32(v_uint_small), 100); + assertEq(helper.toUint16(v_uint_small), 100); + assertEq(helper.toUint8(v_uint_small), 100); + + // Uint array downcasting + uint256[] memory small_uints = new uint256[](2); + small_uints[0] = 10; + small_uints[1] = 20; + Variable memory v_uint_array_small = Variable(Type(TypeKind.Uint256, true), abi.encode(small_uints)); + uint8[] memory u8_array = helper.toUint8Array(v_uint_array_small); + assertEq(u8_array[0], 10); + assertEq(u8_array[1], 20); + + // Int downcasting + Variable memory v_int_small_pos = Variable(Type(TypeKind.Int256, false), abi.encode(int256(100))); + Variable memory v_int_small_neg = Variable(Type(TypeKind.Int256, false), abi.encode(int256(-100))); + assertEq(helper.toInt128(v_int_small_pos), 100); + assertEq(helper.toInt64(v_int_small_neg), -100); + assertEq(helper.toInt32(v_int_small_pos), 100); + assertEq(helper.toInt16(v_int_small_neg), -100); + assertEq(helper.toInt8(v_int_small_pos), 100); + + // Int array downcasting + int256[] memory small_ints = new int256[](2); + small_ints[0] = -10; + small_ints[1] = 20; + Variable memory intArraySmall = Variable(Type(TypeKind.Int256, true), abi.encode(small_ints)); + int8[] memory i8_array = helper.toInt8Array(intArraySmall); + assertEq(i8_array[0], -10); + assertEq(i8_array[1], 20); + } + + // -- REVERT CASES --------------------------------------------------------- + + function testRevert_NotInitialized() public { + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.toBool(uninitVar); + + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.toAddressArray(uninitVar); + } + + function testRevert_assertExists() public { + vm.expectRevert(LibVariable.NotInitialized.selector); + helper.assertExists(uninitVar); + } + + function testRevert_TypeMismatch() public { + // Single values + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256", "bool")); + helper.toUint256(boolVar); + + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "address", "string")); + helper.toAddress(stringVar); + + // Arrays + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256[]", "bool[]")); + helper.toUint256Array(boolArrayVar); + + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "address[]", "string[]")); + helper.toAddressArray(stringArrayVar); + + // Single value to array + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "bool[]", "bool")); + helper.toBoolArray(boolVar); + + // Array to single value + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "bool", "bool[]")); + helper.toBool(boolArrayVar); + + // assertEq reverts + vm.expectRevert(abi.encodeWithSelector(LibVariable.TypeMismatch.selector, "uint256", "bool")); + helper.assertEq(boolVar.ty, Type(TypeKind.Uint256, false)); + } + + function testRevert_UnsafeCast() public { + // uint overflow + Variable memory uintLarge = Variable(Type(TypeKind.Uint256, false), abi.encode(uint256(type(uint128).max) + 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'uint128'"); + vm.expectRevert(expectedErr); + helper.toUint128(uintLarge); + + // int overflow + Variable memory intLarge = Variable(Type(TypeKind.Int256, false), abi.encode(int256(type(int128).max) + 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'int128'"); + + vm.expectRevert(expectedErr); + helper.toInt128(intLarge); + + // int underflow + Variable memory intSmall = Variable(Type(TypeKind.Int256, false), abi.encode(int256(type(int128).min) - 1)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value does not fit in 'int128'"); + + vm.expectRevert(expectedErr); + helper.toInt128(intSmall); + + // uint array overflow + uint256[] memory uintArray = new uint256[](2); + uintArray[0] = 10; + uintArray[1] = uint256(type(uint64).max) + 1; + Variable memory uintArrayLarge = Variable(Type(TypeKind.Uint256, true), abi.encode(uintArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'uint64'"); + + vm.expectRevert(expectedErr); + helper.toUint64Array(uintArrayLarge); + + // int array overflow + int256[] memory intArray = new int256[](2); + intArray[0] = 10; + intArray[1] = int256(type(int64).max) + 1; + Variable memory intArrayLarge = Variable(Type(TypeKind.Int256, true), abi.encode(intArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'int64'"); + + vm.expectRevert(expectedErr); + helper.toInt64Array(intArrayLarge); + + // int array underflow + intArray[0] = 10; + intArray[1] = int256(type(int64).min) - 1; + Variable memory intArraySmall = Variable(Type(TypeKind.Int256, true), abi.encode(intArray)); + expectedErr = abi.encodeWithSelector(LibVariable.UnsafeCast.selector, "value in array does not fit in 'int64'"); + + vm.expectRevert(expectedErr); + helper.toInt64Array(intArraySmall); + } +} + +/// @dev We must use an external helper contract to ensure proper call depth for `vm.expectRevert`, +/// as direct library calls are inlined by the compiler, causing call depth issues. +contract LibVariableHelper { + using LibVariable for Type; + using LibVariable for TypeKind; + + // Assertions + function assertExists(Variable memory v) external pure { + v.assertExists(); + } + + function assertEq(Type memory t1, Type memory t2) external pure { + t1.assertEq(t2); + } + + // Single Value Coercion + function toBool(Variable memory v) external pure returns (bool) { + return v.toBool(); + } + + function toAddress(Variable memory v) external pure returns (address) { + return v.toAddress(); + } + + function toBytes32(Variable memory v) external pure returns (bytes32) { + return v.toBytes32(); + } + + function toUint256(Variable memory v) external pure returns (uint256) { + return v.toUint256(); + } + + function toInt256(Variable memory v) external pure returns (int256) { + return v.toInt256(); + } + + function toString(Variable memory v) external pure returns (string memory) { + return v.toString(); + } + + function toBytes(Variable memory v) external pure returns (bytes memory) { + return v.toBytes(); + } + + // Array Coercion + function toBoolArray(Variable memory v) external pure returns (bool[] memory) { + return v.toBoolArray(); + } + + function toAddressArray(Variable memory v) external pure returns (address[] memory) { + return v.toAddressArray(); + } + + function toBytes32Array(Variable memory v) external pure returns (bytes32[] memory) { + return v.toBytes32Array(); + } + + function toUint256Array(Variable memory v) external pure returns (uint256[] memory) { + return v.toUint256Array(); + } + + function toInt256Array(Variable memory v) external pure returns (int256[] memory) { + return v.toInt256Array(); + } + + function toStringArray(Variable memory v) external pure returns (string[] memory) { + return v.toStringArray(); + } + + function toBytesArray(Variable memory v) external pure returns (bytes[] memory) { + return v.toBytesArray(); + } + + // Uint Downcasting + function toUint128(Variable memory v) external pure returns (uint128) { + return v.toUint128(); + } + + function toUint64(Variable memory v) external pure returns (uint64) { + return v.toUint64(); + } + + function toUint32(Variable memory v) external pure returns (uint32) { + return v.toUint32(); + } + + function toUint16(Variable memory v) external pure returns (uint16) { + return v.toUint16(); + } + + function toUint8(Variable memory v) external pure returns (uint8) { + return v.toUint8(); + } + + // Int Downcasting + function toInt128(Variable memory v) external pure returns (int128) { + return v.toInt128(); + } + + function toInt64(Variable memory v) external pure returns (int64) { + return v.toInt64(); + } + + function toInt32(Variable memory v) external pure returns (int32) { + return v.toInt32(); + } + + function toInt16(Variable memory v) external pure returns (int16) { + return v.toInt16(); + } + + function toInt8(Variable memory v) external pure returns (int8) { + return v.toInt8(); + } + + // Uint Array Downcasting + function toUint128Array(Variable memory v) external pure returns (uint128[] memory) { + return v.toUint128Array(); + } + + function toUint64Array(Variable memory v) external pure returns (uint64[] memory) { + return v.toUint64Array(); + } + + function toUint32Array(Variable memory v) external pure returns (uint32[] memory) { + return v.toUint32Array(); + } + + function toUint16Array(Variable memory v) external pure returns (uint16[] memory) { + return v.toUint16Array(); + } + + function toUint8Array(Variable memory v) external pure returns (uint8[] memory) { + return v.toUint8Array(); + } + + // Int Array Downcasting + function toInt128Array(Variable memory v) external pure returns (int128[] memory) { + return v.toInt128Array(); + } + + function toInt64Array(Variable memory v) external pure returns (int64[] memory) { + return v.toInt64Array(); + } + + function toInt32Array(Variable memory v) external pure returns (int32[] memory) { + return v.toInt32Array(); + } + + function toInt16Array(Variable memory v) external pure returns (int16[] memory) { + return v.toInt16Array(); + } + + function toInt8Array(Variable memory v) external pure returns (int8[] memory) { + return v.toInt8Array(); + } +} diff --git a/test/StdChains.t.sol b/test/StdChains.t.sol index d88069bf5..9522b37d0 100644 --- a/test/StdChains.t.sol +++ b/test/StdChains.t.sol @@ -179,7 +179,7 @@ contract StdChainsTest is Test { stdChainsMock.exposed_getChain(""); } - function test_RevertIf_ChainIdNotFound() public { + function test_RevertIf_ChainNotInitialized() public { // We deploy a mock to properly test the revert. StdChainsMock stdChainsMock = new StdChainsMock(); diff --git a/test/Vm.t.sol b/test/Vm.t.sol index bca885ee5..1b99e3db1 100644 --- a/test/Vm.t.sol +++ b/test/Vm.t.sol @@ -13,6 +13,6 @@ contract VmTest is Test { } function test_VmSafeInterfaceId() public pure { - assertEq(type(VmSafe).interfaceId, bytes4(0xdcd933d4), "VmSafe"); + assertEq(type(VmSafe).interfaceId, bytes4(0xe02727c3), "VmSafe"); } } diff --git a/test/fixtures/config.toml b/test/fixtures/config.toml new file mode 100644 index 000000000..e6dcccca5 --- /dev/null +++ b/test/fixtures/config.toml @@ -0,0 +1,81 @@ +# ------------------------------------------------ +# EXAMPLE DEPLOYMENT CONFIG +# ------------------------------------------------ + +# -- MAINNET ------------------------------------- + +[mainnet] +endpoint_url = "${MAINNET_RPC}" + +[mainnet.bool] +is_live = true +bool_array = [true, false] + +[mainnet.address] +weth = "${WETH_MAINNET}" +deps = [ + "0x0000000000000000000000000000000000000000", + "0x1111111111111111111111111111111111111111", +] + +[mainnet.uint] +number = 1234 +number_array = [5678, 9999] + +[mainnet.int] +signed_number = -1234 +signed_number_array = [-5678, 9999] + +[mainnet.bytes32] +word = "0x00000000000000000000000000000000000000000000000000000000000004d2" # 1234 +word_array = [ + "0x000000000000000000000000000000000000000000000000000000000000162e", # 5678 + "0x000000000000000000000000000000000000000000000000000000000000270f", # 9999 +] + +[mainnet.bytes] +b = "0xabcd" +b_array = ["0xdead", "0xbeef"] + +[mainnet.string] +str = "foo" +str_array = ["bar", "baz"] + +# -- OPTIMISM ------------------------------------ + +[optimism] +endpoint_url = "${OPTIMISM_RPC}" + +[optimism.bool] +is_live = false +bool_array = [false, true] + +[optimism.address] +weth = "${WETH_OPTIMISM}" +deps = [ + "0x2222222222222222222222222222222222222222", + "0x3333333333333333333333333333333333333333", +] + +[optimism.uint] +number = 9999 +number_array = [1234, 5678] + +[optimism.int] +signed_number = 9999 +signed_number_array = [-1234, -5678] + +[optimism.bytes32] +word = "0x000000000000000000000000000000000000000000000000000000000000270f" # 9999 +word_array = [ + "0x00000000000000000000000000000000000000000000000000000000000004d2", # 1234 + "0x000000000000000000000000000000000000000000000000000000000000162e", # 5678 +] + +[optimism.bytes] +b = "0xdcba" +b_array = ["0xc0ffee", "0xbabe"] + +[optimism.string] +str = "alice" +str_array = ["bob", "charlie"]