Skip to content
Verified contractPartialMIT

DefaultDiamondProxy

Address0xacf7ca94d3534d065fc1454ef18eb89948b9aae7
Balance

0 ETH

 

Transactions

886

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 1,000,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
19,613,767
Creation transaction
0xf97ac166e5…d1278509fa

58 files

contracts-internal/src/eip2535/DiamondBase.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { VmSafe } from "forge-std/Vm.sol";

import { IDiamondWritableInternal } from "@solidstate/proxy/diamond/writable/IDiamondWritableInternal.sol";
import {
    ISolidStateDiamond, IDiamondWritable, IDiamondFallback
} from "@solidstate/proxy/diamond/ISolidStateDiamond.sol";
import { IDiamondReadable } from "@solidstate/proxy/diamond/readable/IDiamondReadable.sol";
import { SolidStateDiamond } from "@solidstate/proxy/diamond/SolidStateDiamond.sol";

import { IInitializer } from "@internal/eip2535/IInitializer.sol";
import { IFacet } from "@internal/eip2535/IFacet.sol";

import { Arrays } from "@common/libraries/Arrays.sol";
import { Methods } from "@common/libraries/Methods.sol";
import { Strings } from "@common/libraries/Strings.sol";

import { format, println } from "@vulcan/_internal/Utils.sol";

import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

/// @dev Zero address. Default initializer contract location, noop.
address constant ADDRESS_ZERO = address(0);

/// @dev Zero bytes4. Default selector signature when not exists.
bytes4 constant BYTES4_ZERO = bytes4(0);

/// @dev Empty bytes. Default initializer function, noop.
bytes constant BYTES_EMPTY = "";

/// @dev Aliased `IDiamondWritableInternal.FacetCutAction` enums.
IDiamondWritableInternal.FacetCutAction constant ADD_FACET_ACTION = IDiamondWritableInternal.FacetCutAction.ADD;
IDiamondWritableInternal.FacetCutAction constant REPLACE_FACET_ACTION = IDiamondWritableInternal.FacetCutAction.REPLACE;
IDiamondWritableInternal.FacetCutAction constant REMOVE_FACET_ACTION = IDiamondWritableInternal.FacetCutAction.REMOVE;

/// @notice The default implementation of the Diamond proxy.
/// @dev This contract is used as the default implementation of the Diamond proxy if one is not specified upon deployment.
contract DefaultDiamondProxy is SolidStateDiamond { }

/// @dev A script for managing EIP-2535 (Diamond's) deployments & upgrades.
/// @author Ryley Kimmel <[email protected]>
contract DiamondBase {
    using EnumerableSet for EnumerableSet.AddressSet;
    /// @notice A mapping of Diamond addresses to their respective descriptors.
    /// @dev A single EIP-2535 script can interface with multiple Diamonds.

    mapping(address => DiamondDescriptor) private descriptors;
    mapping(address => DiamondUpdateDescriptor) private updateDescriptors;

    /// @notice The address of the current diamond context.
    /// @dev This is used to track the current diamond being interacted with.
    address private contextImplementation;

    struct Facet {
        address target;
        bytes4[] selectors;
        bytes creationCode;
        string name;
    }

    /// @notice Describes a Diamond and facet cuts
    struct DiamondDescriptor {
        /// @notice The address of the Diamond.
        address implementation;
        /// @notice This diamond implementation.
        ISolidStateDiamond diamond;
        /// @notice The facets of this Diamond.
        Facet[] facets;
        /// @notice An array of pending facet cuts.
        IDiamondWritableInternal.FacetCut[] cuts;
    }

    struct DiamondUpdateDescriptor {
        EnumerableSet.AddressSet existingFacets;
        mapping(address => bytes4[]) existingSelectors;
        bytes4[] newSelectors;
    }

    function newContext(ISolidStateDiamond diamond) internal returns (DiamondDescriptor storage descriptor) {
        address implementation = address(diamond);
        descriptor = descriptors[implementation];

        require(
            descriptor.implementation == ADDRESS_ZERO,
            format(
                "Diamond already exists @ {a}. You should be using `useContext(address|DiamondDescriptor|ISolidStateDiamond)` instead.",
                abi.encode(descriptor.implementation)
            )
        );

        descriptor.implementation = implementation;
        descriptor.diamond = diamond;

        // Start tracking the current diamond context
        contextImplementation = implementation;

        println("Deployed diamond @ {a}", abi.encode(implementation));
    }

    function newContext() internal returns (DiamondDescriptor storage descriptor) {
        descriptor = newContext(new DefaultDiamondProxy());
    }

    function useContext(address implementation) internal returns (DiamondDescriptor storage descriptor) {
        descriptor = descriptors[implementation];

        if (descriptor.implementation == ADDRESS_ZERO) {
            descriptor.implementation = implementation;
            descriptor.diamond = ISolidStateDiamond(payable(implementation));
            println("Unknown diamond @ {a}. Attempting on-chain lookup...", abi.encode(implementation));
            describe(descriptor);
        }

        contextImplementation = implementation;
    }

    function useContext(DiamondDescriptor storage descriptor) internal returns (DiamondDescriptor storage) {
        return useContext(descriptor.implementation);
    }

    function useContext(ISolidStateDiamond diamond) internal returns (DiamondDescriptor storage descriptor) {
        return useContext(address(diamond));
    }

    function describe(DiamondDescriptor storage descriptor) internal {
        /// @dev Ensure the specified `diamondAddress` is a valid Diamond.
        bytes4[] memory requiredInterfaces = new bytes4[](3);
        requiredInterfaces[0] = type(IDiamondFallback).interfaceId;
        requiredInterfaces[1] = type(IDiamondReadable).interfaceId;
        requiredInterfaces[2] = type(IDiamondWritable).interfaceId;

        address implementation = descriptor.implementation;
        require(
            ERC165Checker.supportsAllInterfaces(implementation, requiredInterfaces),
            format(
                "`{a}` is missing one or more of the following interfaces `IERC165`, `IDiamondFallback|IDiamond`, `IDiamondReadable|IDiamondLoupe`, `IDiamondWritable|IDiamondCut`",
                abi.encode(implementation)
            )
        );

        ISolidStateDiamond diamond = ISolidStateDiamond(payable(implementation));
        IDiamondReadable.Facet[] memory facets = diamond.facets();

        descriptor.implementation = implementation;
        descriptor.diamond = diamond;

        for (uint256 i = 0; i < facets.length; i++) {
            address target = facets[i].target;
            descriptor.facets.push(
                Facet({
                    target: target,
                    selectors: facets[i].selectors,
                    creationCode: BYTES_EMPTY,
                    name: Strings.toString(target)
                })
            );
        }

        println("Described diamond: [impl={a}, nfacets={u}]", abi.encode(implementation, facets.length - 1));
    }

    modifier requiresContext() {
        require(
            contextImplementation != ADDRESS_ZERO,
            "No context set. Either create one `newContext(noop|ISolidStateDiamond)` or use an existing `useContext(address|DiamondDescriptor|ISolidStateDiamond)`."
        );
        _;
    }

    function context() private view returns (DiamondDescriptor storage descriptor) {
        descriptor = descriptors[contextImplementation];
    }

    function replaceContext() private view returns (DiamondUpdateDescriptor storage updateDescriptor) {
        updateDescriptor = updateDescriptors[contextImplementation];
    }

    function addFacet(string memory facetName) internal requiresContext returns (address facetAddress) {
        facetAddress = addFacet(context(), facetName, BYTES_EMPTY);
    }

    function addFacet(string memory facetName, bytes memory args)
        internal
        requiresContext
        returns (address facetAddress)
    {
        facetAddress = addFacet(context(), facetName, args);
    }

    function addFacet(DiamondDescriptor storage descriptor, string memory facetName, bytes memory args)
        internal
        returns (address facetAddress)
    {
        Facet memory facet = FacetHelper.deploy(descriptor, facetName, args);
        facetAddress = facet.target;

        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: facetAddress,
                action: ADD_FACET_ACTION,
                selectors: facet.selectors
            })
        );

        println("Added facet: {s} @ {a}", abi.encode(facetName, facetAddress));
    }

    function addFacetNoDeploy(string memory facetName, address facetAddress) internal requiresContext {
        addFacetNoDeploy(context(), facetName, facetAddress);
    }

    function addFacetNoDeploy(DiamondDescriptor storage descriptor, string memory facetName, address facetAddress)
        internal
    {
        Facet memory facet = FacetHelper.describe(descriptor, facetName);

        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: facetAddress,
                action: ADD_FACET_ACTION,
                selectors: facet.selectors
            })
        );

        println("Added facet: {s} @ {a}", abi.encode(facetName, facetAddress));
    }

    function removeFacet(DiamondDescriptor storage descriptor, address facetAddress) internal {
        ISolidStateDiamond diamond = descriptor.diamond;
        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: ADDRESS_ZERO,
                action: REMOVE_FACET_ACTION,
                selectors: diamond.facetFunctionSelectors(facetAddress)
            })
        );
    }

    function removeFacet(address facetAddress) internal requiresContext {
        removeFacet(context(), facetAddress);
    }

    function removeFacet(IFacet facet) internal requiresContext {
        removeFacet(context(), address(facet));
    }

    function removeFacet(DiamondDescriptor storage descriptor, bytes4 selector) internal {
        ISolidStateDiamond diamond = descriptor.diamond;

        address target = diamond.facetAddress(selector);
        require(
            target != ADDRESS_ZERO,
            format("Diamond does not contain any facet with function selector: {a}", abi.encode(selector))
        );

        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: ADDRESS_ZERO,
                action: REMOVE_FACET_ACTION,
                selectors: diamond.facetFunctionSelectors(target)
            })
        );
    }

    function removeFacet(bytes4 selector) internal requiresContext {
        removeFacet(context(), selector);
    }

    function replaceFacet(
        DiamondDescriptor storage descriptor,
        DiamondUpdateDescriptor storage updateDescriptor,
        string memory facetName,
        bytes memory args
    ) internal {
        // Parse facet from disk and attempt to find the on chain facet address
        Facet memory facet = FacetHelper.deploy(descriptor, facetName, args);
        ISolidStateDiamond diamond = descriptor.diamond;
        uint256 existingSelectorsLength = 0;
        uint256 newSelectorsLength = 0;
        for (uint256 i = 0; i < facet.selectors.length; i++) {
            bytes4 selector = facet.selectors[i];
            address target = diamond.facetAddress(selector);
            if (target != ADDRESS_ZERO) {
                updateDescriptor.existingFacets.add(target);
                updateDescriptor.existingSelectors[target].push(selector);
                existingSelectorsLength++;
            } else {
                updateDescriptor.newSelectors.push(selector);
                newSelectorsLength++;
            }
        }

        require(
            existingSelectorsLength != 0,
            format(
                "Unable to find matching selectors from the local facet ({s}) with selectors present on-chain. `replaceFacet()` is designed to substitute outdated selectors with any function selectors that match those found in the local artifact.",
                abi.encode(facetName)
            )
        );
        println(
            "Found {u} existing selectors and {u} new selectors",
            abi.encode(existingSelectorsLength, newSelectorsLength)
        );

        for (uint256 i = 0; i < updateDescriptor.existingFacets.length(); i++) {
            address facetAddress = updateDescriptor.existingFacets.at(i);
            bytes4[] storage selectors = updateDescriptor.existingSelectors[facetAddress];
            descriptor.cuts.push(
                IDiamondWritableInternal.FacetCut({
                    target: facet.target,
                    action: REPLACE_FACET_ACTION,
                    selectors: selectors
                })
            );
        }

        if (newSelectorsLength > 0) {
            descriptor.cuts.push(
                IDiamondWritableInternal.FacetCut({
                    target: facet.target,
                    action: ADD_FACET_ACTION,
                    selectors: updateDescriptor.newSelectors
                })
            );
        }
        println("Replaced facet: {s} @ {a}", abi.encode(facetName, facet.target));
    }

    function replaceFacet(string memory facetName) internal requiresContext {
        replaceFacet(context(), replaceContext(), facetName, BYTES_EMPTY);
    }

    function replaceFacet(string memory facetName, bytes memory args) internal requiresContext {
        replaceFacet(context(), replaceContext(), facetName, args);
    }

    function enableFunction(DiamondDescriptor storage descriptor, bytes4 selector) internal {
        // TODO: We need to check deployment logs and determine the facet the specified `selector` belongs to
        // We then need to check the deployed diamond on chain to ensure the facet within the deployment logs is the same as the facet on chain
        // We then need to check the deployed diamond on chain to ensure the specified `selector` on chain is already disabled
        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: address(0), // TODO target should be the facet address
                action: ADD_FACET_ACTION,
                selectors: Arrays.toArray(selector)
            })
        );
    }

    function enableFunction(bytes4 selector) internal requiresContext {
        enableFunction(context(), selector);
    }

    function disableFunction(DiamondDescriptor storage descriptor, bytes4 selector) internal {
        // TODO: We need to check deployment logs and determine the facet the specified `selector` belongs to
        // We then need to check the deployed diamond on chain to ensure the facet within the deployment logs is the same as the facet on chain
        // We then need to check the deployed diamond on chain to ensure the specified `selector` is not already disabled
        descriptor.cuts.push(
            IDiamondWritableInternal.FacetCut({
                target: ADDRESS_ZERO,
                action: REMOVE_FACET_ACTION,
                selectors: Arrays.toArray(selector)
            })
        );
    }

    function disableFunction(bytes4 selector) internal requiresContext {
        disableFunction(context(), selector);
    }

    function deploy(DiamondDescriptor storage descriptor, IInitializer initializer, bytes memory initializerFunction)
        internal
    {
        deploy(descriptor, address(initializer), initializerFunction);
    }

    function deploy(IInitializer initializer, bytes memory initializerFunction) internal requiresContext {
        deploy(context(), address(initializer), initializerFunction);
    }

    function deploy(DiamondDescriptor storage descriptor) internal {
        deploy(descriptor, ADDRESS_ZERO, BYTES_EMPTY);
    }

    function deploy() internal requiresContext {
        deploy(context());
    }

    function init(DiamondDescriptor storage descriptor, IInitializer initializer, bytes memory initializerFunction)
        internal
    {
        address initializerAddress = address(initializer);
        require(
            initializerAddress != ADDRESS_ZERO,
            format("Attempting to initialize diamond @ {a} with no initializer", abi.encode(descriptor.implementation))
        );
        IDiamondWritableInternal.FacetCut[] memory empty = new IDiamondWritableInternal.FacetCut[](0);
        descriptor.diamond.diamondCut(empty, initializerAddress, initializerFunction);
    }

    function deploy(DiamondDescriptor storage descriptor, address initializerAddress, bytes memory initializerFunction)
        internal
    {
        IDiamondWritableInternal.FacetCut[] memory cuts = descriptor.cuts;
        require(
            cuts.length > 0 || initializerAddress != ADDRESS_ZERO,
            format("Attempting to cut diamond @ {a} with no cuts or initializer", abi.encode(descriptor.implementation))
        );
        descriptor.diamond.diamondCut(cuts, initializerAddress, initializerFunction);
        delete descriptor.cuts;
    }
}

library FacetHelper {
    VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256("hevm cheat code")))));

    function describe(DiamondBase.DiamondDescriptor storage descriptor, string memory facetName)
        internal
        returns (DiamondBase.Facet memory facet)
    {
        string[] memory cmd = new string[](4);
        cmd[0] = "forge";
        cmd[1] = "inspect";
        cmd[2] = facetName;
        cmd[3] = "methods";

        VmSafe.FfiResult memory result = vm.tryFfi(cmd);
        require(
            result.stderr.length == 0, format("Process exited with unexpected error: {s}", abi.encode(result.stderr))
        );
        require(result.exitCode == 0, format("Process exited with unexpected code: {u}.", abi.encode(result.exitCode)));

        string memory json = string(result.stdout);
        string[] memory methods = vm.parseJsonKeys(json, "$");
        bytes4[] memory selectors = Methods.toSignatures(methods);

        for (uint256 i = 0; i < selectors.length; i++) {
            bytes4 selector = selectors[i];
            bytes4 remove = 0x01ffc9a7;

            if (selector == remove) {
                selectors[i] = bytes4(0); //TODO improve this - cheaphax for now
            }
        }

        facet = DiamondBase.Facet({
            target: ADDRESS_ZERO, // Signifies this facet is not yet deployed
            selectors: selectors,
            creationCode: vm.getCode(string.concat(facetName, ".sol")),
            name: facetName
        });

        println("Described facet: {s} with {u} selectors", abi.encode(facetName, selectors.length));
    }

    function deploy(DiamondBase.Facet memory facet, bytes memory args) internal {
        bytes memory creationCode = facet.creationCode;
        bytes memory bytecode = args.length > 0 ? abi.encodePacked(creationCode, args) : creationCode;
        address target;
        assembly ("memory-safe") {
            target := create(0, add(bytecode, 0x20), mload(bytecode))
        }

        facet.target = target;
        require(target != ADDRESS_ZERO, string.concat("Failed to deploy facet: ", facet.name));
    }

    function deploy(DiamondBase.DiamondDescriptor storage descriptor, string memory facetName, bytes memory args)
        internal
        returns (DiamondBase.Facet memory facet)
    {
        facet = describe(descriptor, facetName);
        deploy(facet, args);
    }

    function deploy(DiamondBase.Facet memory facet) internal {
        deploy(facet, BYTES_EMPTY);
    }
}

contracts-common/src/libraries/Arrays.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @dev A utility library to perform array-related operations in Solidity.
///      This library provides helper functions to manipulate and convert certain data types to arrays.
/// @author Ryley Kimmel <[email protected]>
library Arrays {
    /// @notice Wraps a single `bytes4` value into a `bytes4[]` array.
    /// @dev Useful for quickly converting standalone values into single-item arrays,
    ///      especially in contexts where array functions are required.
    /// @param value The `bytes4` value to be wrapped into an array.
    /// @return data Returns a `bytes4[]` array of length 1 with `value` as its only element.
    function toArray(bytes4 value) internal pure returns (bytes4[] memory data) {
        data = new bytes4[](1);
        data[0] = value;
    }
}

contracts-common/src/libraries/Methods.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/// @dev A library for dealing with method selectors and signatures.
/// @author Ryley Kimmel <[email protected]>
library Methods {
    /// @dev Converts a selector to its signature.
    /// @param selector The selector to convert.
    /// @return signature The signature of the selector.
    function toSignature(string memory selector) internal pure returns (bytes4) {
        bytes32 result;

        assembly {
            // Calculate keccak256 hash of the selector
            result := keccak256(add(selector, 0x20), mload(selector))
        }

        return bytes4(result);
    }

    /// @dev Converts selectors to signatures.
    /// @param selectors The selectors to convert.
    /// @return signatures The signatures of the selectors.
    function toSignatures(string[] memory selectors) internal pure returns (bytes4[] memory signatures) {
        uint256 selectorsLength;
        assembly {
            // Load length of selectors array from memory
            selectorsLength := mload(selectors)
        }

        signatures = new bytes4[](selectorsLength);

        for (uint256 i = 0; i < selectorsLength; i++) {
            string memory currentSelector;
            assembly {
                // Load current selector from selectors array
                currentSelector := mload(add(add(selectors, 0x20), mul(i, 0x20)))
            }
            signatures[i] = toSignature(currentSelector);
        }
        return signatures;
    }
}

contracts-common/src/libraries/Strings.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { Strings as OpenZeppelinStrings } from "@openzeppelin/contracts/utils/Strings.sol";

/// @notice Provides utility functions to work with string data type in Solidity
/// @author Ryley Kimmel <[email protected]>
library Strings {
    /// @notice Checks if two strings are equal
    /// @param a The first string to compare
    /// @param b The second string to compare
    /// @return `true` if the strings are equal, `false` otherwise
    function equals(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
    }

    /// @notice Calculate the byte length of a string
    /// @param value The input string whose byte length needs to be calculated
    /// @return length The byte length of the input string
    function byteLength(string memory value) internal pure returns (uint256 length) {
        length = bytes(value).length;
    }

    /// @notice Checks if a string is empty
    /// @dev This function is equivalent to `byteLength(value) == 0`.
    /// @param value The input string to check
    /// @return `true` if the string is empty, `false` otherwise
    function isEmpty(string memory value) internal pure returns (bool) {
        return byteLength(value) == 0;
    }

    /// @notice Checks if a string is not empty
    /// @dev This function is equivalent to `byteLength(value) != 0`.
    /// @param value The input string to check
    /// @return `true` if the string is not empty, `false` otherwise
    function isNotEmpty(string memory value) internal pure returns (bool) {
        return !isEmpty(value);
    }

    /// @notice Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
    /// @dev This function is equivalent to `Strings.toHexString(address)` from OpenZeppelin. It exists here only for convenience.
    /// @param account The input `address` to convert to a hexadecimal string
    /// @return The hexadecimal string representation of the input `address`
    function toString(address account) internal pure returns (string memory) {
        return OpenZeppelinStrings.toHexString(account);
    }

    /// @notice Converts an `uint256` to its ASCII `string` decimal representation.
    /// @dev This function is equivalent to `Strings.toString(uint256)` from OpenZeppelin. It exists here only for convenience.
    /// @param value The input `uint256` to convert to a decimal string
    /// @return The decimal string representation of the input `uint256`
    function toString(uint256 value) internal pure returns (string memory) {
        return OpenZeppelinStrings.toString(value);
    }

    /// @notice Capitalizes each lowercase ASCII character in a string
    /// @dev This function only works for ASCII characters; it does not support UTF-8 characters.
    /// @param str The input string whose lowercase characters need to be capitalized
    /// @return capitalized The input string with each lowercase character capitalized
    function capitalize(string memory str) internal pure returns (string memory) {
        bytes memory strBytes = bytes(str);
        bytes memory capitalizedBytes = new bytes(strBytes.length);

        for (uint256 i = 0; i < strBytes.length; i++) {
            bytes1 character = strBytes[i];

            bool isLowercase = (character >= 0x61 && character <= 0x7A);
            if (isLowercase) {
                capitalizedBytes[i] = bytes1(uint8(character) - 32); // Convert to uppercase
            } else {
                capitalizedBytes[i] = character;
            }
        }

        return string(capitalizedBytes);
    }

    /// @notice Calculate the character length of a UTF-8 encoded string
    /// @dev This function distinguishes between different UTF-8 encoded byte lengths of characters.
    ///      For example, a typical ASCII character is 1 byte, but many emojis are 3 bytes.
    /// @param value The input UTF-8 encoded string whose character length needs to be calculated
    /// @return length The character length of the input string
    function characterLength(string memory value) internal pure returns (uint256 length) {
        assembly {
            let s := add(value, 0x20) // Skip the length of the string
            let len := mload(value)
            let end := add(s, len) // End position of the data

            for { } lt(s, end) { } {
                let b := and(0xFF, shr(248, mload(s))) // Load only the first byte

                // 1-byte character
                switch lt(b, 0x80)
                case 1 { s := add(s, 1) }
                case 0 {
                    // 2-byte character
                    switch and(gt(b, 0x7F), lt(b, 0xE0))
                    case 1 { s := add(s, 2) }
                    case 0 {
                        // 3-byte character
                        switch lt(b, 0xF0)
                        case 1 { s := add(s, 3) }
                        case 0 {
                            // 4-byte character
                            s := add(s, 4)
                        }
                    }
                }
                length := add(length, 1)
            }
        }
    }
}

contracts-internal/src/eip2535/IFacet.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IFacet {
    error Facet__CallUnauthorized();

    error Facet__CallNotImplemented();
}

contracts-internal/src/eip2535/IInitializer.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IInitializer { }

lib/forge-std/src/StdStorage.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.9.0;

import {Vm} from "./Vm.sol";

struct FindData {
    uint256 slot;
    uint256 offsetLeft;
    uint256 offsetRight;
    bool found;
}

struct StdStorage {
    mapping(address => mapping(bytes4 => mapping(bytes32 => FindData))) finds;
    bytes32[] _keys;
    bytes4 _sig;
    uint256 _depth;
    address _target;
    bytes32 _set;
    bool _enable_packed_slots;
    bytes _calldata;
}

library stdStorageSafe {
    event SlotFound(address who, bytes4 fsig, bytes32 keysHash, uint256 slot);
    event WARNING_UninitedSlot(address who, uint256 slot);

    Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));
    uint256 constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935;

    function sigs(string memory sigStr) internal pure returns (bytes4) {
        return bytes4(keccak256(bytes(sigStr)));
    }

    function getCallParams(StdStorage storage self) internal view returns (bytes memory) {
        if (self._calldata.length == 0) {
            return flatten(self._keys);
        } else {
            return self._calldata;
        }
    }

    // Calls target contract with configured parameters
    function callTarget(StdStorage storage self) internal view returns (bool, bytes32) {
        bytes memory cald = abi.encodePacked(self._sig, getCallParams(self));
        (bool success, bytes memory rdat) = self._target.staticcall(cald);
        bytes32 result = bytesToBytes32(rdat, 32 * self._depth);

        return (success, result);
    }

    // Tries mutating slot value to determine if the targeted value is stored in it.
    // If current value is 0, then we are setting slot value to type(uint256).max
    // Otherwise, we set it to 0. That way, return value should always be affected.
    function checkSlotMutatesCall(StdStorage storage self, bytes32 slot) internal returns (bool) {
        bytes32 prevSlotValue = vm.load(self._target, slot);
        (bool success, bytes32 prevReturnValue) = callTarget(self);

        bytes32 testVal = prevReturnValue == bytes32(0) ? bytes32(UINT256_MAX) : bytes32(0);
        vm.store(self._target, slot, testVal);

        (, bytes32 newReturnValue) = callTarget(self);

        vm.store(self._target, slot, prevSlotValue);

        return (success && (prevReturnValue != newReturnValue));
    }

    // Tries setting one of the bits in slot to 1 until return value changes.
    // Index of resulted bit is an offset packed slot has from left/right side
    function findOffset(StdStorage storage self, bytes32 slot, bool left) internal returns (bool, uint256) {
        for (uint256 offset = 0; offset < 256; offset++) {
            uint256 valueToPut = left ? (1 << (255 - offset)) : (1 << offset);
            vm.store(self._target, slot, bytes32(valueToPut));

            (bool success, bytes32 data) = callTarget(self);

            if (success && (uint256(data) > 0)) {
                return (true, offset);
            }
        }
        return (false, 0);
    }

    function findOffsets(StdStorage storage self, bytes32 slot) internal returns (bool, uint256, uint256) {
        bytes32 prevSlotValue = vm.load(self._target, slot);

        (bool foundLeft, uint256 offsetLeft) = findOffset(self, slot, true);
        (bool foundRight, uint256 offsetRight) = findOffset(self, slot, false);

        // `findOffset` may mutate slot value, so we are setting it to initial value
        vm.store(self._target, slot, prevSlotValue);
        return (foundLeft && foundRight, offsetLeft, offsetRight);
    }

    function find(StdStorage storage self) internal returns (FindData storage) {
        return find(self, true);
    }

    /// @notice find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against
    // slot complexity:
    //  if flat, will be bytes32(uint256(uint));
    //  if map, will be keccak256(abi.encode(key, uint(slot)));
    //  if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))));
    //  if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth);
    function find(StdStorage storage self, bool _clear) internal returns (FindData storage) {
        address who = self._target;
        bytes4 fsig = self._sig;
        uint256 field_depth = self._depth;
        bytes memory params = getCallParams(self);

        // calldata to test against
        if (self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found) {
            if (_clear) {
                clear(self);
            }
            return self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))];
        }
        vm.record();
        (, bytes32 callResult) = callTarget(self);
        (bytes32[] memory reads,) = vm.accesses(address(who));

        if (reads.length == 0) {
            revert("stdStorage find(StdStorage): No storage use detected for target.");
        } else {
            for (uint256 i = reads.length; --i >= 0;) {
                bytes32 prev = vm.load(who, reads[i]);
                if (prev == bytes32(0)) {
                    emit WARNING_UninitedSlot(who, uint256(reads[i]));
                }

                if (!checkSlotMutatesCall(self, reads[i])) {
                    continue;
                }

                (uint256 offsetLeft, uint256 offsetRight) = (0, 0);

                if (self._enable_packed_slots) {
                    bool found;
                    (found, offsetLeft, offsetRight) = findOffsets(self, reads[i]);
                    if (!found) {
                        continue;
                    }
                }

                // Check that value between found offsets is equal to the current call result
                uint256 curVal = (uint256(prev) & getMaskByOffsets(offsetLeft, offsetRight)) >> offsetRight;

                if (uint256(callResult) != curVal) {
                    continue;
                }

                emit SlotFound(who, fsig, keccak256(abi.encodePacked(params, field_depth)), uint256(reads[i]));
                self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))] =
                    FindData(uint256(reads[i]), offsetLeft, offsetRight, true);
                break;
            }
        }

        require(
            self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found,
            "stdStorage find(StdStorage): Slot(s) not found."
        );

        if (_clear) {
            clear(self);
        }
        return self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))];
    }

    function target(StdStorage storage self, address _target) internal returns (StdStorage storage) {
        self._target = _target;
        return self;
    }

    function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) {
        self._sig = _sig;
        return self;
    }

    function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) {
        self._sig = sigs(_sig);
        return self;
    }

    function with_calldata(StdStorage storage self, bytes memory _calldata) internal returns (StdStorage storage) {
        self._calldata = _calldata;
        return self;
    }

    function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) {
        self._keys.push(bytes32(uint256(uint160(who))));
        return self;
    }

    function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) {
        self._keys.push(bytes32(amt));
        return self;
    }

    function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) {
        self._keys.push(key);
        return self;
    }

    function enable_packed_slots(StdStorage storage self) internal returns (StdStorage storage) {
        self._enable_packed_slots = true;
        return self;
    }

    function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) {
        self._depth = _depth;
        return self;
    }

    function read(StdStorage storage self) private returns (bytes memory) {
        FindData storage data = find(self, false);
        uint256 mask = getMaskByOffsets(data.offsetLeft, data.offsetRight);
        uint256 value = (uint256(vm.load(self._target, bytes32(data.slot))) & mask) >> data.offsetRight;
        clear(self);
        return abi.encode(value);
    }

    function read_bytes32(StdStorage storage self) internal returns (bytes32) {
        return abi.decode(read(self), (bytes32));
    }

    function read_bool(StdStorage storage self) internal returns (bool) {
        int256 v = read_int(self);
        if (v == 0) return false;
        if (v == 1) return true;
        revert("stdStorage read_bool(StdStorage): Cannot decode. Make sure you are reading a bool.");
    }

    function read_address(StdStorage storage self) internal returns (address) {
        return abi.decode(read(self), (address));
    }

    function read_uint(StdStorage storage self) internal returns (uint256) {
        return abi.decode(read(self), (uint256));
    }

    function read_int(StdStorage storage self) internal returns (int256) {
        return abi.decode(read(self), (int256));
    }

    function parent(StdStorage storage self) internal returns (uint256, bytes32) {
        address who = self._target;
        uint256 field_depth = self._depth;
        vm.startMappingRecording();
        uint256 child = find(self, true).slot - field_depth;
        (bool found, bytes32 key, bytes32 parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(child));
        if (!found) {
            revert(
                "stdStorage read_bool(StdStorage): Cannot find parent. Make sure you give a slot and startMappingRecording() has been called."
            );
        }
        return (uint256(parent_slot), key);
    }

    function root(StdStorage storage self) internal returns (uint256) {
        address who = self._target;
        uint256 field_depth = self._depth;
        vm.startMappingRecording();
        uint256 child = find(self, true).slot - field_depth;
        bool found;
        bytes32 root_slot;
        bytes32 parent_slot;
        (found,, parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(child));
        if (!found) {
            revert(
                "stdStorage read_bool(StdStorage): Cannot find parent. Make sure you give a slot and startMappingRecording() has been called."
            );
        }
        while (found) {
            root_slot = parent_slot;
            (found,, parent_slot) = vm.getMappingKeyAndParentOf(who, bytes32(root_slot));
        }
        return uint256(root_slot);
    }

    function bytesToBytes32(bytes memory b, uint256 offset) private pure returns (bytes32) {
        bytes32 out;

        uint256 max = b.length > 32 ? 32 : b.length;
        for (uint256 i = 0; i < max; i++) {
            out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
        }
        return out;
    }

    function flatten(bytes32[] memory b) private pure returns (bytes memory) {
        bytes memory result = new bytes(b.length * 32);
        for (uint256 i = 0; i < b.length; i++) {
            bytes32 k = b[i];
            /// @solidity memory-safe-assembly
            assembly {
                mstore(add(result, add(32, mul(32, i))), k)
            }
        }

        return result;
    }

    function clear(StdStorage storage self) internal {
        delete self._target;
        delete self._sig;
        delete self._keys;
        delete self._depth;
        delete self._enable_packed_slots;
        delete self._calldata;
    }

    // Returns mask which contains non-zero bits for values between `offsetLeft` and `offsetRight`
    // (slotValue & mask) >> offsetRight will be the value of the given packed variable
    function getMaskByOffsets(uint256 offsetLeft, uint256 offsetRight) internal pure returns (uint256 mask) {
        // mask = ((1 << (256 - (offsetRight + offsetLeft))) - 1) << offsetRight;
        // using assembly because (1 << 256) causes overflow
        assembly {
            mask := shl(offsetRight, sub(shl(sub(256, add(offsetRight, offsetLeft)), 1), 1))
        }
    }

    // Returns slot value with updated packed variable.
    function getUpdatedSlotValue(bytes32 curValue, uint256 varValue, uint256 offsetLeft, uint256 offsetRight)
        internal
        pure
        returns (bytes32 newValue)
    {
        return bytes32((uint256(curValue) & ~getMaskByOffsets(offsetLeft, offsetRight)) | (varValue << offsetRight));
    }
}

library stdStorage {
    Vm private constant vm = Vm(address(uint160(uint256(keccak256("hevm cheat code")))));

    function sigs(string memory sigStr) internal pure returns (bytes4) {
        return stdStorageSafe.sigs(sigStr);
    }

    function find(StdStorage storage self) internal returns (uint256) {
        return find(self, true);
    }

    function find(StdStorage storage self, bool _clear) internal returns (uint256) {
        return stdStorageSafe.find(self, _clear).slot;
    }

    function target(StdStorage storage self, address _target) internal returns (StdStorage storage) {
        return stdStorageSafe.target(self, _target);
    }

    function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) {
        return stdStorageSafe.sig(self, _sig);
    }

    function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) {
        return stdStorageSafe.sig(self, _sig);
    }

    function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) {
        return stdStorageSafe.with_key(self, who);
    }

    function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) {
        return stdStorageSafe.with_key(self, amt);
    }

    function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) {
        return stdStorageSafe.with_key(self, key);
    }

    function with_calldata(StdStorage storage self, bytes memory _calldata) internal returns (StdStorage storage) {
        return stdStorageSafe.with_calldata(self, _calldata);
    }

    function enable_packed_slots(StdStorage storage self) internal returns (StdStorage storage) {
        return stdStorageSafe.enable_packed_slots(self);
    }

    function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) {
        return stdStorageSafe.depth(self, _depth);
    }

    function clear(StdStorage storage self) internal {
        stdStorageSafe.clear(self);
    }

    function checked_write(StdStorage storage self, address who) internal {
        checked_write(self, bytes32(uint256(uint160(who))));
    }

    function checked_write(StdStorage storage self, uint256 amt) internal {
        checked_write(self, bytes32(amt));
    }

    function checked_write_int(StdStorage storage self, int256 val) internal {
        checked_write(self, bytes32(uint256(val)));
    }

    function checked_write(StdStorage storage self, bool write) internal {
        bytes32 t;
        /// @solidity memory-safe-assembly
        assembly {
            t := write
        }
        checked_write(self, t);
    }

    function checked_write(StdStorage storage self, bytes32 set) internal {
        address who = self._target;
        bytes4 fsig = self._sig;
        uint256 field_depth = self._depth;
        bytes memory params = stdStorageSafe.getCallParams(self);

        if (!self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))].found) {
            find(self, false);
        }
        FindData storage data = self.finds[who][fsig][keccak256(abi.encodePacked(params, field_depth))];
        if ((data.offsetLeft + data.offsetRight) > 0) {
            uint256 maxVal = 2 ** (256 - (data.offsetLeft + data.offsetRight));
            require(
                uint256(set) < maxVal,
                string(
                    abi.encodePacked(
                        "stdStorage find(StdStorage): Packed slot. We can't fit value greater than ",
                        vm.toString(maxVal)
                    )
                )
            );
        }
        bytes32 curVal = vm.load(who, bytes32(data.slot));
        bytes32 valToSet = stdStorageSafe.getUpdatedSlotValue(curVal, uint256(set), data.offsetLeft, data.offsetRight);

        vm.store(who, bytes32(data.slot), valToSet);

        (bool success, bytes32 callResult) = stdStorageSafe.callTarget(self);

        if (!success || callResult != set) {
            vm.store(who, bytes32(data.slot), curVal);
            revert("stdStorage find(StdStorage): Failed to write value.");
        }
        clear(self);
    }

    function read_bytes32(StdStorage storage self) internal returns (bytes32) {
        return stdStorageSafe.read_bytes32(self);
    }

    function read_bool(StdStorage storage self) internal returns (bool) {
        return stdStorageSafe.read_bool(self);
    }

    function read_address(StdStorage storage self) internal returns (address) {
        return stdStorageSafe.read_address(self);
    }

    function read_uint(StdStorage storage self) internal returns (uint256) {
        return stdStorageSafe.read_uint(self);
    }

    function read_int(StdStorage storage self) internal returns (int256) {
        return stdStorageSafe.read_int(self);
    }

    function parent(StdStorage storage self) internal returns (uint256, bytes32) {
        return stdStorageSafe.parent(self);
    }

    function root(StdStorage storage self) internal returns (uint256) {
        return stdStorageSafe.root(self);
    }
}

lib/forge-std/src/Vm.sol

// Automatically @generated by scripts/vm.py. Do not modify manually.

// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.6.2 <0.9.0;
pragma experimental ABIEncoderV2;

/// The `VmSafe` interface does not allow manipulation of the EVM state or other actions that may
/// result in Script simulations differing from on-chain execution. It is recommended to only use
/// these cheats in scripts.
interface VmSafe {
    /// A modification applied to either `msg.sender` or `tx.origin`. Returned by `readCallers`.
    enum CallerMode {
        // No caller modification is currently active.
        None,
        // A one time broadcast triggered by a `vm.broadcast()` call is currently active.
        Broadcast,
        // A recurrent broadcast triggered by a `vm.startBroadcast()` call is currently active.
        RecurrentBroadcast,
        // A one time prank triggered by a `vm.prank()` call is currently active.
        Prank,
        // A recurrent prank triggered by a `vm.startPrank()` call is currently active.
        RecurrentPrank
    }

    /// The kind of account access that occurred.
    enum AccountAccessKind {
        // The account was called.
        Call,
        // The account was called via delegatecall.
        DelegateCall,
        // The account was called via callcode.
        CallCode,
        // The account was called via staticcall.
        StaticCall,
        // The account was created.
        Create,
        // The account was selfdestructed.
        SelfDestruct,
        // Synthetic access indicating the current context has resumed after a previous sub-context (AccountAccess).
        Resume,
        // The account's balance was read.
        Balance,
        // The account's codesize was read.
        Extcodesize,
        // The account's codehash was read.
        Extcodehash,
        // The account's code was copied.
        Extcodecopy
    }

    /// Forge execution contexts.
    enum ForgeContext {
        // Test group execution context (test, coverage or snapshot).
        TestGroup,
        // `forge test` execution context.
        Test,
        // `forge coverage` execution context.
        Coverage,
        // `forge snapshot` execution context.
        Snapshot,
        // Script group execution context (dry run, broadcast or resume).
        ScriptGroup,
        // `forge script` execution context.
        ScriptDryRun,
        // `forge script --broadcast` execution context.
        ScriptBroadcast,
        // `forge script --resume` execution context.
        ScriptResume,
        // Unknown `forge` execution context.
        Unknown
    }

    /// An Ethereum log. Returned by `getRecordedLogs`.
    struct Log {
        // The topics of the log, including the signature, if any.
        bytes32[] topics;
        // The raw data of the log.
        bytes data;
        // The address of the log's emitter.
        address emitter;
    }

    /// An RPC URL and its alias. Returned by `rpcUrlStructs`.
    struct Rpc {
        // The alias of the RPC URL.
        string key;
        // The RPC URL.
        string url;
    }

    /// An RPC log object. Returned by `eth_getLogs`.
    struct EthGetLogs {
        // The address of the log's emitter.
        address emitter;
        // The topics of the log, including the signature, if any.
        bytes32[] topics;
        // The raw data of the log.
        bytes data;
        // The block hash.
        bytes32 blockHash;
        // The block number.
        uint64 blockNumber;
        // The transaction hash.
        bytes32 transactionHash;
        // The transaction index in the block.
        uint64 transactionIndex;
        // The log index.
        uint256 logIndex;
        // Whether the log was removed.
        bool removed;
    }

    /// A single entry in a directory listing. Returned by `readDir`.
    struct DirEntry {
        // The error message, if any.
        string errorMessage;
        // The path of the entry.
        string path;
        // The depth of the entry.
        uint64 depth;
        // Whether the entry is a directory.
        bool isDir;
        // Whether the entry is a symlink.
        bool isSymlink;
    }

    /// Metadata information about a file.
    /// This structure is returned from the `fsMetadata` function and represents known
    /// metadata about a file such as its permissions, size, modification
    /// times, etc.
    struct FsMetadata {
        // True if this metadata is for a directory.
        bool isDir;
        // True if this metadata is for a symlink.
        bool isSymlink;
        // The size of the file, in bytes, this metadata is for.
        uint256 length;
        // True if this metadata is for a readonly (unwritable) file.
        bool readOnly;
        // The last modification time listed in this metadata.
        uint256 modified;
        // The last access time of this metadata.
        uint256 accessed;
        // The creation time listed in this metadata.
        uint256 created;
    }

    /// A wallet with a public and private key.
    struct Wallet {
        // The wallet's address.
        address addr;
        // The wallet's public key `X`.
        uint256 publicKeyX;
        // The wallet's public key `Y`.
        uint256 publicKeyY;
        // The wallet's private key.
        uint256 privateKey;
    }

    /// The result of a `tryFfi` call.
    struct FfiResult {
        // The exit code of the call.
        int32 exitCode;
        // The optionally hex-decoded `stdout` data.
        bytes stdout;
        // The `stderr` data.
        bytes stderr;
    }

    /// Information on the chain and fork.
    struct ChainInfo {
        // The fork identifier. Set to zero if no fork is active.
        uint256 forkId;
        // The chain ID of the current fork.
        uint256 chainId;
    }

    /// The result of a `stopAndReturnStateDiff` call.
    struct AccountAccess {
        // The chain and fork the access occurred.
        ChainInfo chainInfo;
        // The kind of account access that determines what the account is.
        // If kind is Call, DelegateCall, StaticCall or CallCode, then the account is the callee.
        // If kind is Create, then the account is the newly created account.
        // If kind is SelfDestruct, then the account is the selfdestruct recipient.
        // If kind is a Resume, then account represents a account context that has resumed.
        AccountAccessKind kind;
        // The account that was accessed.
        // It's either the account created, callee or a selfdestruct recipient for CREATE, CALL or SELFDESTRUCT.
        address account;
        // What accessed the account.
        address accessor;
        // If the account was initialized or empty prior to the access.
        // An account is considered initialized if it has code, a
        // non-zero nonce, or a non-zero balance.
        bool initialized;
        // The previous balance of the accessed account.
        uint256 oldBalance;
        // The potential new balance of the accessed account.
        // That is, all balance changes are recorded here, even if reverts occurred.
        uint256 newBalance;
        // Code of the account deployed by CREATE.
        bytes deployedCode;
        // Value passed along with the account access
        uint256 value;
        // Input data provided to the CREATE or CALL
        bytes data;
        // If this access reverted in either the current or parent context.
        bool reverted;
        // An ordered list of storage accesses made during an account access operation.
        StorageAccess[] storageAccesses;
        // Call depth traversed during the recording of state differences
        uint64 depth;
    }

    /// The storage accessed during an `AccountAccess`.
    struct StorageAccess {
        // The account whose storage was accessed.
        address account;
        // The slot that was accessed.
        bytes32 slot;
        // If the access was a write.
        bool isWrite;
        // The previous value of the slot.
        bytes32 previousValue;
        // The new value of the slot.
        bytes32 newValue;
        // If the access was reverted.
        bool reverted;
    }

    /// Gas used. Returned by `lastCallGas`.
    struct Gas {
        // The gas limit of the call.
        uint64 gasLimit;
        // The total gas used.
        uint64 gasTotalUsed;
        // DEPRECATED: The amount of gas used for memory expansion. Ref: <https://github.com/foundry-rs/foundry/pull/7934#pullrequestreview-2069236939>
        uint64 gasMemoryUsed;
        // The amount of gas refunded.
        int64 gasRefunded;
        // The amount of gas remaining.
        uint64 gasRemaining;
    }

    // ======== Crypto ========

    /// Derives a private key from the name, labels the account with that name, and returns the wallet.
    function createWallet(string calldata walletLabel) external returns (Wallet memory wallet);

    /// Generates a wallet from the private key and returns the wallet.
    function createWallet(uint256 privateKey) external returns (Wallet memory wallet);

    /// Generates a wallet from the private key, labels the account with that name, and returns the wallet.
    function createWallet(uint256 privateKey, string calldata walletLabel) external returns (Wallet memory wallet);

    /// Derive a private key from a provided mnenomic string (or mnenomic file path)
    /// at the derivation path `m/44'/60'/0'/0/{index}`.
    function deriveKey(string calldata mnemonic, uint32 index) external pure returns (uint256 privateKey);

    /// Derive a private key from a provided mnenomic string (or mnenomic file path)
    /// at `{derivationPath}{index}`.
    function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index)
        external
        pure
        returns (uint256 privateKey);

    /// Derive a private key from a provided mnenomic string (or mnenomic file path) in the specified language
    /// at the derivation path `m/44'/60'/0'/0/{index}`.
    function deriveKey(string calldata mnemonic, uint32 index, string calldata language)
        external
        pure
        returns (uint256 privateKey);

    /// Derive a private key from a provided mnenomic string (or mnenomic file path) in the specified language
    /// at `{derivationPath}{index}`.
    function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index, string calldata language)
        external
        pure
        returns (uint256 privateKey);

    /// Derives secp256r1 public key from the provided `privateKey`.
    function publicKeyP256(uint256 privateKey) external pure returns (uint256 publicKeyX, uint256 publicKeyY);

    /// Adds a private key to the local forge wallet and returns the address.
    function rememberKey(uint256 privateKey) external returns (address keyAddr);

    /// Signs data with a `Wallet`.
    /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the
    /// signature's `s` value, and the recovery id `v` in a single bytes32.
    /// This format reduces the signature size from 65 to 64 bytes.
    function signCompact(Wallet calldata wallet, bytes32 digest) external returns (bytes32 r, bytes32 vs);

    /// Signs `digest` with `privateKey` using the secp256k1 curve.
    /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the
    /// signature's `s` value, and the recovery id `v` in a single bytes32.
    /// This format reduces the signature size from 65 to 64 bytes.
    function signCompact(uint256 privateKey, bytes32 digest) external pure returns (bytes32 r, bytes32 vs);

    /// Signs `digest` with signer provided to script using the secp256k1 curve.
    /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the
    /// signature's `s` value, and the recovery id `v` in a single bytes32.
    /// This format reduces the signature size from 65 to 64 bytes.
    /// If `--sender` is provided, the signer with provided address is used, otherwise,
    /// if exactly one signer is provided to the script, that signer is used.
    /// Raises error if signer passed through `--sender` does not match any unlocked signers or
    /// if `--sender` is not provided and not exactly one signer is passed to the script.
    function signCompact(bytes32 digest) external pure returns (bytes32 r, bytes32 vs);

    /// Signs `digest` with signer provided to script using the secp256k1 curve.
    /// Returns a compact signature (`r`, `vs`) as per EIP-2098, where `vs` encodes both the
    /// signature's `s` value, and the recovery id `v` in a single bytes32.
    /// This format reduces the signature size from 65 to 64 bytes.
    /// Raises error if none of the signers passed into the script have provided address.
    function signCompact(address signer, bytes32 digest) external pure returns (bytes32 r, bytes32 vs);

    /// Signs `digest` with `privateKey` using the secp256r1 curve.
    function signP256(uint256 privateKey, bytes32 digest) external pure returns (bytes32 r, bytes32 s);

    /// Signs data with a `Wallet`.
    function sign(Wallet calldata wallet, bytes32 digest) external returns (uint8 v, bytes32 r, bytes32 s);

    /// Signs `digest` with `privateKey` using the secp256k1 curve.
    function sign(uint256 privateKey, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);

    /// Signs `digest` with signer provided to script using the secp256k1 curve.
    /// If `--sender` is provided, the signer with provided address is used, otherwise,
    /// if exactly one signer is provided to the script, that signer is used.
    /// Raises error if signer passed through `--sender` does not match any unlocked signers or
    /// if `--sender` is not provided and not exactly one signer is passed to the script.
    function sign(bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);

    /// Signs `digest` with signer provided to script using the secp256k1 curve.
    /// Raises error if none of the signers passed into the script have provided address.
    function sign(address signer, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);

    // ======== Environment ========

    /// Gets the environment variable `name` and parses it as `address`.
    /// Reverts if the variable was not found or could not be parsed.
    function envAddress(string calldata name) external view returns (address value);

    /// Gets the environment variable `name` and parses it as an array of `address`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envAddress(string calldata name, string calldata delim) external view returns (address[] memory value);

    /// Gets the environment variable `name` and parses it as `bool`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBool(string calldata name) external view returns (bool value);

    /// Gets the environment variable `name` and parses it as an array of `bool`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBool(string calldata name, string calldata delim) external view returns (bool[] memory value);

    /// Gets the environment variable `name` and parses it as `bytes32`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBytes32(string calldata name) external view returns (bytes32 value);

    /// Gets the environment variable `name` and parses it as an array of `bytes32`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBytes32(string calldata name, string calldata delim) external view returns (bytes32[] memory value);

    /// Gets the environment variable `name` and parses it as `bytes`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBytes(string calldata name) external view returns (bytes memory value);

    /// Gets the environment variable `name` and parses it as an array of `bytes`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envBytes(string calldata name, string calldata delim) external view returns (bytes[] memory value);

    /// Gets the environment variable `name` and returns true if it exists, else returns false.
    function envExists(string calldata name) external view returns (bool result);

    /// Gets the environment variable `name` and parses it as `int256`.
    /// Reverts if the variable was not found or could not be parsed.
    function envInt(string calldata name) external view returns (int256 value);

    /// Gets the environment variable `name` and parses it as an array of `int256`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envInt(string calldata name, string calldata delim) external view returns (int256[] memory value);

    /// Gets the environment variable `name` and parses it as `bool`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, bool defaultValue) external view returns (bool value);

    /// Gets the environment variable `name` and parses it as `uint256`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, uint256 defaultValue) external view returns (uint256 value);

    /// Gets the environment variable `name` and parses it as an array of `address`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, address[] calldata defaultValue)
        external
        view
        returns (address[] memory value);

    /// Gets the environment variable `name` and parses it as an array of `bytes32`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, bytes32[] calldata defaultValue)
        external
        view
        returns (bytes32[] memory value);

    /// Gets the environment variable `name` and parses it as an array of `string`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, string[] calldata defaultValue)
        external
        view
        returns (string[] memory value);

    /// Gets the environment variable `name` and parses it as an array of `bytes`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, bytes[] calldata defaultValue)
        external
        view
        returns (bytes[] memory value);

    /// Gets the environment variable `name` and parses it as `int256`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, int256 defaultValue) external view returns (int256 value);

    /// Gets the environment variable `name` and parses it as `address`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, address defaultValue) external view returns (address value);

    /// Gets the environment variable `name` and parses it as `bytes32`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, bytes32 defaultValue) external view returns (bytes32 value);

    /// Gets the environment variable `name` and parses it as `string`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata defaultValue) external view returns (string memory value);

    /// Gets the environment variable `name` and parses it as `bytes`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, bytes calldata defaultValue) external view returns (bytes memory value);

    /// Gets the environment variable `name` and parses it as an array of `bool`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, bool[] calldata defaultValue)
        external
        view
        returns (bool[] memory value);

    /// Gets the environment variable `name` and parses it as an array of `uint256`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, uint256[] calldata defaultValue)
        external
        view
        returns (uint256[] memory value);

    /// Gets the environment variable `name` and parses it as an array of `int256`, delimited by `delim`.
    /// Reverts if the variable could not be parsed.
    /// Returns `defaultValue` if the variable was not found.
    function envOr(string calldata name, string calldata delim, int256[] calldata defaultValue)
        external
        view
        returns (int256[] memory value);

    /// Gets the environment variable `name` and parses it as `string`.
    /// Reverts if the variable was not found or could not be parsed.
    function envString(string calldata name) external view returns (string memory value);

    /// Gets the environment variable `name` and parses it as an array of `string`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envString(string calldata name, string calldata delim) external view returns (string[] memory value);

    /// Gets the environment variable `name` and parses it as `uint256`.
    /// Reverts if the variable was not found or could not be parsed.
    function envUint(string calldata name) external view returns (uint256 value);

    /// Gets the environment variable `name` and parses it as an array of `uint256`, delimited by `delim`.
    /// Reverts if the variable was not found or could not be parsed.
    function envUint(string calldata name, string calldata delim) external view returns (uint256[] memory value);

    /// Returns true if `forge` command was executed in given context.
    function isContext(ForgeContext context) external view returns (bool result);

    /// 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);

    /// Gets the address for a given private key.
    function addr(uint256 privateKey) external pure returns (address keyAddr);

    /// Gets all the logs according to specified filter.
    function eth_getLogs(uint256 fromBlock, uint256 toBlock, address target, bytes32[] calldata topics)
        external
        returns (EthGetLogs[] memory logs);

    /// Gets the current `block.blobbasefee`.
    /// You should use this instead of `block.blobbasefee` if you use `vm.blobBaseFee`, as `block.blobbasefee` is 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 getBlobBaseFee() external view returns (uint256 blobBaseFee);

    /// Gets the current `block.number`.
    /// You should use this instead of `block.number` if you use `vm.roll`, as `block.number` is 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 getBlockNumber() external view returns (uint256 height);

    /// Gets the current `block.timestamp`.
    /// You should use this instead of `block.timestamp` if you use `vm.warp`, as `block.timestamp` is 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 getBlockTimestamp() external view returns (uint256 timestamp);

    /// Gets the map key and parent of a mapping at a given slot, for a given address.
    function getMappingKeyAndParentOf(address target, bytes32 elementSlot)
        external
        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);

    /// 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);

    /// 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);

    /// Gets all the recorded logs.
    function getRecordedLogs() external returns (Log[] memory logs);

    /// Gets the gas used in the last call.
    function lastCallGas() external view returns (Gas memory gas);

    /// Loads a storage slot from an address.
    function load(address target, bytes32 slot) external view returns (bytes32 data);

    /// Pauses gas metering (i.e. gas usage is not counted). Noop if already paused.
    function pauseGasMetering() external;

    /// Records all storage reads and writes.
    function record() external;

    /// Record all the transaction logs.
    function recordLogs() external;

    /// Reset gas metering (i.e. gas usage is set to gas limit).
    function resetGasMetering() external;

    /// Resumes gas metering (i.e. gas usage is counted again). Noop if already on.
    function resumeGasMetering() external;

    /// Performs an Ethereum JSON-RPC request to the current fork URL.
    function rpc(string calldata method, string calldata params) external returns (bytes memory data);

    /// Performs an Ethereum JSON-RPC request to the given endpoint.
    function rpc(string calldata urlOrAlias, string calldata method, string calldata params)
        external
        returns (bytes memory data);

    /// Starts recording all map SSTOREs for later retrieval.
    function startMappingRecording() external;

    /// Record all account accesses as part of CREATE, CALL or SELFDESTRUCT opcodes in order,
    /// along with the context of the calls
    function startStateDiffRecording() external;

    /// Returns an ordered array of all account accesses from a `vm.startStateDiffRecording` session.
    function stopAndReturnStateDiff() external returns (AccountAccess[] memory accountAccesses);

    /// Stops recording all map SSTOREs for later retrieval and clears the recorded data.
    function stopMappingRecording() external;

    // ======== Filesystem ========

    /// Closes file for reading, resetting the offset and allowing to read it from beginning with readLine.
    /// `path` is relative to the project root.
    function closeFile(string calldata path) external;

    /// Copies the contents of one file to another. This function will **overwrite** the contents of `to`.
    /// On success, the total number of bytes copied is returned and it is equal to the length of the `to` file as reported by `metadata`.
    /// Both `from` and `to` are relative to the project root.
    function copyFile(string calldata from, string calldata to) external returns (uint64 copied);

    /// Creates a new, empty directory at the provided path.
    /// This cheatcode will revert in the following situations, but is not limited to just these cases:
    /// - User lacks permissions to modify `path`.
    /// - A parent of the given path doesn't exist and `recursive` is false.
    /// - `path` already exists and `recursive` is false.
    /// `path` is relative to the project root.
    function createDir(string calldata path, bool recursive) external;

    /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the
    /// artifact in the form of <path>:<contract>:<version> where <contract> and <version> parts are optional.
    function deployCode(string calldata artifactPath) external returns (address deployedAddress);

    /// Deploys a contract from an artifact file. Takes in the relative path to the json file or the path to the
    /// artifact in the form of <path>:<contract>:<version> where <contract> and <version> parts are optional.
    /// Additionally accepts abi-encoded constructor arguments.
    function deployCode(string calldata artifactPath, bytes calldata constructorArgs)
        external
        returns (address deployedAddress);

    /// Returns true if the given path points to an existing entity, else returns false.
    function exists(string calldata path) external returns (bool result);

    /// Performs a foreign function call via the terminal.
    function ffi(string[] calldata commandInput) external returns (bytes memory result);

    /// Given a path, query the file system to get information about a file, directory, etc.
    function fsMetadata(string calldata path) external view returns (FsMetadata memory metadata);

    /// Gets the artifact path from code (aka. creation code).
    function getArtifactPathByCode(bytes calldata code) external view returns (string memory path);

    /// Gets the artifact path from deployed code (aka. runtime code).
    function getArtifactPathByDeployedCode(bytes calldata deployedCode) external view returns (string memory path);

    /// Gets the creation bytecode from an artifact file. Takes in the relative path to the json file or the path to the
    /// artifact in the form of <path>:<contract>:<version> where <contract> and <version> parts are optional.
    function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode);

    /// Gets the deployed bytecode from an artifact file. Takes in the relative path to the json file or the path to the
    /// artifact in the form of <path>:<contract>:<version> where <contract> and <version> parts are optional.
    function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode);

    /// Returns true if the path exists on disk and is pointing at a directory, else returns false.
    function isDir(string calldata path) external returns (bool result);

    /// Returns true if the path exists on disk and is pointing at a regular file, else returns false.
    function isFile(string calldata path) external returns (bool result);

    /// Get the path of the current project root.
    function projectRoot() external view returns (string memory path);

    /// Prompts the user for a string value in the terminal.
    function prompt(string calldata promptText) external returns (string memory input);

    /// Prompts the user for an address in the terminal.
    function promptAddress(string calldata promptText) external returns (address);

    /// Prompts the user for a hidden string value in the terminal.
    function promptSecret(string calldata promptText) external returns (string memory input);

    /// Prompts the user for hidden uint256 in the terminal (usually pk).
    function promptSecretUint(string calldata promptText) external returns (uint256);

    /// Prompts the user for uint256 in the terminal.
    function promptUint(string calldata promptText) external returns (uint256);

    /// Reads the directory at the given path recursively, up to `maxDepth`.
    /// `maxDepth` defaults to 1, meaning only the direct children of the given directory will be returned.
    /// Follows symbolic links if `followLinks` is true.
    function readDir(string calldata path) external view returns (DirEntry[] memory entries);

    /// See `readDir(string)`.
    function readDir(string calldata path, uint64 maxDepth) external view returns (DirEntry[] memory entries);

    /// See `readDir(string)`.
    function readDir(string calldata path, uint64 maxDepth, bool followLinks)
        external
        view
        returns (DirEntry[] memory entries);

    /// Reads the entire content of file to string. `path` is relative to the project root.
    function readFile(string calldata path) external view returns (string memory data);

    /// Reads the entire content of file as binary. `path` is relative to the project root.
    function readFileBinary(string calldata path) external view returns (bytes memory data);

    /// Reads next line of file to string.
    function readLine(string calldata path) external view returns (string memory line);

    /// Reads a symbolic link, returning the path that the link points to.
    /// This cheatcode will revert in the following situations, but is not limited to just these cases:
    /// - `path` is not a symbolic link.
    /// - `path` does not exist.
    function readLink(string calldata linkPath) external view returns (string memory targetPath);

    /// Removes a directory at the provided path.
    /// This cheatcode will revert in the following situations, but is not limited to just these cases:
    /// - `path` doesn't exist.
    /// - `path` isn't a directory.
    /// - User lacks permissions to modify `path`.
    /// - The directory is not empty and `recursive` is false.
    /// `path` is relative to the project root.
    function removeDir(string calldata path, bool recursive) external;

    /// Removes a file from the filesystem.
    /// This cheatcode will revert in the following situations, but is not limited to just these cases:
    /// - `path` points to a directory.
    /// - The file doesn't exist.
    /// - The user lacks permissions to remove the file.
    /// `path` is relative to the project root.
    function removeFile(string calldata path) external;

    /// Performs a foreign function call via terminal and returns the exit code, stdout, and stderr.
    function tryFfi(string[] calldata commandInput) external returns (FfiResult memory result);

    /// Returns the time since unix epoch in milliseconds.
    function unixTime() external returns (uint256 milliseconds);

    /// Writes data to file, creating a file if it does not exist, and entirely replacing its contents if it does.
    /// `path` is relative to the project root.
    function writeFile(string calldata path, string calldata data) external;

    /// Writes binary data to a file, creating a file if it does not exist, and entirely replacing its contents if it does.
    /// `path` is relative to the project root.
    function writeFileBinary(string calldata path, bytes calldata data) external;

    /// Writes line to file, creating a file if it does not exist.
    /// `path` is relative to the project root.
    function writeLine(string calldata path, string calldata data) external;

    // ======== JSON ========

    /// Checks if `key` exists in a JSON object.
    function keyExistsJson(string calldata json, string calldata key) external view returns (bool);

    /// Parses a string of JSON data at `key` and coerces it to `address`.
    function parseJsonAddress(string calldata json, string calldata key) external pure returns (address);

    /// Parses a string of JSON data at `key` and coerces it to `address[]`.
    function parseJsonAddressArray(string calldata json, string calldata key)
        external
        pure
        returns (address[] memory);

    /// Parses a string of JSON data at `key` and coerces it to `bool`.
    function parseJsonBool(string calldata json, string calldata key) external pure returns (bool);

    /// Parses a string of JSON data at `key` and coerces it to `bool[]`.
    function parseJsonBoolArray(string calldata json, string calldata key) external pure returns (bool[] memory);

    /// Parses a string of JSON data at `key` and coerces it to `bytes`.
    function parseJsonBytes(string calldata json, string calldata key) external pure returns (bytes memory);

    /// Parses a string of JSON data at `key` and coerces it to `bytes32`.
    function parseJsonBytes32(string calldata json, string calldata key) external pure returns (bytes32);

    /// Parses a string of JSON data at `key` and coerces it to `bytes32[]`.
    function parseJsonBytes32Array(string calldata json, string calldata key)
        external
        pure
        returns (bytes32[] memory);

    /// Parses a string of JSON data at `key` and coerces it to `bytes[]`.
    function parseJsonBytesArray(string calldata json, string calldata key) external pure returns (bytes[] memory);

    /// Parses a string of JSON data at `key` and coerces it to `int256`.
    function parseJsonInt(string calldata json, string calldata key) external pure returns (int256);

    /// Parses a string of JSON data at `key` and coerces it to `int256[]`.
    function parseJsonIntArray(string calldata json, string calldata key) external pure returns (int256[] memory);

    /// Returns an array of all the keys in a JSON object.
    function parseJsonKeys(string calldata json, string calldata key) external pure returns (string[] memory keys);

    /// Parses a string of JSON data at `key` and coerces it to `string`.
    function parseJsonString(string calldata json, string calldata key) external pure returns (string memory);

    /// Parses a string of JSON data at `key` and coerces it to `string[]`.
    function parseJsonStringArray(string calldata json, string calldata key) external pure returns (string[] memory);

    /// Parses a string of JSON data at `key` and coerces it to type array corresponding to `typeDescription`.
    function parseJsonTypeArray(string calldata json, string calldata key, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of JSON data and coerces it to type corresponding to `typeDescription`.
    function parseJsonType(string calldata json, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of JSON data at `key` and coerces it to type corresponding to `typeDescription`.
    function parseJsonType(string calldata json, string calldata key, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of JSON data at `key` and coerces it to `uint256`.
    function parseJsonUint(string calldata json, string calldata key) external pure returns (uint256);

    /// Parses a string of JSON data at `key` and coerces it to `uint256[]`.
    function parseJsonUintArray(string calldata json, string calldata key) external pure returns (uint256[] memory);

    /// ABI-encodes a JSON object.
    function parseJson(string calldata json) external pure returns (bytes memory abiEncodedData);

    /// ABI-encodes a JSON object at `key`.
    function parseJson(string calldata json, string calldata key) external pure returns (bytes memory abiEncodedData);

    /// See `serializeJson`.
    function serializeAddress(string calldata objectKey, string calldata valueKey, address value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeAddress(string calldata objectKey, string calldata valueKey, address[] calldata values)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBool(string calldata objectKey, string calldata valueKey, bool value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBool(string calldata objectKey, string calldata valueKey, bool[] calldata values)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32 value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32[] calldata values)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBytes(string calldata objectKey, string calldata valueKey, bytes calldata value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeBytes(string calldata objectKey, string calldata valueKey, bytes[] calldata values)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeInt(string calldata objectKey, string calldata valueKey, int256 value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeInt(string calldata objectKey, string calldata valueKey, int256[] calldata values)
        external
        returns (string memory json);

    /// Serializes a key and value to a JSON object stored in-memory that can be later written to a file.
    /// Returns the stringified version of the specific JSON file up to that moment.
    function serializeJson(string calldata objectKey, string calldata value) external returns (string memory json);

    /// See `serializeJson`.
    function serializeJsonType(string calldata typeDescription, bytes calldata value)
        external
        pure
        returns (string memory json);

    /// See `serializeJson`.
    function serializeJsonType(
        string calldata objectKey,
        string calldata valueKey,
        string calldata typeDescription,
        bytes calldata value
    ) external returns (string memory json);

    /// See `serializeJson`.
    function serializeString(string calldata objectKey, string calldata valueKey, string calldata value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeString(string calldata objectKey, string calldata valueKey, string[] calldata values)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeUintToHex(string calldata objectKey, string calldata valueKey, uint256 value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value)
        external
        returns (string memory json);

    /// See `serializeJson`.
    function serializeUint(string calldata objectKey, string calldata valueKey, uint256[] calldata values)
        external
        returns (string memory json);

    /// Write a serialized JSON object to a file. If the file exists, it will be overwritten.
    function writeJson(string calldata json, string calldata path) external;

    /// Write a serialized JSON object to an **existing** JSON file, replacing a value with key = <value_key.>
    /// This is useful to replace a specific value of a JSON file, without having to parse the entire thing.
    function writeJson(string calldata json, string calldata path, string calldata valueKey) external;

    /// Checks if `key` exists in a JSON object
    /// `keyExists` is being deprecated in favor of `keyExistsJson`. It will be removed in future versions.
    function keyExists(string calldata json, string calldata key) external view returns (bool);

    // ======== Scripting ========

    /// Takes a signed transaction and broadcasts it to the network.
    function broadcastRawTransaction(bytes calldata data) external;

    /// Has the next call (at this call depth only) create transactions that can later be signed and sent onchain.
    /// Broadcasting address is determined by checking the following in order:
    /// 1. If `--sender` argument was provided, that address is used.
    /// 2. If exactly one signer (e.g. private key, hw wallet, keystore) is set when `forge broadcast` is invoked, that signer is used.
    /// 3. Otherwise, default foundry sender (1804c8AB1F12E6bbf3894d4083f33e07309d1f38) is used.
    function broadcast() external;

    /// Has the next call (at this call depth only) create a transaction with the address provided
    /// as the sender that can later be signed and sent onchain.
    function broadcast(address signer) external;

    /// Has the next call (at this call depth only) create a transaction with the private key
    /// provided as the sender that can later be signed and sent onchain.
    function broadcast(uint256 privateKey) external;

    /// Has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain.
    /// Broadcasting address is determined by checking the following in order:
    /// 1. If `--sender` argument was provided, that address is used.
    /// 2. If exactly one signer (e.g. private key, hw wallet, keystore) is set when `forge broadcast` is invoked, that signer is used.
    /// 3. Otherwise, default foundry sender (1804c8AB1F12E6bbf3894d4083f33e07309d1f38) is used.
    function startBroadcast() external;

    /// Has all subsequent calls (at this call depth only) create transactions with the address
    /// provided that can later be signed and sent onchain.
    function startBroadcast(address signer) external;

    /// Has all subsequent calls (at this call depth only) create transactions with the private key
    /// provided that can later be signed and sent onchain.
    function startBroadcast(uint256 privateKey) external;

    /// Stops collecting onchain transactions.
    function stopBroadcast() external;

    // ======== String ========

    /// 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.
    /// Returns 0 in case of an empty `key`.
    function indexOf(string calldata input, string calldata key) external pure returns (uint256);

    /// Parses the given `string` into an `address`.
    function parseAddress(string calldata stringifiedValue) external pure returns (address parsedValue);

    /// Parses the given `string` into a `bool`.
    function parseBool(string calldata stringifiedValue) external pure returns (bool parsedValue);

    /// Parses the given `string` into `bytes`.
    function parseBytes(string calldata stringifiedValue) external pure returns (bytes memory parsedValue);

    /// Parses the given `string` into a `bytes32`.
    function parseBytes32(string calldata stringifiedValue) external pure returns (bytes32 parsedValue);

    /// Parses the given `string` into a `int256`.
    function parseInt(string calldata stringifiedValue) external pure returns (int256 parsedValue);

    /// Parses the given `string` into a `uint256`.
    function parseUint(string calldata stringifiedValue) external pure returns (uint256 parsedValue);

    /// Replaces occurrences of `from` in the given `string` with `to`.
    function replace(string calldata input, string calldata from, string calldata to)
        external
        pure
        returns (string memory output);

    /// Splits the given `string` into an array of strings divided by the `delimiter`.
    function split(string calldata input, string calldata delimiter) external pure returns (string[] memory outputs);

    /// Converts the given `string` value to Lowercase.
    function toLowercase(string calldata input) external pure returns (string memory output);

    /// Converts the given value to a `string`.
    function toString(address value) external pure returns (string memory stringifiedValue);

    /// Converts the given value to a `string`.
    function toString(bytes calldata value) external pure returns (string memory stringifiedValue);

    /// Converts the given value to a `string`.
    function toString(bytes32 value) external pure returns (string memory stringifiedValue);

    /// Converts the given value to a `string`.
    function toString(bool value) external pure returns (string memory stringifiedValue);

    /// Converts the given value to a `string`.
    function toString(uint256 value) external pure returns (string memory stringifiedValue);

    /// Converts the given value to a `string`.
    function toString(int256 value) external pure returns (string memory stringifiedValue);

    /// Converts the given `string` value to Uppercase.
    function toUppercase(string calldata input) external pure returns (string memory output);

    /// Trims leading and trailing whitespace from the given `string` value.
    function trim(string calldata input) external pure returns (string memory output);

    // ======== Testing ========

    /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Formats values with decimals in failure message.
    function assertApproxEqAbsDecimal(uint256 left, uint256 right, uint256 maxDelta, uint256 decimals) external pure;

    /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertApproxEqAbsDecimal(
        uint256 left,
        uint256 right,
        uint256 maxDelta,
        uint256 decimals,
        string calldata error
    ) external pure;

    /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Formats values with decimals in failure message.
    function assertApproxEqAbsDecimal(int256 left, int256 right, uint256 maxDelta, uint256 decimals) external pure;

    /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertApproxEqAbsDecimal(
        int256 left,
        int256 right,
        uint256 maxDelta,
        uint256 decimals,
        string calldata error
    ) external pure;

    /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`.
    function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta) external pure;

    /// Compares two `uint256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Includes error message into revert string on failure.
    function assertApproxEqAbs(uint256 left, uint256 right, uint256 maxDelta, string calldata error) external pure;

    /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`.
    function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta) external pure;

    /// Compares two `int256` values. Expects difference to be less than or equal to `maxDelta`.
    /// Includes error message into revert string on failure.
    function assertApproxEqAbs(int256 left, int256 right, uint256 maxDelta, string calldata error) external pure;

    /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Formats values with decimals in failure message.
    function assertApproxEqRelDecimal(uint256 left, uint256 right, uint256 maxPercentDelta, uint256 decimals)
        external
        pure;

    /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertApproxEqRelDecimal(
        uint256 left,
        uint256 right,
        uint256 maxPercentDelta,
        uint256 decimals,
        string calldata error
    ) external pure;

    /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Formats values with decimals in failure message.
    function assertApproxEqRelDecimal(int256 left, int256 right, uint256 maxPercentDelta, uint256 decimals)
        external
        pure;

    /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertApproxEqRelDecimal(
        int256 left,
        int256 right,
        uint256 maxPercentDelta,
        uint256 decimals,
        string calldata error
    ) external pure;

    /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    function assertApproxEqRel(uint256 left, uint256 right, uint256 maxPercentDelta) external pure;

    /// Compares two `uint256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Includes error message into revert string on failure.
    function assertApproxEqRel(uint256 left, uint256 right, uint256 maxPercentDelta, string calldata error)
        external
        pure;

    /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    function assertApproxEqRel(int256 left, int256 right, uint256 maxPercentDelta) external pure;

    /// Compares two `int256` values. Expects relative difference in percents to be less than or equal to `maxPercentDelta`.
    /// `maxPercentDelta` is an 18 decimal fixed point number, where 1e18 == 100%
    /// Includes error message into revert string on failure.
    function assertApproxEqRel(int256 left, int256 right, uint256 maxPercentDelta, string calldata error)
        external
        pure;

    /// Asserts that two `uint256` values are equal, formatting them with decimals in failure message.
    function assertEqDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Asserts that two `uint256` values are equal, formatting them with decimals in failure message.
    /// Includes error message into revert string on failure.
    function assertEqDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Asserts that two `int256` values are equal, formatting them with decimals in failure message.
    function assertEqDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Asserts that two `int256` values are equal, formatting them with decimals in failure message.
    /// Includes error message into revert string on failure.
    function assertEqDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Asserts that two `bool` values are equal.
    function assertEq(bool left, bool right) external pure;

    /// Asserts that two `bool` values are equal and includes error message into revert string on failure.
    function assertEq(bool left, bool right, string calldata error) external pure;

    /// Asserts that two `string` values are equal.
    function assertEq(string calldata left, string calldata right) external pure;

    /// Asserts that two `string` values are equal and includes error message into revert string on failure.
    function assertEq(string calldata left, string calldata right, string calldata error) external pure;

    /// Asserts that two `bytes` values are equal.
    function assertEq(bytes calldata left, bytes calldata right) external pure;

    /// Asserts that two `bytes` values are equal and includes error message into revert string on failure.
    function assertEq(bytes calldata left, bytes calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bool` values are equal.
    function assertEq(bool[] calldata left, bool[] calldata right) external pure;

    /// Asserts that two arrays of `bool` values are equal and includes error message into revert string on failure.
    function assertEq(bool[] calldata left, bool[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `uint256 values are equal.
    function assertEq(uint256[] calldata left, uint256[] calldata right) external pure;

    /// Asserts that two arrays of `uint256` values are equal and includes error message into revert string on failure.
    function assertEq(uint256[] calldata left, uint256[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `int256` values are equal.
    function assertEq(int256[] calldata left, int256[] calldata right) external pure;

    /// Asserts that two arrays of `int256` values are equal and includes error message into revert string on failure.
    function assertEq(int256[] calldata left, int256[] calldata right, string calldata error) external pure;

    /// Asserts that two `uint256` values are equal.
    function assertEq(uint256 left, uint256 right) external pure;

    /// Asserts that two arrays of `address` values are equal.
    function assertEq(address[] calldata left, address[] calldata right) external pure;

    /// Asserts that two arrays of `address` values are equal and includes error message into revert string on failure.
    function assertEq(address[] calldata left, address[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bytes32` values are equal.
    function assertEq(bytes32[] calldata left, bytes32[] calldata right) external pure;

    /// Asserts that two arrays of `bytes32` values are equal and includes error message into revert string on failure.
    function assertEq(bytes32[] calldata left, bytes32[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `string` values are equal.
    function assertEq(string[] calldata left, string[] calldata right) external pure;

    /// Asserts that two arrays of `string` values are equal and includes error message into revert string on failure.
    function assertEq(string[] calldata left, string[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bytes` values are equal.
    function assertEq(bytes[] calldata left, bytes[] calldata right) external pure;

    /// Asserts that two arrays of `bytes` values are equal and includes error message into revert string on failure.
    function assertEq(bytes[] calldata left, bytes[] calldata right, string calldata error) external pure;

    /// Asserts that two `uint256` values are equal and includes error message into revert string on failure.
    function assertEq(uint256 left, uint256 right, string calldata error) external pure;

    /// Asserts that two `int256` values are equal.
    function assertEq(int256 left, int256 right) external pure;

    /// Asserts that two `int256` values are equal and includes error message into revert string on failure.
    function assertEq(int256 left, int256 right, string calldata error) external pure;

    /// Asserts that two `address` values are equal.
    function assertEq(address left, address right) external pure;

    /// Asserts that two `address` values are equal and includes error message into revert string on failure.
    function assertEq(address left, address right, string calldata error) external pure;

    /// Asserts that two `bytes32` values are equal.
    function assertEq(bytes32 left, bytes32 right) external pure;

    /// Asserts that two `bytes32` values are equal and includes error message into revert string on failure.
    function assertEq(bytes32 left, bytes32 right, string calldata error) external pure;

    /// Asserts that the given condition is false.
    function assertFalse(bool condition) external pure;

    /// Asserts that the given condition is false and includes error message into revert string on failure.
    function assertFalse(bool condition, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than or equal to second.
    /// Formats values with decimals in failure message.
    function assertGeDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than or equal to second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertGeDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be greater than or equal to second.
    /// Formats values with decimals in failure message.
    function assertGeDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Compares two `int256` values. Expects first value to be greater than or equal to second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertGeDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than or equal to second.
    function assertGe(uint256 left, uint256 right) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than or equal to second.
    /// Includes error message into revert string on failure.
    function assertGe(uint256 left, uint256 right, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be greater than or equal to second.
    function assertGe(int256 left, int256 right) external pure;

    /// Compares two `int256` values. Expects first value to be greater than or equal to second.
    /// Includes error message into revert string on failure.
    function assertGe(int256 left, int256 right, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than second.
    /// Formats values with decimals in failure message.
    function assertGtDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertGtDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be greater than second.
    /// Formats values with decimals in failure message.
    function assertGtDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Compares two `int256` values. Expects first value to be greater than second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertGtDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than second.
    function assertGt(uint256 left, uint256 right) external pure;

    /// Compares two `uint256` values. Expects first value to be greater than second.
    /// Includes error message into revert string on failure.
    function assertGt(uint256 left, uint256 right, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be greater than second.
    function assertGt(int256 left, int256 right) external pure;

    /// Compares two `int256` values. Expects first value to be greater than second.
    /// Includes error message into revert string on failure.
    function assertGt(int256 left, int256 right, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be less than or equal to second.
    /// Formats values with decimals in failure message.
    function assertLeDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Compares two `uint256` values. Expects first value to be less than or equal to second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertLeDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be less than or equal to second.
    /// Formats values with decimals in failure message.
    function assertLeDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Compares two `int256` values. Expects first value to be less than or equal to second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertLeDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be less than or equal to second.
    function assertLe(uint256 left, uint256 right) external pure;

    /// Compares two `uint256` values. Expects first value to be less than or equal to second.
    /// Includes error message into revert string on failure.
    function assertLe(uint256 left, uint256 right, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be less than or equal to second.
    function assertLe(int256 left, int256 right) external pure;

    /// Compares two `int256` values. Expects first value to be less than or equal to second.
    /// Includes error message into revert string on failure.
    function assertLe(int256 left, int256 right, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be less than second.
    /// Formats values with decimals in failure message.
    function assertLtDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Compares two `uint256` values. Expects first value to be less than second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertLtDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be less than second.
    /// Formats values with decimals in failure message.
    function assertLtDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Compares two `int256` values. Expects first value to be less than second.
    /// Formats values with decimals in failure message. Includes error message into revert string on failure.
    function assertLtDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Compares two `uint256` values. Expects first value to be less than second.
    function assertLt(uint256 left, uint256 right) external pure;

    /// Compares two `uint256` values. Expects first value to be less than second.
    /// Includes error message into revert string on failure.
    function assertLt(uint256 left, uint256 right, string calldata error) external pure;

    /// Compares two `int256` values. Expects first value to be less than second.
    function assertLt(int256 left, int256 right) external pure;

    /// Compares two `int256` values. Expects first value to be less than second.
    /// Includes error message into revert string on failure.
    function assertLt(int256 left, int256 right, string calldata error) external pure;

    /// Asserts that two `uint256` values are not equal, formatting them with decimals in failure message.
    function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals) external pure;

    /// Asserts that two `uint256` values are not equal, formatting them with decimals in failure message.
    /// Includes error message into revert string on failure.
    function assertNotEqDecimal(uint256 left, uint256 right, uint256 decimals, string calldata error) external pure;

    /// Asserts that two `int256` values are not equal, formatting them with decimals in failure message.
    function assertNotEqDecimal(int256 left, int256 right, uint256 decimals) external pure;

    /// Asserts that two `int256` values are not equal, formatting them with decimals in failure message.
    /// Includes error message into revert string on failure.
    function assertNotEqDecimal(int256 left, int256 right, uint256 decimals, string calldata error) external pure;

    /// Asserts that two `bool` values are not equal.
    function assertNotEq(bool left, bool right) external pure;

    /// Asserts that two `bool` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bool left, bool right, string calldata error) external pure;

    /// Asserts that two `string` values are not equal.
    function assertNotEq(string calldata left, string calldata right) external pure;

    /// Asserts that two `string` values are not equal and includes error message into revert string on failure.
    function assertNotEq(string calldata left, string calldata right, string calldata error) external pure;

    /// Asserts that two `bytes` values are not equal.
    function assertNotEq(bytes calldata left, bytes calldata right) external pure;

    /// Asserts that two `bytes` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bytes calldata left, bytes calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bool` values are not equal.
    function assertNotEq(bool[] calldata left, bool[] calldata right) external pure;

    /// Asserts that two arrays of `bool` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bool[] calldata left, bool[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `uint256` values are not equal.
    function assertNotEq(uint256[] calldata left, uint256[] calldata right) external pure;

    /// Asserts that two arrays of `uint256` values are not equal and includes error message into revert string on failure.
    function assertNotEq(uint256[] calldata left, uint256[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `int256` values are not equal.
    function assertNotEq(int256[] calldata left, int256[] calldata right) external pure;

    /// Asserts that two arrays of `int256` values are not equal and includes error message into revert string on failure.
    function assertNotEq(int256[] calldata left, int256[] calldata right, string calldata error) external pure;

    /// Asserts that two `uint256` values are not equal.
    function assertNotEq(uint256 left, uint256 right) external pure;

    /// Asserts that two arrays of `address` values are not equal.
    function assertNotEq(address[] calldata left, address[] calldata right) external pure;

    /// Asserts that two arrays of `address` values are not equal and includes error message into revert string on failure.
    function assertNotEq(address[] calldata left, address[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bytes32` values are not equal.
    function assertNotEq(bytes32[] calldata left, bytes32[] calldata right) external pure;

    /// Asserts that two arrays of `bytes32` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bytes32[] calldata left, bytes32[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `string` values are not equal.
    function assertNotEq(string[] calldata left, string[] calldata right) external pure;

    /// Asserts that two arrays of `string` values are not equal and includes error message into revert string on failure.
    function assertNotEq(string[] calldata left, string[] calldata right, string calldata error) external pure;

    /// Asserts that two arrays of `bytes` values are not equal.
    function assertNotEq(bytes[] calldata left, bytes[] calldata right) external pure;

    /// Asserts that two arrays of `bytes` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bytes[] calldata left, bytes[] calldata right, string calldata error) external pure;

    /// Asserts that two `uint256` values are not equal and includes error message into revert string on failure.
    function assertNotEq(uint256 left, uint256 right, string calldata error) external pure;

    /// Asserts that two `int256` values are not equal.
    function assertNotEq(int256 left, int256 right) external pure;

    /// Asserts that two `int256` values are not equal and includes error message into revert string on failure.
    function assertNotEq(int256 left, int256 right, string calldata error) external pure;

    /// Asserts that two `address` values are not equal.
    function assertNotEq(address left, address right) external pure;

    /// Asserts that two `address` values are not equal and includes error message into revert string on failure.
    function assertNotEq(address left, address right, string calldata error) external pure;

    /// Asserts that two `bytes32` values are not equal.
    function assertNotEq(bytes32 left, bytes32 right) external pure;

    /// Asserts that two `bytes32` values are not equal and includes error message into revert string on failure.
    function assertNotEq(bytes32 left, bytes32 right, string calldata error) external pure;

    /// Asserts that the given condition is true.
    function assertTrue(bool condition) external pure;

    /// Asserts that the given condition is true and includes error message into revert string on failure.
    function assertTrue(bool condition, string calldata error) external pure;

    /// If the condition is false, discard this run's fuzz inputs and generate new ones.
    function assume(bool condition) external pure;

    /// Discard this run's fuzz inputs and generate new ones if next call reverted.
    function assumeNoRevert() external pure;

    /// Writes a breakpoint to jump to in the debugger.
    function breakpoint(string calldata char) external;

    /// Writes a conditional breakpoint to jump to in the debugger.
    function breakpoint(string calldata char, bool value) external;

    /// Returns the Foundry version.
    /// Format: <cargo_version>+<git_sha>+<build_timestamp>
    /// Sample output: 0.2.0+faa94c384+202407110019
    /// Note: Build timestamps may vary slightly across platforms due to separate CI jobs.
    /// For reliable version comparisons, use YYYYMMDD0000 format (e.g., >= 202407110000)
    /// to compare timestamps while ignoring minor time differences.
    function getFoundryVersion() external view returns (string memory version);

    /// Returns the RPC url for the given alias.
    function rpcUrl(string calldata rpcAlias) external view returns (string memory json);

    /// Returns all rpc urls and their aliases as structs.
    function rpcUrlStructs() external view returns (Rpc[] memory urls);

    /// Returns all rpc urls and their aliases `[alias, url][]`.
    function rpcUrls() external view returns (string[2][] memory urls);

    /// Suspends execution of the main thread for `duration` milliseconds.
    function sleep(uint256 duration) external;

    // ======== Toml ========

    /// Checks if `key` exists in a TOML table.
    function keyExistsToml(string calldata toml, string calldata key) external view returns (bool);

    /// Parses a string of TOML data at `key` and coerces it to `address`.
    function parseTomlAddress(string calldata toml, string calldata key) external pure returns (address);

    /// Parses a string of TOML data at `key` and coerces it to `address[]`.
    function parseTomlAddressArray(string calldata toml, string calldata key)
        external
        pure
        returns (address[] memory);

    /// Parses a string of TOML data at `key` and coerces it to `bool`.
    function parseTomlBool(string calldata toml, string calldata key) external pure returns (bool);

    /// Parses a string of TOML data at `key` and coerces it to `bool[]`.
    function parseTomlBoolArray(string calldata toml, string calldata key) external pure returns (bool[] memory);

    /// Parses a string of TOML data at `key` and coerces it to `bytes`.
    function parseTomlBytes(string calldata toml, string calldata key) external pure returns (bytes memory);

    /// Parses a string of TOML data at `key` and coerces it to `bytes32`.
    function parseTomlBytes32(string calldata toml, string calldata key) external pure returns (bytes32);

    /// Parses a string of TOML data at `key` and coerces it to `bytes32[]`.
    function parseTomlBytes32Array(string calldata toml, string calldata key)
        external
        pure
        returns (bytes32[] memory);

    /// Parses a string of TOML data at `key` and coerces it to `bytes[]`.
    function parseTomlBytesArray(string calldata toml, string calldata key) external pure returns (bytes[] memory);

    /// Parses a string of TOML data at `key` and coerces it to `int256`.
    function parseTomlInt(string calldata toml, string calldata key) external pure returns (int256);

    /// Parses a string of TOML data at `key` and coerces it to `int256[]`.
    function parseTomlIntArray(string calldata toml, string calldata key) external pure returns (int256[] memory);

    /// Returns an array of all the keys in a TOML table.
    function parseTomlKeys(string calldata toml, string calldata key) external pure returns (string[] memory keys);

    /// Parses a string of TOML data at `key` and coerces it to `string`.
    function parseTomlString(string calldata toml, string calldata key) external pure returns (string memory);

    /// Parses a string of TOML data at `key` and coerces it to `string[]`.
    function parseTomlStringArray(string calldata toml, string calldata key) external pure returns (string[] memory);

    /// Parses a string of TOML data at `key` and coerces it to type array corresponding to `typeDescription`.
    function parseTomlTypeArray(string calldata toml, string calldata key, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of TOML data and coerces it to type corresponding to `typeDescription`.
    function parseTomlType(string calldata toml, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of TOML data at `key` and coerces it to type corresponding to `typeDescription`.
    function parseTomlType(string calldata toml, string calldata key, string calldata typeDescription)
        external
        pure
        returns (bytes memory);

    /// Parses a string of TOML data at `key` and coerces it to `uint256`.
    function parseTomlUint(string calldata toml, string calldata key) external pure returns (uint256);

    /// Parses a string of TOML data at `key` and coerces it to `uint256[]`.
    function parseTomlUintArray(string calldata toml, string calldata key) external pure returns (uint256[] memory);

    /// ABI-encodes a TOML table.
    function parseToml(string calldata toml) external pure returns (bytes memory abiEncodedData);

    /// ABI-encodes a TOML table at `key`.
    function parseToml(string calldata toml, string calldata key) external pure returns (bytes memory abiEncodedData);

    /// Takes serialized JSON, converts to TOML and write a serialized TOML to a file.
    function writeToml(string calldata json, string calldata path) external;

    /// Takes serialized JSON, converts to TOML and write a serialized TOML table to an **existing** TOML file, replacing a value with key = <value_key.>
    /// This is useful to replace a specific value of a TOML file, without having to parse the entire thing.
    function writeToml(string calldata json, string calldata path, string calldata valueKey) external;

    // ======== Utilities ========

    /// Compute the address of a contract created with CREATE2 using the given CREATE2 deployer.
    function computeCreate2Address(bytes32 salt, bytes32 initCodeHash, address deployer)
        external
        pure
        returns (address);

    /// Compute the address of a contract created with CREATE2 using the default CREATE2 deployer.
    function computeCreate2Address(bytes32 salt, bytes32 initCodeHash) external pure returns (address);

    /// Compute the address a contract will be deployed at for a given deployer address and nonce.
    function computeCreateAddress(address deployer, uint256 nonce) external pure returns (address);

    /// Utility cheatcode to copy storage of `from` contract to another `to` contract.
    function copyStorage(address from, address to) external;

    /// Returns ENS namehash for provided string.
    function ensNamehash(string calldata name) external pure returns (bytes32);

    /// Gets the label for the specified address.
    function getLabel(address account) external view returns (string memory currentLabel);

    /// Labels an address in call traces.
    function label(address account, string calldata newLabel) external;

    /// Pauses collection of call traces. Useful in cases when you want to skip tracing of
    /// complex calls which are not useful for debugging.
    function pauseTracing() external view;

    /// Returns a random `address`.
    function randomAddress() external returns (address);

    /// Returns an random `bool`.
    function randomBool() external view returns (bool);

    /// Returns an random byte array value of the given length.
    function randomBytes(uint256 len) external view returns (bytes memory);

    /// Returns an random `int256` value.
    function randomInt() external view returns (int256);

    /// Returns an random `int256` value of given bits.
    function randomInt(uint256 bits) external view returns (int256);

    /// Returns a random uint256 value.
    function randomUint() external returns (uint256);

    /// Returns random uint256 value between the provided range (=min..=max).
    function randomUint(uint256 min, uint256 max) external returns (uint256);

    /// Returns an random `uint256` value of given bits.
    function randomUint(uint256 bits) external view returns (uint256);

    /// Unpauses collection of call traces.
    function resumeTracing() external view;

    /// Utility cheatcode to set arbitrary storage for given target address.
    function setArbitraryStorage(address target) external;

    /// Encodes a `bytes` value to a base64url string.
    function toBase64URL(bytes calldata data) external pure returns (string memory);

    /// Encodes a `string` value to a base64url string.
    function toBase64URL(string calldata data) external pure returns (string memory);

    /// Encodes a `bytes` value to a base64 string.
    function toBase64(bytes calldata data) external pure returns (string memory);

    /// Encodes a `string` value to a base64 string.
    function toBase64(string calldata data) external pure returns (string memory);
}

/// The `Vm` interface does allow manipulation of the EVM state. These are all intended to be used
/// in tests, but it is not recommended to use these cheats in scripts.
interface Vm is VmSafe {
    // ======== EVM ========

    /// Returns the identifier of the currently active fork. Reverts if no fork is currently active.
    function activeFork() external view returns (uint256 forkId);

    /// In forking mode, explicitly grant the given address cheatcode access.
    function allowCheatcodes(address account) external;

    /// Sets `block.blobbasefee`
    function blobBaseFee(uint256 newBlobBaseFee) external;

    /// Sets the blobhashes in the transaction.
    /// Not available on EVM versions before Cancun.
    /// If used on unsupported EVM versions it will revert.
    function blobhashes(bytes32[] calldata hashes) external;

    /// Sets `block.chainid`.
    function chainId(uint256 newChainId) external;

    /// Clears all mocked calls.
    function clearMockedCalls() external;

    /// Sets `block.coinbase`.
    function coinbase(address newCoinbase) external;

    /// Creates a new fork with the given endpoint and the _latest_ block and returns the identifier of the fork.
    function createFork(string calldata urlOrAlias) external returns (uint256 forkId);

    /// Creates a new fork with the given endpoint and block and returns the identifier of the fork.
    function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);

    /// Creates a new fork with the given endpoint and at the block the given transaction was mined in,
    /// replays all transaction mined in the block before the transaction, and returns the identifier of the fork.
    function createFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);

    /// Creates and also selects a new fork with the given endpoint and the latest block and returns the identifier of the fork.
    function createSelectFork(string calldata urlOrAlias) external returns (uint256 forkId);

    /// Creates and also selects a new fork with the given endpoint and block and returns the identifier of the fork.
    function createSelectFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);

    /// Creates and also selects new fork with the given endpoint and at the block the given transaction was mined in,
    /// replays all transaction mined in the block before the transaction, returns the identifier of the fork.
    function createSelectFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);

    /// Sets an address' balance.
    function deal(address account, uint256 newBalance) external;

    /// Removes the snapshot with the given ID created by `snapshot`.
    /// Takes the snapshot ID to delete.
    /// Returns `true` if the snapshot was successfully deleted.
    /// Returns `false` if the snapshot does not exist.
    function deleteSnapshot(uint256 snapshotId) external returns (bool success);

    /// Removes _all_ snapshots previously created by `snapshot`.
    function deleteSnapshots() external;

    /// Sets `block.difficulty`.
    /// Not available on EVM versions from Paris onwards. Use `prevrandao` instead.
    /// Reverts if used on unsupported EVM versions.
    function difficulty(uint256 newDifficulty) external;

    /// Dump a genesis JSON file's `allocs` to disk.
    function dumpState(string calldata pathToStateJson) external;

    /// Sets an address' code.
    function etch(address target, bytes calldata newRuntimeBytecode) external;

    /// Sets `block.basefee`.
    function fee(uint256 newBasefee) external;

    /// Gets the blockhashes from the current transaction.
    /// Not available on EVM versions before Cancun.
    /// If used on unsupported EVM versions it will revert.
    function getBlobhashes() external view returns (bytes32[] memory hashes);

    /// Returns true if the account is marked as persistent.
    function isPersistent(address account) external view returns (bool persistent);

    /// Load a genesis JSON file's `allocs` into the in-memory revm state.
    function loadAllocs(string calldata pathToAllocsJson) external;

    /// Marks that the account(s) should use persistent storage across fork swaps in a multifork setup
    /// Meaning, changes made to the state of this account will be kept when switching forks.
    function makePersistent(address account) external;

    /// See `makePersistent(address)`.
    function makePersistent(address account0, address account1) external;

    /// See `makePersistent(address)`.
    function makePersistent(address account0, address account1, address account2) external;

    /// See `makePersistent(address)`.
    function makePersistent(address[] calldata accounts) external;

    /// Reverts a call to an address with specified revert data.
    function mockCallRevert(address callee, bytes calldata data, bytes calldata revertData) external;

    /// Reverts a call to an address with a specific `msg.value`, with specified revert data.
    function mockCallRevert(address callee, uint256 msgValue, bytes calldata data, bytes calldata revertData)
        external;

    /// Mocks a call to an address, returning specified data.
    /// Calldata can either be strict or a partial match, e.g. if you only
    /// pass a Solidity selector to the expected calldata, then the entire Solidity
    /// function will be mocked.
    function mockCall(address callee, bytes calldata data, bytes calldata returnData) external;

    /// Mocks a call to an address with a specific `msg.value`, returning specified data.
    /// Calldata match takes precedence over `msg.value` in case of ambiguity.
    function mockCall(address callee, uint256 msgValue, bytes calldata data, bytes calldata returnData) external;

    /// Whenever a call is made to `callee` with calldata `data`, this cheatcode instead calls
    /// `target` with the same calldata. This functionality is similar to a delegate call made to
    /// `target` contract from `callee`.
    /// Can be used to substitute a call to a function with another implementation that captures
    /// the primary logic of the original function but is easier to reason about.
    /// If calldata is not a strict match then partial match by selector is attempted.
    function mockFunction(address callee, address target, bytes calldata data) external;

    /// Sets the *next* call's `msg.sender` to be the input address.
    function prank(address msgSender) external;

    /// Sets the *next* call's `msg.sender` to be the input address, and the `tx.origin` to be the second input.
    function prank(address msgSender, address txOrigin) external;

    /// Sets `block.prevrandao`.
    /// Not available on EVM versions before Paris. Use `difficulty` instead.
    /// If used on unsupported EVM versions it will revert.
    function prevrandao(bytes32 newPrevrandao) external;

    /// Sets `block.prevrandao`.
    /// Not available on EVM versions before Paris. Use `difficulty` instead.
    /// If used on unsupported EVM versions it will revert.
    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);

    /// Resets the nonce of an account to 0 for EOAs and 1 for contract accounts.
    function resetNonce(address account) external;

    /// Revert the state of the EVM to a previous snapshot
    /// Takes the snapshot ID to revert to.
    /// Returns `true` if the snapshot was successfully reverted.
    /// Returns `false` if the snapshot does not exist.
    /// **Note:** This does not automatically delete the snapshot. To delete the snapshot use `deleteSnapshot`.
    function revertTo(uint256 snapshotId) external returns (bool success);

    /// Revert the state of the EVM to a previous snapshot and automatically deletes the snapshots
    /// Takes the snapshot ID to revert to.
    /// Returns `true` if the snapshot was successfully reverted and deleted.
    /// Returns `false` if the snapshot does not exist.
    function revertToAndDelete(uint256 snapshotId) external returns (bool success);

    /// Revokes persistent status from the address, previously added via `makePersistent`.
    function revokePersistent(address account) external;

    /// See `revokePersistent(address)`.
    function revokePersistent(address[] calldata accounts) external;

    /// Sets `block.height`.
    function roll(uint256 newHeight) external;

    /// Updates the currently active fork to given block number
    /// This is similar to `roll` but for the currently active fork.
    function rollFork(uint256 blockNumber) external;

    /// Updates the currently active fork to given transaction. This will `rollFork` with the number
    /// of the block the transaction was mined in and replays all transaction mined before it in the block.
    function rollFork(bytes32 txHash) external;

    /// Updates the given fork to given block number.
    function rollFork(uint256 forkId, uint256 blockNumber) external;

    /// Updates the given fork to block number of the given transaction and replays all transaction mined before it in the block.
    function rollFork(uint256 forkId, bytes32 txHash) external;

    /// Takes a fork identifier created by `createFork` and sets the corresponding forked state as active.
    function selectFork(uint256 forkId) external;

    /// Set blockhash for the current block.
    /// It only sets the blockhash for blocks where `block.number - 256 <= number < block.number`.
    function setBlockhash(uint256 blockNumber, bytes32 blockHash) external;

    /// Sets the nonce of an account. Must be higher than the current nonce of the account.
    function setNonce(address account, uint64 newNonce) external;

    /// Sets the nonce of an account to an arbitrary value.
    function setNonceUnsafe(address account, uint64 newNonce) external;

    /// Snapshot the current state of the evm.
    /// Returns the ID of the snapshot that was created.
    /// To revert a snapshot use `revertTo`.
    function snapshot() external returns (uint256 snapshotId);

    /// Sets all subsequent calls' `msg.sender` to be the input address until `stopPrank` is called.
    function startPrank(address msgSender) external;

    /// Sets all subsequent calls' `msg.sender` to be the input address until `stopPrank` is called, and the `tx.origin` to be the second input.
    function startPrank(address msgSender, address txOrigin) external;

    /// Resets subsequent calls' `msg.sender` to be `address(this)`.
    function stopPrank() external;

    /// Stores a value to an address' storage slot.
    function store(address target, bytes32 slot, bytes32 value) external;

    /// Fetches the given transaction from the active fork and executes it on the current state.
    function transact(bytes32 txHash) external;

    /// Fetches the given transaction from the given fork and executes it on the current state.
    function transact(uint256 forkId, bytes32 txHash) external;

    /// Sets `tx.gasprice`.
    function txGasPrice(uint256 newGasPrice) external;

    /// Sets `block.timestamp`.
    function warp(uint256 newTimestamp) external;

    // ======== Testing ========

    /// Expect a call to an address with the specified `msg.value` and calldata, and a *minimum* amount of gas.
    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data) external;

    /// Expect given number of calls to an address with the specified `msg.value` and calldata, and a *minimum* amount of gas.
    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count)
        external;

    /// Expects a call to an address with the specified calldata.
    /// Calldata can either be a strict or a partial match.
    function expectCall(address callee, bytes calldata data) external;

    /// Expects given number of calls to an address with the specified calldata.
    function expectCall(address callee, bytes calldata data, uint64 count) external;

    /// Expects a call to an address with the specified `msg.value` and calldata.
    function expectCall(address callee, uint256 msgValue, bytes calldata data) external;

    /// Expects given number of calls to an address with the specified `msg.value` and calldata.
    function expectCall(address callee, uint256 msgValue, bytes calldata data, uint64 count) external;

    /// Expect a call to an address with the specified `msg.value`, gas, and calldata.
    function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data) external;

    /// Expects given number of calls to an address with the specified `msg.value`, gas, and calldata.
    function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data, uint64 count) external;

    /// Prepare an expected anonymous log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData.).
    /// Call this function, then emit an anonymous event, then call a function. Internally after the call, we check if
    /// logs were emitted in the expected order with the expected topics and data (as specified by the booleans).
    function expectEmitAnonymous(bool checkTopic0, bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData)
        external;

    /// Same as the previous method, but also checks supplied address against emitting contract.
    function expectEmitAnonymous(
        bool checkTopic0,
        bool checkTopic1,
        bool checkTopic2,
        bool checkTopic3,
        bool checkData,
        address emitter
    ) external;

    /// Prepare an expected anonymous log with all topic and data checks enabled.
    /// Call this function, then emit an anonymous event, then call a function. Internally after the call, we check if
    /// logs were emitted in the expected order with the expected topics and data.
    function expectEmitAnonymous() external;

    /// Same as the previous method, but also checks supplied address against emitting contract.
    function expectEmitAnonymous(address emitter) external;

    /// Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData.).
    /// Call this function, then emit an event, then call a function. Internally after the call, we check if
    /// logs were emitted in the expected order with the expected topics and data (as specified by the booleans).
    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) external;

    /// Same as the previous method, but also checks supplied address against emitting contract.
    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, address emitter)
        external;

    /// Prepare an expected log with all topic and data checks enabled.
    /// Call this function, then emit an event, then call a function. Internally after the call, we check if
    /// logs were emitted in the expected order with the expected topics and data.
    function expectEmit() external;

    /// Same as the previous method, but also checks supplied address against emitting contract.
    function expectEmit(address emitter) external;

    /// Expects an error on next call that starts with the revert data.
    function expectPartialRevert(bytes4 revertData) external;

    /// Expects an error on next call to reverter address, that starts with the revert data.
    function expectPartialRevert(bytes4 revertData, address reverter) external;

    /// Expects an error on next call with any revert data.
    function expectRevert() external;

    /// Expects an error on next call that exactly matches the revert data.
    function expectRevert(bytes4 revertData) external;

    /// Expects an error on next call that exactly matches the revert data.
    function expectRevert(bytes calldata revertData) external;

    /// Expects an error with any revert data on next call to reverter address.
    function expectRevert(address reverter) external;

    /// Expects an error from reverter address on next call, with any revert data.
    function expectRevert(bytes4 revertData, address reverter) external;

    /// Expects an error from reverter address on next call, that exactly matches the revert data.
    function expectRevert(bytes calldata revertData, address reverter) external;

    /// Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the current subcontext. If any other
    /// memory is written to, the test will fail. Can be called multiple times to add more ranges to the set.
    function expectSafeMemory(uint64 min, uint64 max) external;

    /// Only allows memory writes to offsets [0x00, 0x60) ∪ [min, max) in the next created subcontext.
    /// If any other memory is written to, the test will fail. Can be called multiple times to add more ranges
    /// to the set.
    function expectSafeMemoryCall(uint64 min, uint64 max) external;

    /// Marks a test as skipped. Must be called at the top level of a test.
    function skip(bool skipTest) external;

    /// Marks a test as skipped with a reason. Must be called at the top level of a test.
    function skip(bool skipTest, string calldata reason) external;

    /// Stops all safe memory expectation in the current subcontext.
    function stopExpectSafeMemory() external;
}

lib/openzeppelin-contracts/contracts/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Library used to query support of an interface declared via {IERC165}.
 *
 * Note that these functions return the actual result of the query: they do not
 * `revert` if an interface is not supported. It is up to the caller to decide
 * what to do in these cases.
 */
library ERC165Checker {
    // As per the EIP-165 spec, no interface should ever match 0xffffffff
    bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;

    /**
     * @dev Returns true if `account` supports the {IERC165} interface.
     */
    function supportsERC165(address account) internal view returns (bool) {
        // Any contract that implements ERC165 must explicitly indicate support of
        // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
        return
            supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&
            !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);
    }

    /**
     * @dev Returns true if `account` supports the interface defined by
     * `interfaceId`. Support for {IERC165} itself is queried automatically.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
        // query support of both ERC165 as per the spec and support of _interfaceId
        return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
    }

    /**
     * @dev Returns a boolean array where each value corresponds to the
     * interfaces passed in and whether they're supported or not. This allows
     * you to batch check interfaces for a contract where your expectation
     * is that some interfaces may not be supported.
     *
     * See {IERC165-supportsInterface}.
     *
     * _Available since v3.4._
     */
    function getSupportedInterfaces(
        address account,
        bytes4[] memory interfaceIds
    ) internal view returns (bool[] memory) {
        // an array of booleans corresponding to interfaceIds and whether they're supported or not
        bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);

        // query support of ERC165 itself
        if (supportsERC165(account)) {
            // query support of each interface in interfaceIds
            for (uint256 i = 0; i < interfaceIds.length; i++) {
                interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
            }
        }

        return interfaceIdsSupported;
    }

    /**
     * @dev Returns true if `account` supports all the interfaces defined in
     * `interfaceIds`. Support for {IERC165} itself is queried automatically.
     *
     * Batch-querying can lead to gas savings by skipping repeated checks for
     * {IERC165} support.
     *
     * See {IERC165-supportsInterface}.
     */
    function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
        // query support of ERC165 itself
        if (!supportsERC165(account)) {
            return false;
        }

        // query support of each interface in interfaceIds
        for (uint256 i = 0; i < interfaceIds.length; i++) {
            if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
                return false;
            }
        }

        // all interfaces supported
        return true;
    }

    /**
     * @notice Query if a contract implements an interface, does not check ERC165 support
     * @param account The address of the contract to query for support of an interface
     * @param interfaceId The interface identifier, as specified in ERC-165
     * @return true if the contract at account indicates support of the interface with
     * identifier interfaceId, false otherwise
     * @dev Assumes that account contains a contract that supports ERC165, otherwise
     * the behavior of this method is undefined. This precondition can be checked
     * with {supportsERC165}.
     *
     * Some precompiled contracts will falsely indicate support for a given interface, so caution
     * should be exercised when using this function.
     *
     * Interface identification is specified in ERC-165.
     */
    function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
        // prepare call
        bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);

        // perform static call
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly {
            success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0x00)
        }

        return success && returnSize >= 0x20 && returnValue > 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}

lib/solidstate-solidity/contracts/access/ownable/IOwnable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC173 } from '../../interfaces/IERC173.sol';
import { IOwnableInternal } from './IOwnableInternal.sol';

interface IOwnable is IOwnableInternal, IERC173 {}

lib/solidstate-solidity/contracts/access/ownable/IOwnableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC173Internal } from '../../interfaces/IERC173Internal.sol';

interface IOwnableInternal is IERC173Internal {
    error Ownable__NotOwner();
    error Ownable__NotTransitiveOwner();
}

lib/solidstate-solidity/contracts/access/ownable/ISafeOwnable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IOwnable } from './IOwnable.sol';
import { ISafeOwnableInternal } from './ISafeOwnableInternal.sol';

interface ISafeOwnable is ISafeOwnableInternal, IOwnable {
    /**
     * @notice get the nominated owner who has permission to call acceptOwnership
     */
    function nomineeOwner() external view returns (address);

    /**
     * @notice accept transfer of contract ownership
     */
    function acceptOwnership() external;
}

lib/solidstate-solidity/contracts/access/ownable/ISafeOwnableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IOwnableInternal } from './IOwnableInternal.sol';

interface ISafeOwnableInternal is IOwnableInternal {
    error SafeOwnable__NotNomineeOwner();
}

lib/solidstate-solidity/contracts/access/ownable/Ownable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC173 } from '../../interfaces/IERC173.sol';
import { IOwnable } from './IOwnable.sol';
import { OwnableInternal } from './OwnableInternal.sol';

/**
 * @title Ownership access control based on ERC173
 */
abstract contract Ownable is IOwnable, OwnableInternal {
    /**
     * @inheritdoc IERC173
     */
    function owner() public view virtual returns (address) {
        return _owner();
    }

    /**
     * @inheritdoc IERC173
     */
    function transferOwnership(address account) public virtual onlyOwner {
        _transferOwnership(account);
    }
}

lib/solidstate-solidity/contracts/access/ownable/OwnableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC173 } from '../../interfaces/IERC173.sol';
import { AddressUtils } from '../../utils/AddressUtils.sol';
import { IOwnableInternal } from './IOwnableInternal.sol';
import { OwnableStorage } from './OwnableStorage.sol';

abstract contract OwnableInternal is IOwnableInternal {
    using AddressUtils for address;

    modifier onlyOwner() {
        if (msg.sender != _owner()) revert Ownable__NotOwner();
        _;
    }

    modifier onlyTransitiveOwner() {
        if (msg.sender != _transitiveOwner())
            revert Ownable__NotTransitiveOwner();
        _;
    }

    function _owner() internal view virtual returns (address) {
        return OwnableStorage.layout().owner;
    }

    function _transitiveOwner() internal view virtual returns (address owner) {
        owner = _owner();

        while (owner.isContract()) {
            try IERC173(owner).owner() returns (address transitiveOwner) {
                owner = transitiveOwner;
            } catch {
                break;
            }
        }
    }

    function _transferOwnership(address account) internal virtual {
        _setOwner(account);
    }

    function _setOwner(address account) internal virtual {
        OwnableStorage.Layout storage l = OwnableStorage.layout();
        emit OwnershipTransferred(l.owner, account);
        l.owner = account;
    }
}

lib/solidstate-solidity/contracts/access/ownable/OwnableStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

library OwnableStorage {
    struct Layout {
        address owner;
    }

    bytes32 internal constant STORAGE_SLOT =
        keccak256('solidstate.contracts.storage.Ownable');

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }
}

lib/solidstate-solidity/contracts/access/ownable/SafeOwnable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { Ownable } from './Ownable.sol';
import { ISafeOwnable } from './ISafeOwnable.sol';
import { OwnableInternal } from './OwnableInternal.sol';
import { SafeOwnableInternal } from './SafeOwnableInternal.sol';

/**
 * @title Ownership access control based on ERC173 with ownership transfer safety check
 */
abstract contract SafeOwnable is ISafeOwnable, Ownable, SafeOwnableInternal {
    /**
     * @inheritdoc ISafeOwnable
     */
    function nomineeOwner() public view virtual returns (address) {
        return _nomineeOwner();
    }

    /**
     * @inheritdoc ISafeOwnable
     */
    function acceptOwnership() public virtual onlyNomineeOwner {
        _acceptOwnership();
    }

    function _transferOwnership(
        address account
    ) internal virtual override(OwnableInternal, SafeOwnableInternal) {
        super._transferOwnership(account);
    }
}

lib/solidstate-solidity/contracts/access/ownable/SafeOwnableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { ISafeOwnableInternal } from './ISafeOwnableInternal.sol';
import { OwnableInternal } from './OwnableInternal.sol';
import { SafeOwnableStorage } from './SafeOwnableStorage.sol';

abstract contract SafeOwnableInternal is ISafeOwnableInternal, OwnableInternal {
    modifier onlyNomineeOwner() {
        if (msg.sender != _nomineeOwner())
            revert SafeOwnable__NotNomineeOwner();
        _;
    }

    /**
     * @notice get the nominated owner who has permission to call acceptOwnership
     */
    function _nomineeOwner() internal view virtual returns (address) {
        return SafeOwnableStorage.layout().nomineeOwner;
    }

    /**
     * @notice accept transfer of contract ownership
     */
    function _acceptOwnership() internal virtual {
        _setOwner(msg.sender);
        delete SafeOwnableStorage.layout().nomineeOwner;
    }

    /**
     * @notice grant permission to given address to claim contract ownership
     */
    function _transferOwnership(address account) internal virtual override {
        _setNomineeOwner(account);
    }

    /**
     * @notice set nominee owner
     */
    function _setNomineeOwner(address account) internal virtual {
        SafeOwnableStorage.layout().nomineeOwner = account;
    }
}

lib/solidstate-solidity/contracts/access/ownable/SafeOwnableStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

library SafeOwnableStorage {
    struct Layout {
        address nomineeOwner;
    }

    bytes32 internal constant STORAGE_SLOT =
        keccak256('solidstate.contracts.storage.SafeOwnable');

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }
}

lib/solidstate-solidity/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC165Internal } from './IERC165Internal.sol';

/**
 * @title ERC165 interface registration interface
 * @dev see https://eips.ethereum.org/EIPS/eip-165
 */
interface IERC165 is IERC165Internal {
    /**
     * @notice query whether contract has registered support for given interface
     * @param interfaceId interface id
     * @return bool whether interface is supported
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

lib/solidstate-solidity/contracts/interfaces/IERC165Internal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

/**
 * @title ERC165 interface registration interface
 */
interface IERC165Internal {

}

lib/solidstate-solidity/contracts/interfaces/IERC173.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC173Internal } from './IERC173Internal.sol';

/**
 * @title Contract ownership standard interface
 * @dev see https://eips.ethereum.org/EIPS/eip-173
 */
interface IERC173 is IERC173Internal {
    /**
     * @notice get the ERC173 contract owner
     * @return contract owner
     */
    function owner() external view returns (address);

    /**
     * @notice transfer contract ownership to new account
     * @param account address of new owner
     */
    function transferOwnership(address account) external;
}

lib/solidstate-solidity/contracts/interfaces/IERC173Internal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

/**
 * @title Partial ERC173 interface needed by internal functions
 */
interface IERC173Internal {
    event OwnershipTransferred(
        address indexed previousOwner,
        address indexed newOwner
    );
}

lib/solidstate-solidity/contracts/introspection/ERC165/base/ERC165Base.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC165 } from '../../../interfaces/IERC165.sol';
import { IERC165Base } from './IERC165Base.sol';
import { ERC165BaseInternal } from './ERC165BaseInternal.sol';
import { ERC165BaseStorage } from './ERC165BaseStorage.sol';

/**
 * @title ERC165 implementation
 */
abstract contract ERC165Base is IERC165Base, ERC165BaseInternal {
    /**
     * @inheritdoc IERC165
     */
    function supportsInterface(bytes4 interfaceId) public view returns (bool) {
        return _supportsInterface(interfaceId);
    }
}

lib/solidstate-solidity/contracts/introspection/ERC165/base/ERC165BaseInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IERC165BaseInternal } from './IERC165BaseInternal.sol';
import { ERC165BaseStorage } from './ERC165BaseStorage.sol';

/**
 * @title ERC165 implementation
 */
abstract contract ERC165BaseInternal is IERC165BaseInternal {
    /**
     * @notice indicates whether an interface is already supported based on the interfaceId
     * @param interfaceId id of interface to check
     * @return bool indicating whether interface is supported
     */
    function _supportsInterface(
        bytes4 interfaceId
    ) internal view virtual returns (bool) {
        return ERC165BaseStorage.layout().supportedInterfaces[interfaceId];
    }

    /**
     * @notice sets status of interface support
     * @param interfaceId id of interface to set status for
     * @param status boolean indicating whether interface will be set as supported
     */
    function _setSupportsInterface(
        bytes4 interfaceId,
        bool status
    ) internal virtual {
        if (interfaceId == 0xffffffff) revert ERC165Base__InvalidInterfaceId();
        ERC165BaseStorage.layout().supportedInterfaces[interfaceId] = status;
    }
}

lib/solidstate-solidity/contracts/introspection/ERC165/base/ERC165BaseStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

library ERC165BaseStorage {
    struct Layout {
        mapping(bytes4 => bool) supportedInterfaces;
    }

    bytes32 internal constant STORAGE_SLOT =
        keccak256('solidstate.contracts.storage.ERC165Base');

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }
}

lib/solidstate-solidity/contracts/introspection/ERC165/base/IERC165Base.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import { IERC165 } from '../../../interfaces/IERC165.sol';
import { IERC165BaseInternal } from './IERC165BaseInternal.sol';

interface IERC165Base is IERC165, IERC165BaseInternal {}

lib/solidstate-solidity/contracts/introspection/ERC165/base/IERC165BaseInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import { IERC165Internal } from '../../../interfaces/IERC165Internal.sol';

interface IERC165BaseInternal is IERC165Internal {
    error ERC165Base__InvalidInterfaceId();
}

lib/solidstate-solidity/contracts/proxy/IProxy.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

interface IProxy {
    error Proxy__ImplementationIsNotContract();

    fallback() external payable;
}

lib/solidstate-solidity/contracts/proxy/Proxy.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { AddressUtils } from '../utils/AddressUtils.sol';
import { IProxy } from './IProxy.sol';

/**
 * @title Base proxy contract
 */
abstract contract Proxy is IProxy {
    using AddressUtils for address;

    /**
     * @notice delegate all calls to implementation contract
     * @dev reverts if implementation address contains no code, for compatibility with metamorphic contracts
     * @dev memory location in use by assembly may be unsafe in other contexts
     */
    fallback() external payable virtual {
        address implementation = _getImplementation();

        if (!implementation.isContract())
            revert Proxy__ImplementationIsNotContract();

        assembly {
            calldatacopy(0, 0, calldatasize())
            let result := delegatecall(
                gas(),
                implementation,
                0,
                calldatasize(),
                0,
                0
            )
            returndatacopy(0, 0, returndatasize())

            switch result
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @notice get logic implementation address
     * @return implementation address
     */
    function _getImplementation() internal virtual returns (address);
}

lib/solidstate-solidity/contracts/proxy/diamond/ISolidStateDiamond.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { ISafeOwnable } from '../../access/ownable/ISafeOwnable.sol';
import { IERC165 } from '../../interfaces/IERC165.sol';
import { IDiamondBase } from './base/IDiamondBase.sol';
import { IDiamondFallback } from './fallback/IDiamondFallback.sol';
import { IDiamondReadable } from './readable/IDiamondReadable.sol';
import { IDiamondWritable } from './writable/IDiamondWritable.sol';

interface ISolidStateDiamond is
    IDiamondBase,
    IDiamondFallback,
    IDiamondReadable,
    IDiamondWritable,
    ISafeOwnable,
    IERC165
{
    receive() external payable;
}

lib/solidstate-solidity/contracts/proxy/diamond/SolidStateDiamond.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IOwnable, Ownable, OwnableInternal } from '../../access/ownable/Ownable.sol';
import { ISafeOwnable, SafeOwnable } from '../../access/ownable/SafeOwnable.sol';
import { IERC165 } from '../../interfaces/IERC165.sol';
import { IERC173 } from '../../interfaces/IERC173.sol';
import { ERC165Base, ERC165BaseStorage } from '../../introspection/ERC165/base/ERC165Base.sol';
import { DiamondBase } from './base/DiamondBase.sol';
import { DiamondFallback, IDiamondFallback } from './fallback/DiamondFallback.sol';
import { DiamondReadable, IDiamondReadable } from './readable/DiamondReadable.sol';
import { DiamondWritable, IDiamondWritable } from './writable/DiamondWritable.sol';
import { ISolidStateDiamond } from './ISolidStateDiamond.sol';

/**
 * @title SolidState "Diamond" proxy reference implementation
 */
abstract contract SolidStateDiamond is
    ISolidStateDiamond,
    DiamondBase,
    DiamondFallback,
    DiamondReadable,
    DiamondWritable,
    SafeOwnable,
    ERC165Base
{
    constructor() {
        bytes4[] memory selectors = new bytes4[](12);
        uint256 selectorIndex;

        // register DiamondFallback

        selectors[selectorIndex++] = IDiamondFallback
            .getFallbackAddress
            .selector;
        selectors[selectorIndex++] = IDiamondFallback
            .setFallbackAddress
            .selector;

        _setSupportsInterface(type(IDiamondFallback).interfaceId, true);

        // register DiamondWritable

        selectors[selectorIndex++] = IDiamondWritable.diamondCut.selector;

        _setSupportsInterface(type(IDiamondWritable).interfaceId, true);

        // register DiamondReadable

        selectors[selectorIndex++] = IDiamondReadable.facets.selector;
        selectors[selectorIndex++] = IDiamondReadable
            .facetFunctionSelectors
            .selector;
        selectors[selectorIndex++] = IDiamondReadable.facetAddresses.selector;
        selectors[selectorIndex++] = IDiamondReadable.facetAddress.selector;

        _setSupportsInterface(type(IDiamondReadable).interfaceId, true);

        // register ERC165

        selectors[selectorIndex++] = IERC165.supportsInterface.selector;

        _setSupportsInterface(type(IERC165).interfaceId, true);

        // register SafeOwnable

        selectors[selectorIndex++] = Ownable.owner.selector;
        selectors[selectorIndex++] = SafeOwnable.nomineeOwner.selector;
        selectors[selectorIndex++] = Ownable.transferOwnership.selector;
        selectors[selectorIndex++] = SafeOwnable.acceptOwnership.selector;

        _setSupportsInterface(type(IERC173).interfaceId, true);

        // diamond cut

        FacetCut[] memory facetCuts = new FacetCut[](1);

        facetCuts[0] = FacetCut({
            target: address(this),
            action: FacetCutAction.ADD,
            selectors: selectors
        });

        _diamondCut(facetCuts, address(0), '');

        // set owner

        _setOwner(msg.sender);
    }

    receive() external payable {}

    function _transferOwnership(
        address account
    ) internal virtual override(OwnableInternal, SafeOwnable) {
        super._transferOwnership(account);
    }

    /**
     * @inheritdoc DiamondFallback
     */
    function _getImplementation()
        internal
        view
        override(DiamondBase, DiamondFallback)
        returns (address implementation)
    {
        implementation = super._getImplementation();
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/base/DiamondBase.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { Proxy } from '../../Proxy.sol';
import { IDiamondBase } from './IDiamondBase.sol';
import { DiamondBaseStorage } from './DiamondBaseStorage.sol';

/**
 * @title EIP-2535 "Diamond" proxy base contract
 * @dev see https://eips.ethereum.org/EIPS/eip-2535
 */
abstract contract DiamondBase is IDiamondBase, Proxy {
    /**
     * @inheritdoc Proxy
     */
    function _getImplementation()
        internal
        view
        virtual
        override
        returns (address implementation)
    {
        // inline storage layout retrieval uses less gas
        DiamondBaseStorage.Layout storage l;
        bytes32 slot = DiamondBaseStorage.STORAGE_SLOT;
        assembly {
            l.slot := slot
        }

        implementation = address(bytes20(l.facets[msg.sig]));
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/base/DiamondBaseStorage.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

/**
 * @dev derived from https://github.com/mudgen/diamond-2 (MIT license)
 */
library DiamondBaseStorage {
    struct Layout {
        // function selector => (facet address, selector slot position)
        mapping(bytes4 => bytes32) facets;
        // total number of selectors registered
        uint16 selectorCount;
        // array of selector slots with 8 selectors per slot
        mapping(uint256 => bytes32) selectorSlots;
        address fallbackAddress;
    }

    bytes32 internal constant STORAGE_SLOT =
        keccak256('solidstate.contracts.storage.DiamondBase');

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = STORAGE_SLOT;
        assembly {
            l.slot := slot
        }
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/base/IDiamondBase.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IProxy } from '../../IProxy.sol';

interface IDiamondBase is IProxy {}

lib/solidstate-solidity/contracts/proxy/diamond/fallback/DiamondFallback.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { OwnableInternal } from '../../../access/ownable/OwnableInternal.sol';
import { DiamondBase } from '../base/DiamondBase.sol';
import { DiamondBaseStorage } from '../base/DiamondBaseStorage.sol';
import { IDiamondFallback } from './IDiamondFallback.sol';

/**
 * @title Fallback feature for EIP-2535 "Diamond" proxy
 */
abstract contract DiamondFallback is
    IDiamondFallback,
    OwnableInternal,
    DiamondBase
{
    /**
     * @inheritdoc IDiamondFallback
     */
    function getFallbackAddress()
        external
        view
        returns (address fallbackAddress)
    {
        fallbackAddress = _getFallbackAddress();
    }

    /**
     * @inheritdoc IDiamondFallback
     */
    function setFallbackAddress(address fallbackAddress) external onlyOwner {
        _setFallbackAddress(fallbackAddress);
    }

    /**
     * @inheritdoc DiamondBase
     * @notice query custom fallback address is no implementation is found
     */
    function _getImplementation()
        internal
        view
        virtual
        override
        returns (address implementation)
    {
        implementation = super._getImplementation();

        if (implementation == address(0)) {
            implementation = _getFallbackAddress();
        }
    }

    /**
     * @notice query the address of the fallback implementation
     * @return fallbackAddress address of fallback implementation
     */
    function _getFallbackAddress()
        internal
        view
        virtual
        returns (address fallbackAddress)
    {
        fallbackAddress = DiamondBaseStorage.layout().fallbackAddress;
    }

    /**
     * @notice set the address of the fallback implementation
     * @param fallbackAddress address of fallback implementation
     */
    function _setFallbackAddress(address fallbackAddress) internal virtual {
        DiamondBaseStorage.layout().fallbackAddress = fallbackAddress;
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/fallback/IDiamondFallback.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IDiamondBase } from '../base/IDiamondBase.sol';

interface IDiamondFallback is IDiamondBase {
    /**
     * @notice query the address of the fallback implementation
     * @return fallbackAddress address of fallback implementation
     */
    function getFallbackAddress()
        external
        view
        returns (address fallbackAddress);

    /**
     * @notice set the address of the fallback implementation
     * @param fallbackAddress address of fallback implementation
     */
    function setFallbackAddress(address fallbackAddress) external;
}

lib/solidstate-solidity/contracts/proxy/diamond/readable/DiamondReadable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { DiamondBaseStorage } from '../base/DiamondBaseStorage.sol';
import { IDiamondReadable } from './IDiamondReadable.sol';

/**
 * @title EIP-2535 "Diamond" proxy introspection contract
 * @dev derived from https://github.com/mudgen/diamond-2 (MIT license)
 */
abstract contract DiamondReadable is IDiamondReadable {
    /**
     * @inheritdoc IDiamondReadable
     */
    function facets() external view returns (Facet[] memory diamondFacets) {
        DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout();

        diamondFacets = new Facet[](l.selectorCount);

        uint8[] memory numFacetSelectors = new uint8[](l.selectorCount);
        uint256 numFacets;
        uint256 selectorIndex;

        // loop through function selectors
        for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) {
            bytes32 slot = l.selectorSlots[slotIndex];

            for (
                uint256 selectorSlotIndex;
                selectorSlotIndex < 8;
                selectorSlotIndex++
            ) {
                selectorIndex++;

                if (selectorIndex > l.selectorCount) {
                    break;
                }

                bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));
                address facet = address(bytes20(l.facets[selector]));

                bool continueLoop;

                for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
                    if (diamondFacets[facetIndex].target == facet) {
                        diamondFacets[facetIndex].selectors[
                            numFacetSelectors[facetIndex]
                        ] = selector;
                        // probably will never have more than 256 functions from one facet contract
                        require(numFacetSelectors[facetIndex] < 255);
                        numFacetSelectors[facetIndex]++;
                        continueLoop = true;
                        break;
                    }
                }

                if (continueLoop) {
                    continue;
                }

                diamondFacets[numFacets].target = facet;
                diamondFacets[numFacets].selectors = new bytes4[](
                    l.selectorCount
                );
                diamondFacets[numFacets].selectors[0] = selector;
                numFacetSelectors[numFacets] = 1;
                numFacets++;
            }
        }

        for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
            uint256 numSelectors = numFacetSelectors[facetIndex];
            bytes4[] memory selectors = diamondFacets[facetIndex].selectors;

            // setting the number of selectors
            assembly {
                mstore(selectors, numSelectors)
            }
        }

        // setting the number of facets
        assembly {
            mstore(diamondFacets, numFacets)
        }
    }

    /**
     * @inheritdoc IDiamondReadable
     */
    function facetFunctionSelectors(
        address facet
    ) external view returns (bytes4[] memory selectors) {
        DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout();

        selectors = new bytes4[](l.selectorCount);

        uint256 numSelectors;
        uint256 selectorIndex;

        // loop through function selectors
        for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) {
            bytes32 slot = l.selectorSlots[slotIndex];

            for (
                uint256 selectorSlotIndex;
                selectorSlotIndex < 8;
                selectorSlotIndex++
            ) {
                selectorIndex++;

                if (selectorIndex > l.selectorCount) {
                    break;
                }

                bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));

                if (facet == address(bytes20(l.facets[selector]))) {
                    selectors[numSelectors] = selector;
                    numSelectors++;
                }
            }
        }

        // set the number of selectors in the array
        assembly {
            mstore(selectors, numSelectors)
        }
    }

    /**
     * @inheritdoc IDiamondReadable
     */
    function facetAddresses()
        external
        view
        returns (address[] memory addresses)
    {
        DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout();

        addresses = new address[](l.selectorCount);
        uint256 numFacets;
        uint256 selectorIndex;

        for (uint256 slotIndex; selectorIndex < l.selectorCount; slotIndex++) {
            bytes32 slot = l.selectorSlots[slotIndex];

            for (
                uint256 selectorSlotIndex;
                selectorSlotIndex < 8;
                selectorSlotIndex++
            ) {
                selectorIndex++;

                if (selectorIndex > l.selectorCount) {
                    break;
                }

                bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));
                address facet = address(bytes20(l.facets[selector]));

                bool continueLoop;

                for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
                    if (facet == addresses[facetIndex]) {
                        continueLoop = true;
                        break;
                    }
                }

                if (continueLoop) {
                    continue;
                }

                addresses[numFacets] = facet;
                numFacets++;
            }
        }

        // set the number of facet addresses in the array
        assembly {
            mstore(addresses, numFacets)
        }
    }

    /**
     * @inheritdoc IDiamondReadable
     */
    function facetAddress(
        bytes4 selector
    ) external view returns (address facet) {
        facet = address(bytes20(DiamondBaseStorage.layout().facets[selector]));
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/readable/IDiamondReadable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

/**
 * @title Diamond proxy introspection interface
 * @dev see https://eips.ethereum.org/EIPS/eip-2535
 */
interface IDiamondReadable {
    struct Facet {
        address target;
        bytes4[] selectors;
    }

    /**
     * @notice get all facets and their selectors
     * @return diamondFacets array of structured facet data
     */
    function facets() external view returns (Facet[] memory diamondFacets);

    /**
     * @notice get all selectors for given facet address
     * @param facet address of facet to query
     * @return selectors array of function selectors
     */
    function facetFunctionSelectors(
        address facet
    ) external view returns (bytes4[] memory selectors);

    /**
     * @notice get addresses of all facets used by diamond
     * @return addresses array of facet addresses
     */
    function facetAddresses()
        external
        view
        returns (address[] memory addresses);

    /**
     * @notice get the address of the facet associated with given selector
     * @param selector function selector to query
     * @return facet facet address (zero address if not found)
     */
    function facetAddress(
        bytes4 selector
    ) external view returns (address facet);
}

lib/solidstate-solidity/contracts/proxy/diamond/writable/DiamondWritable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { OwnableInternal } from '../../../access/ownable/OwnableInternal.sol';
import { IDiamondWritable } from './IDiamondWritable.sol';
import { DiamondWritableInternal } from './DiamondWritableInternal.sol';

/**
 * @title EIP-2535 "Diamond" proxy update contract
 */
abstract contract DiamondWritable is
    IDiamondWritable,
    DiamondWritableInternal,
    OwnableInternal
{
    /**
     * @inheritdoc IDiamondWritable
     */
    function diamondCut(
        FacetCut[] calldata facetCuts,
        address target,
        bytes calldata data
    ) external onlyOwner {
        _diamondCut(facetCuts, target, data);
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/writable/DiamondWritableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import { AddressUtils } from '../../../utils/AddressUtils.sol';
import { DiamondBaseStorage } from '../base/DiamondBaseStorage.sol';
import { IDiamondWritableInternal } from './IDiamondWritableInternal.sol';

abstract contract DiamondWritableInternal is IDiamondWritableInternal {
    using AddressUtils for address;

    bytes32 private constant CLEAR_ADDRESS_MASK =
        bytes32(uint256(0xffffffffffffffffffffffff));
    bytes32 private constant CLEAR_SELECTOR_MASK =
        bytes32(uint256(0xffffffff << 224));

    /**
     * @notice update functions callable on Diamond proxy
     * @param facetCuts array of structured Diamond facet update data
     * @param target optional recipient of initialization delegatecall
     * @param data optional initialization call data
     */
    function _diamondCut(
        FacetCut[] memory facetCuts,
        address target,
        bytes memory data
    ) internal virtual {
        DiamondBaseStorage.Layout storage l = DiamondBaseStorage.layout();

        unchecked {
            uint256 originalSelectorCount = l.selectorCount;
            uint256 selectorCount = originalSelectorCount;
            bytes32 selectorSlot;

            // Check if last selector slot is not full
            if (selectorCount & 7 > 0) {
                // get last selectorSlot
                selectorSlot = l.selectorSlots[selectorCount >> 3];
            }

            for (uint256 i; i < facetCuts.length; i++) {
                FacetCut memory facetCut = facetCuts[i];
                FacetCutAction action = facetCut.action;

                if (facetCut.selectors.length == 0)
                    revert DiamondWritable__SelectorNotSpecified();

                if (action == FacetCutAction.ADD) {
                    (selectorCount, selectorSlot) = _addFacetSelectors(
                        l,
                        selectorCount,
                        selectorSlot,
                        facetCut
                    );
                } else if (action == FacetCutAction.REPLACE) {
                    _replaceFacetSelectors(l, facetCut);
                } else if (action == FacetCutAction.REMOVE) {
                    (selectorCount, selectorSlot) = _removeFacetSelectors(
                        l,
                        selectorCount,
                        selectorSlot,
                        facetCut
                    );
                }
            }

            if (selectorCount != originalSelectorCount) {
                l.selectorCount = uint16(selectorCount);
            }

            // If last selector slot is not full
            if (selectorCount & 7 > 0) {
                l.selectorSlots[selectorCount >> 3] = selectorSlot;
            }

            emit DiamondCut(facetCuts, target, data);
            _initialize(target, data);
        }
    }

    function _addFacetSelectors(
        DiamondBaseStorage.Layout storage l,
        uint256 selectorCount,
        bytes32 selectorSlot,
        FacetCut memory facetCut
    ) internal returns (uint256, bytes32) {
        unchecked {
            if (
                facetCut.target != address(this) &&
                !facetCut.target.isContract()
            ) revert DiamondWritable__TargetHasNoCode();

            for (uint256 i; i < facetCut.selectors.length; i++) {
                bytes4 selector = facetCut.selectors[i];
                bytes32 oldFacet = l.facets[selector];

                if (address(bytes20(oldFacet)) != address(0))
                    revert DiamondWritable__SelectorAlreadyAdded();

                // add facet for selector
                l.facets[selector] =
                    bytes20(facetCut.target) |
                    bytes32(selectorCount);
                uint256 selectorInSlotPosition = (selectorCount & 7) << 5;

                // clear selector position in slot and add selector
                selectorSlot =
                    (selectorSlot &
                        ~(CLEAR_SELECTOR_MASK >> selectorInSlotPosition)) |
                    (bytes32(selector) >> selectorInSlotPosition);

                // if slot is full then write it to storage
                if (selectorInSlotPosition == 224) {
                    l.selectorSlots[selectorCount >> 3] = selectorSlot;
                    selectorSlot = 0;
                }

                selectorCount++;
            }

            return (selectorCount, selectorSlot);
        }
    }

    function _removeFacetSelectors(
        DiamondBaseStorage.Layout storage l,
        uint256 selectorCount,
        bytes32 selectorSlot,
        FacetCut memory facetCut
    ) internal returns (uint256, bytes32) {
        unchecked {
            if (facetCut.target != address(0))
                revert DiamondWritable__RemoveTargetNotZeroAddress();

            uint256 selectorSlotCount = selectorCount >> 3;
            uint256 selectorInSlotIndex = selectorCount & 7;

            for (uint256 i; i < facetCut.selectors.length; i++) {
                bytes4 selector = facetCut.selectors[i];
                bytes32 oldFacet = l.facets[selector];

                if (address(bytes20(oldFacet)) == address(0))
                    revert DiamondWritable__SelectorNotFound();

                if (address(bytes20(oldFacet)) == address(this))
                    revert DiamondWritable__SelectorIsImmutable();

                if (selectorSlot == 0) {
                    selectorSlotCount--;
                    selectorSlot = l.selectorSlots[selectorSlotCount];
                    selectorInSlotIndex = 7;
                } else {
                    selectorInSlotIndex--;
                }

                bytes4 lastSelector;
                uint256 oldSelectorsSlotCount;
                uint256 oldSelectorInSlotPosition;

                // adding a block here prevents stack too deep error
                {
                    // replace selector with last selector in l.facets
                    lastSelector = bytes4(
                        selectorSlot << (selectorInSlotIndex << 5)
                    );

                    if (lastSelector != selector) {
                        // update last selector slot position info
                        l.facets[lastSelector] =
                            (oldFacet & CLEAR_ADDRESS_MASK) |
                            bytes20(l.facets[lastSelector]);
                    }

                    delete l.facets[selector];
                    uint256 oldSelectorCount = uint16(uint256(oldFacet));
                    oldSelectorsSlotCount = oldSelectorCount >> 3;
                    oldSelectorInSlotPosition = (oldSelectorCount & 7) << 5;
                }

                if (oldSelectorsSlotCount != selectorSlotCount) {
                    bytes32 oldSelectorSlot = l.selectorSlots[
                        oldSelectorsSlotCount
                    ];

                    // clears the selector we are deleting and puts the last selector in its place.
                    oldSelectorSlot =
                        (oldSelectorSlot &
                            ~(CLEAR_SELECTOR_MASK >>
                                oldSelectorInSlotPosition)) |
                        (bytes32(lastSelector) >> oldSelectorInSlotPosition);

                    // update storage with the modified slot
                    l.selectorSlots[oldSelectorsSlotCount] = oldSelectorSlot;
                } else {
                    // clears the selector we are deleting and puts the last selector in its place.
                    selectorSlot =
                        (selectorSlot &
                            ~(CLEAR_SELECTOR_MASK >>
                                oldSelectorInSlotPosition)) |
                        (bytes32(lastSelector) >> oldSelectorInSlotPosition);
                }

                if (selectorInSlotIndex == 0) {
                    delete l.selectorSlots[selectorSlotCount];
                    selectorSlot = 0;
                }
            }

            selectorCount = (selectorSlotCount << 3) | selectorInSlotIndex;

            return (selectorCount, selectorSlot);
        }
    }

    function _replaceFacetSelectors(
        DiamondBaseStorage.Layout storage l,
        FacetCut memory facetCut
    ) internal {
        unchecked {
            if (!facetCut.target.isContract())
                revert DiamondWritable__TargetHasNoCode();

            for (uint256 i; i < facetCut.selectors.length; i++) {
                bytes4 selector = facetCut.selectors[i];
                bytes32 oldFacet = l.facets[selector];
                address oldFacetAddress = address(bytes20(oldFacet));

                if (oldFacetAddress == address(0))
                    revert DiamondWritable__SelectorNotFound();
                if (oldFacetAddress == address(this))
                    revert DiamondWritable__SelectorIsImmutable();
                if (oldFacetAddress == facetCut.target)
                    revert DiamondWritable__ReplaceTargetIsIdentical();

                // replace old facet address
                l.facets[selector] =
                    (oldFacet & CLEAR_ADDRESS_MASK) |
                    bytes20(facetCut.target);
            }
        }
    }

    function _initialize(address target, bytes memory data) private {
        if ((target == address(0)) != (data.length == 0))
            revert DiamondWritable__InvalidInitializationParameters();

        if (target != address(0)) {
            if (target != address(this)) {
                if (!target.isContract())
                    revert DiamondWritable__TargetHasNoCode();
            }

            (bool success, ) = target.delegatecall(data);

            if (!success) {
                assembly {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
            }
        }
    }
}

lib/solidstate-solidity/contracts/proxy/diamond/writable/IDiamondWritable.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { IDiamondWritableInternal } from './IDiamondWritableInternal.sol';

/**
 * @title Diamond proxy upgrade interface
 * @dev see https://eips.ethereum.org/EIPS/eip-2535
 */
interface IDiamondWritable is IDiamondWritableInternal {
    /**
     * @notice update diamond facets and optionally execute arbitrary initialization function
     * @param facetCuts array of structured Diamond facet update data
     * @param target optional target of initialization delegatecall
     * @param data optional initialization function call data
     */
    function diamondCut(
        FacetCut[] calldata facetCuts,
        address target,
        bytes calldata data
    ) external;
}

lib/solidstate-solidity/contracts/proxy/diamond/writable/IDiamondWritableInternal.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

interface IDiamondWritableInternal {
    enum FacetCutAction {
        ADD,
        REPLACE,
        REMOVE
    }

    event DiamondCut(FacetCut[] facetCuts, address target, bytes data);

    error DiamondWritable__InvalidInitializationParameters();
    error DiamondWritable__RemoveTargetNotZeroAddress();
    error DiamondWritable__ReplaceTargetIsIdentical();
    error DiamondWritable__SelectorAlreadyAdded();
    error DiamondWritable__SelectorIsImmutable();
    error DiamondWritable__SelectorNotFound();
    error DiamondWritable__SelectorNotSpecified();
    error DiamondWritable__TargetHasNoCode();

    struct FacetCut {
        address target;
        FacetCutAction action;
        bytes4[] selectors;
    }
}

lib/solidstate-solidity/contracts/utils/AddressUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

import { UintUtils } from './UintUtils.sol';

library AddressUtils {
    using UintUtils for uint256;

    error AddressUtils__InsufficientBalance();
    error AddressUtils__NotContract();
    error AddressUtils__SendValueFailed();

    function toString(address account) internal pure returns (string memory) {
        return uint256(uint160(account)).toHexString(20);
    }

    function isContract(address account) internal view returns (bool) {
        uint256 size;
        assembly {
            size := extcodesize(account)
        }
        return size > 0;
    }

    function sendValue(address payable account, uint256 amount) internal {
        (bool success, ) = account.call{ value: amount }('');
        if (!success) revert AddressUtils__SendValueFailed();
    }

    function functionCall(
        address target,
        bytes memory data
    ) internal returns (bytes memory) {
        return
            functionCall(target, data, 'AddressUtils: failed low-level call');
    }

    function functionCall(
        address target,
        bytes memory data,
        string memory error
    ) internal returns (bytes memory) {
        return _functionCallWithValue(target, data, 0, error);
    }

    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return
            functionCallWithValue(
                target,
                data,
                value,
                'AddressUtils: failed low-level call with value'
            );
    }

    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory error
    ) internal returns (bytes memory) {
        if (value > address(this).balance)
            revert AddressUtils__InsufficientBalance();
        return _functionCallWithValue(target, data, value, error);
    }

    /**
     * @notice execute arbitrary external call with limited gas usage and amount of copied return data
     * @dev derived from https://github.com/nomad-xyz/ExcessivelySafeCall (MIT License)
     * @param target recipient of call
     * @param gasAmount gas allowance for call
     * @param value native token value to include in call
     * @param maxCopy maximum number of bytes to copy from return data
     * @param data encoded call data
     * @return success whether call is successful
     * @return returnData copied return data
     */
    function excessivelySafeCall(
        address target,
        uint256 gasAmount,
        uint256 value,
        uint16 maxCopy,
        bytes memory data
    ) internal returns (bool success, bytes memory returnData) {
        returnData = new bytes(maxCopy);

        assembly {
            // execute external call via assembly to avoid automatic copying of return data
            success := call(
                gasAmount,
                target,
                value,
                add(data, 0x20),
                mload(data),
                0,
                0
            )

            // determine whether to limit amount of data to copy
            let toCopy := returndatasize()

            if gt(toCopy, maxCopy) {
                toCopy := maxCopy
            }

            // store the length of the copied bytes
            mstore(returnData, toCopy)

            // copy the bytes from returndata[0:toCopy]
            returndatacopy(add(returnData, 0x20), 0, toCopy)
        }
    }

    function _functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory error
    ) private returns (bytes memory) {
        if (!isContract(target)) revert AddressUtils__NotContract();

        (bool success, bytes memory returnData) = target.call{ value: value }(
            data
        );

        if (success) {
            return returnData;
        } else if (returnData.length > 0) {
            assembly {
                let returnData_size := mload(returnData)
                revert(add(32, returnData), returnData_size)
            }
        } else {
            revert(error);
        }
    }
}

lib/solidstate-solidity/contracts/utils/UintUtils.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.8;

/**
 * @title utility functions for uint256 operations
 * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license)
 */
library UintUtils {
    error UintUtils__InsufficientHexLength();

    bytes16 private constant HEX_SYMBOLS = '0123456789abcdef';

    function add(uint256 a, int256 b) internal pure returns (uint256) {
        return b < 0 ? sub(a, -b) : a + uint256(b);
    }

    function sub(uint256 a, int256 b) internal pure returns (uint256) {
        return b < 0 ? add(a, -b) : a - uint256(b);
    }

    function toString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return '0';
        }

        uint256 temp = value;
        uint256 digits;

        while (temp != 0) {
            digits++;
            temp /= 10;
        }

        bytes memory buffer = new bytes(digits);

        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }

        return string(buffer);
    }

    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return '0x00';
        }

        uint256 length = 0;

        for (uint256 temp = value; temp != 0; temp >>= 8) {
            unchecked {
                length++;
            }
        }

        return toHexString(value, length);
    }

    function toHexString(
        uint256 value,
        uint256 length
    ) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = '0';
        buffer[1] = 'x';

        unchecked {
            for (uint256 i = 2 * length + 1; i > 1; --i) {
                buffer[i] = HEX_SYMBOLS[value & 0xf];
                value >>= 4;
            }
        }

        if (value != 0) revert UintUtils__InsufficientHexLength();

        return string(buffer);
    }
}

lib/vulcan/src/_internal/Accounts.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import {stdStorage, StdStorage} from "forge-std/StdStorage.sol";

import {strings} from "./Strings.sol";
import "./Vulcan.sol";
import {formatError} from "./Utils.sol";

/// @dev Accounts module for scripts
library accountsSafe {
    /// @dev Reads the storage at the specified `slot` for the given `who` address and returns the content.
    /// @param who The address whose storage will be read.
    /// @param slot The position of the storage slot to read.
    /// @return The contents of the specified storage slot as a bytes32 value.
    function readStorage(address who, bytes32 slot) internal view returns (bytes32) {
        return vulcan.hevm.load(who, slot);
    }

    /// @dev Signs the specified `digest` using the provided `privKey` and returns the signature in the form of `(v, r, s)`.
    /// @param privKey The private key to use for signing the digest.
    /// @param digest The message digest to sign.
    /// @return A tuple containing the signature parameters `(v, r, s)` as a `uint8`, `bytes32`, and `bytes32`, respectively.
    function sign(uint256 privKey, bytes32 digest) internal pure returns (uint8, bytes32, bytes32) {
        return vulcan.hevm.sign(privKey, digest);
    }

    /// @dev Derives the Ethereum address corresponding to the provided `privKey`.
    /// @param privKey The private key to use for deriving the Ethereum address.
    /// @return The Ethereum address derived from the provided private key.
    function derive(uint256 privKey) internal pure returns (address) {
        return vulcan.hevm.addr(privKey);
    }

    /// @dev Derives the private key corresponding to the specified `mnemonicOrPath` and `index`.
    /// @param mnemonicOrPath The mnemonic or derivation path to use for deriving the private key.
    /// @param index The index of the derived private key to retrieve.
    /// @return The private key derived from the specified mnemonic and index as a `uint256` value.
    function deriveKey(string memory mnemonicOrPath, uint32 index) internal pure returns (uint256) {
        return vulcan.hevm.deriveKey(mnemonicOrPath, index);
    }

    /// @dev Derives the private key corresponding to the specified `mnemonicOrPath`, `derivationPath`, and `index`.
    /// @param mnemonicOrPath The mnemonic or derivation path to use for deriving the master key.
    /// @param derivationPath The specific derivation path to use for deriving the private key (optional).
    /// @param index The index of the derived private key to retrieve.
    /// @return The private key derived from the specified mnemonic, derivation path, and index as a `uint256` value.
    function deriveKey(string memory mnemonicOrPath, string memory derivationPath, uint32 index)
        internal
        pure
        returns (uint256)
    {
        return vulcan.hevm.deriveKey(mnemonicOrPath, derivationPath, index);
    }

    /// @dev Adds the specified `privKey` to the local forge wallet.
    /// @param privKey The private key to add to the local forge wallet.
    /// @return The Ethereum address corresponding to the added private key.
    function rememberKey(uint256 privKey) internal returns (address) {
        return vulcan.hevm.rememberKey(privKey);
    }

    /// @dev Returns the current `nonce` of the specified `who` address.
    /// @param who The address for which to obtain the current `nonce`.
    /// @return The current `nonce` of the specified address as a `uint64` value.
    function getNonce(address who) internal view returns (uint64) {
        return vulcan.hevm.getNonce(who);
    }

    /// @dev Starts recording all storage reads and writes for later analysis.
    function recordStorage() internal {
        vulcan.hevm.record();
    }

    /// @dev Obtains an array of slots that have been read and written for the specified address `who`.
    /// @param who The address for which to obtain the storage accesses.
    /// @return reads An array of storage slots that have been read.
    /// @return writes An array of storage slots that have been written.
    function getStorageAccesses(address who) internal returns (bytes32[] memory reads, bytes32[] memory writes) {
        return vulcan.hevm.accesses(who);
    }

    /// @dev Adds a label to the specified address `who` for identification purposes in debug traces.
    /// @param who The address to label.
    /// @param lbl The label to apply to the address.
    /// @return The same address that was passed as input.
    function label(address who, string memory lbl) internal returns (address) {
        vulcan.hevm.label(who, lbl);
        return who;
    }

    /// @dev Creates an address without label.
    function create() internal returns (address) {
        uint256 id = _incrementId();
        return derive(uint256(keccak256(abi.encode(id))));
    }

    /// @dev Creates an address using the hash of the specified `name` as the private key and adds a label to the address.
    /// @param name The name to use as the basis for the address.
    /// @return The newly created address.
    function create(string memory name) internal returns (address) {
        return create(name, name);
    }

    /// @dev Creates an address using the hash of the specified `name` as the private key and adds a label to the address.
    /// @param name The name to use as the basis for the address.
    /// @param lbl The label to apply to the address.
    /// @return The newly created address.
    function create(string memory name, string memory lbl) internal returns (address) {
        address addr = derive(uint256(keccak256(abi.encodePacked(name))));

        return label(addr, lbl);
    }

    /// @dev Calculates the deployment address of `who` with nonce `nonce`.
    /// @param who The deployer address.
    /// @param nonce The deployer nonce.
    function getDeploymentAddress(address who, uint64 nonce) internal pure returns (address) {
        bytes memory data;

        if (nonce == 0x00) {
            data = abi.encodePacked(bytes1(0xd6), bytes1(0x94), who, bytes1(0x80));
        } else if (nonce <= 0x7f) {
            data = abi.encodePacked(bytes1(0xd6), bytes1(0x94), who, uint8(nonce));
        } else if (nonce <= 0xff) {
            data = abi.encodePacked(bytes1(0xd7), bytes1(0x94), who, bytes1(0x81), uint8(nonce));
        } else if (nonce <= 0xffff) {
            data = abi.encodePacked(bytes1(0xd8), bytes1(0x94), who, bytes1(0x82), uint16(nonce));
        } else if (nonce <= 0xffffff) {
            data = abi.encodePacked(bytes1(0xd9), bytes1(0x94), who, bytes1(0x83), uint24(nonce));
        } else if (nonce <= 0xffffffff) {
            data = abi.encodePacked(bytes1(0xda), bytes1(0x94), who, bytes1(0x84), uint32(nonce));
        } else if (nonce <= 0xffffffffff) {
            data = abi.encodePacked(bytes1(0xdb), bytes1(0x94), who, bytes1(0x85), uint40(nonce));
        } else if (nonce <= 0xffffffffffff) {
            data = abi.encodePacked(bytes1(0xdc), bytes1(0x94), who, bytes1(0x86), uint48(nonce));
        } else if (nonce <= 0xffffffffffffff) {
            data = abi.encodePacked(bytes1(0xdd), bytes1(0x94), who, bytes1(0x87), uint56(nonce));
        } else if (nonce <= 0xffffffffffffffff) {
            data = abi.encodePacked(bytes1(0xde), bytes1(0x94), who, bytes1(0x88), uint64(nonce));
        }

        return address(uint160(uint256(keccak256(data))));
    }

    /// @dev Calculates the deployment address of `who` with the current nonce.
    /// @param who The deployer address.
    function getDeploymentAddress(address who) internal view returns (address) {
        return getDeploymentAddress(who, getNonce(who));
    }

    /// @dev Generates an array of addresses with a specific length.
    /// @param length The amount of addresses to generate.
    function createMany(uint256 length) internal returns (address[] memory) {
        require(length > 0, _formatError("createMany(uint256)", "Invalid length for addresses array"));

        address[] memory addresses = new address[](length);

        for (uint256 i = 0; i < length; i++) {
            addresses[i] = create();
        }

        return addresses;
    }

    /// @dev Generates an array of addresses with a specific length and a prefix as label.
    /// The label for each address will be `{prefix}_{i}`.
    /// @param length The amount of addresses to generate.
    /// @param prefix The prefix of the label for each address.
    function createMany(uint256 length, string memory prefix) internal returns (address[] memory) {
        require(length > 0, "accounts: invalid length for addresses array");

        address[] memory addresses = new address[](length);

        for (uint256 i = 0; i < length; i++) {
            addresses[i] = create(string.concat(prefix, "_", strings.toString(i)));
        }

        return addresses;
    }

    function _incrementId() private returns (uint256 count) {
        bytes32 slot = keccak256("vulcan.accounts.id.counter");

        assembly {
            count := sload(slot)
            sstore(slot, add(count, 1))
        }
    }

    function _formatError(string memory func, string memory message) private pure returns (string memory) {
        return formatError("accounts", func, message);
    }
}

/// @dev Accounts module for tests
library accountsUnsafe {
    using stdStorage for StdStorage;

    function stdStore() internal pure returns (StdStorage storage s) {
        bytes32 slot = keccak256("vulcan.accounts.stdStore");

        assembly {
            s.slot := slot
        }
    }

    function readStorage(address who, bytes32 slot) internal view returns (bytes32) {
        return accountsSafe.readStorage(who, slot);
    }

    function sign(uint256 privKey, bytes32 digest) internal pure returns (uint8, bytes32, bytes32) {
        return accountsSafe.sign(privKey, digest);
    }

    function derive(uint256 privKey) internal pure returns (address) {
        return accountsSafe.derive(privKey);
    }

    function deriveKey(string memory mnemonicOrPath, uint32 index) internal pure returns (uint256) {
        return accountsSafe.deriveKey(mnemonicOrPath, index);
    }

    function deriveKey(string memory mnemonicOrPath, string memory derivationPath, uint32 index)
        internal
        pure
        returns (uint256)
    {
        return accountsSafe.deriveKey(mnemonicOrPath, derivationPath, index);
    }

    function rememberKey(uint256 privKey) internal returns (address) {
        return accountsSafe.rememberKey(privKey);
    }

    function getNonce(address who) internal view returns (uint64) {
        return accountsSafe.getNonce(who);
    }

    function recordStorage() internal {
        return accountsSafe.recordStorage();
    }

    function getStorageAccesses(address who) internal returns (bytes32[] memory reads, bytes32[] memory writes) {
        return accountsSafe.getStorageAccesses(who);
    }

    function label(address who, string memory lbl) internal returns (address) {
        return accountsSafe.label(who, lbl);
    }

    function create() internal returns (address) {
        return accountsSafe.create();
    }

    function create(string memory name) internal returns (address) {
        return accountsSafe.create(name);
    }

    function create(string memory name, string memory lbl) internal returns (address) {
        return accountsSafe.create(name, lbl);
    }

    /// @dev Calculates the deployment address of `who` with nonce `nonce`.
    /// @param who The deployer address.
    /// @param nonce The deployer nonce.
    function getDeploymentAddress(address who, uint64 nonce) internal pure returns (address) {
        return accountsSafe.getDeploymentAddress(who, nonce);
    }

    /// @dev Calculates the deployment address of `who` with the current nonce.
    /// @param who The deployer address.
    function getDeploymentAddress(address who) internal view returns (address) {
        return accountsSafe.getDeploymentAddress(who);
    }

    /// @dev Sets the specified `slot` in the storage of the given `self` address to the provided `value`.
    /// @param self The address to modify the storage of.
    /// @param slot The storage slot to set.
    /// @param value The value to set the storage slot to.
    /// @return The address that was modified.
    function setStorage(address self, bytes32 slot, bytes32 value) internal returns (address) {
        vulcan.hevm.store(self, slot, value);
        return self;
    }

    /// @dev Sets the nonce of the given `self` address to the provided value `n`. It will revert if
    // the new nonce is lower than the current address nonce.
    /// @param self The address to set the nonce for.
    /// @param n The value to set the nonce to.
    /// @return The updated address with the modified nonce.
    function setNonce(address self, uint64 n) internal returns (address) {
        vulcan.hevm.setNonce(self, n);
        return self;
    }

    /// @dev Sets the nonce of the given `self` address to the arbitrary provided value `n`.
    /// @param self The address to set the nonce for.
    /// @param n The value to set the nonce to.
    /// @return The updated address with the modified nonce.
    function setNonceUnsafe(address self, uint64 n) internal returns (address) {
        vulcan.hevm.setNonceUnsafe(self, n);
        return self;
    }

    /// @dev Sets the `msg.sender` of the next call to `self`.
    /// @param self The address to impersonate.
    /// @return The address that was impersonated.
    function impersonateOnce(address self) internal returns (address) {
        stopImpersonate();
        vulcan.hevm.prank(self);
        return self;
    }

    /// @notice Sets the `msg.sender` of all subsequent calls to `self` until `stopImpersonate` is called
    /// @param self The address to impersonate.
    /// @return The address being impersonated.
    function impersonate(address self) internal returns (address) {
        stopImpersonate();
        vulcan.hevm.startPrank(self);
        return self;
    }

    /// @dev Sets the `msg.sender` of the next call to `self` and the `tx.origin`
    /// to `origin`.
    /// @param self The address to impersonate.
    /// @param origin The new `tx.origin`.
    /// @return The address that was impersonated.
    function impersonateOnce(address self, address origin) internal returns (address) {
        stopImpersonate();
        vulcan.hevm.prank(self, origin);
        return self;
    }

    /// @dev Sets the `msg.sender` and `tx.origin` of all the subsequent calls to `self` and `origin`
    /// respectively until `stopImpersonate` is called.
    /// @param self The address to impersonate.
    /// @param origin The new value for `tx.origin`.
    /// @return The address being impersonated.
    function impersonate(address self, address origin) internal returns (address) {
        stopImpersonate();
        vulcan.hevm.startPrank(self, origin);
        return self;
    }

    /// @notice Resets the values of `msg.sender` and `tx.origin` to the original values.
    function stopImpersonate() internal {
        try vulcan.hevm.stopPrank() {} catch (bytes memory) {}
    }

    /// @dev Sets the balance of an address and returns the address that was modified.
    /// @param self The address to set the balance of.
    /// @param bal The new balance to set.
    /// @return The address that was modified.
    function setBalance(address self, uint256 bal) internal returns (address) {
        vulcan.hevm.deal(self, bal);
        return self;
    }

    /// @dev Mints an amount of tokens to an address. This operation modifies the total supply of the token.
    /// @dev self The address that will own the tokens.
    /// @dev token The token to mint.
    /// @dev amount The amount of tokens to mint.
    /// @return The address that owns the minted tokens.
    function mintToken(address self, address token, uint256 amount) internal returns (address) {
        (, bytes memory balData) = token.call(abi.encodeWithSelector(0x70a08231, self));

        uint256 prevBal = abi.decode(balData, (uint256));

        setTokenBalance(self, token, prevBal + amount);

        (, bytes memory totSupData) = token.call(abi.encodeWithSelector(0x18160ddd));
        uint256 totSup = abi.decode(totSupData, (uint256));

        setTotalSupply(token, totSup + amount);

        return self;
    }

    /// @dev Burns an amount of tokens from an address. This operation modifies the total supply of the token.
    /// @dev self The address that owns the tokens.
    /// @dev token The token to burn.
    /// @dev amount The amount of tokens to burn.
    /// @return The address that owned the burned tokens.
    function burnToken(address self, address token, uint256 amount) internal returns (address) {
        (, bytes memory balData) = token.call(abi.encodeWithSelector(0x70a08231, self));

        uint256 prevBal = abi.decode(balData, (uint256));

        setTokenBalance(self, token, prevBal - amount);

        (, bytes memory totSupData) = token.call(abi.encodeWithSelector(0x18160ddd));
        uint256 totSup = abi.decode(totSupData, (uint256));

        setTotalSupply(token, totSup - amount);

        return self;
    }

    /// @dev Sets the token balance of an address.
    /// @param self The address to set the balance of.
    /// @param token The token that will be given to `self`.
    /// @param bal The new token balance of `self`.
    /// @return The address that was modified.
    function setTokenBalance(address self, address token, uint256 bal) internal returns (address) {
        stdStore().target(token).sig(0x70a08231).with_key(self).checked_write(bal);

        return self;
    }

    /// @dev Sets the total supply of a token.
    /// @param token The token that will be modified.
    /// @param totalSupply The new total supply of token.
    /// @return The token address.
    function setTotalSupply(address token, uint256 totalSupply) private returns (address) {
        stdStore().target(token).sig(0x18160ddd).checked_write(totalSupply);

        return token;
    }

    /// @dev Sets the code of an address.
    /// @param self The address to set the code for.
    /// @param code The new code to set for the address.
    /// @return The address that was modified.
    function setCode(address self, bytes memory code) internal returns (address) {
        vulcan.hevm.etch(self, code);
        return self;
    }

    /// @dev Generates an array of addresses with a specific length.
    /// @param length The amount of addresses to generate.
    function createMany(uint256 length) internal returns (address[] memory) {
        return accountsSafe.createMany(length);
    }

    /// @dev Generates an array of addresses with a specific length and a prefix as label.
    /// The label for each address will be `{prefix}_{i}`.
    /// @param length The amount of addresses to generate.
    /// @param prefix The prefix of the label for each address.
    function createMany(uint256 length, string memory prefix) internal returns (address[] memory) {
        return accountsSafe.createMany(length, prefix);
    }
}

lib/vulcan/src/_internal/Context.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import {vulcan} from "./Vulcan.sol";
import {accountsUnsafe as accounts} from "./Accounts.sol";
import {strings} from "./Strings.sol";
import {println, formatError} from "./Utils.sol";

type Context is bytes32;

interface IMutator {
    function mutate() external pure;
}

library ctxSafe {
    function broadcast() internal {
        vulcan.hevm.broadcast();
    }

    function broadcast(address from) internal {
        vulcan.hevm.broadcast(from);
    }

    function broadcast(uint256 privKey) internal {
        vulcan.hevm.broadcast(privKey);
    }

    function startBroadcast() internal {
        vulcan.hevm.startBroadcast();
    }

    function startBroadcast(address from) internal {
        vulcan.hevm.startBroadcast(from);
    }

    function startBroadcast(uint256 privKey) internal {
        vulcan.hevm.startBroadcast(privKey);
    }

    function stopBroadcast() internal {
        vulcan.hevm.stopBroadcast();
    }

    function assume(bool condition) internal pure {
        vulcan.hevm.assume(condition);
    }

    function pauseGasMetering() internal {
        vulcan.hevm.pauseGasMetering();
    }

    function resumeGasMetering() internal {
        vulcan.hevm.resumeGasMetering();
    }

    function startGasReport(string memory name) internal {
        if (bytes(name).length > 32) {
            revert(_formatError("startGasReport", "Gas report name can't have more than 32 characters"));
        }

        bytes32 b32Name = bytes32(bytes(name));
        bytes32 slot = keccak256(bytes("vulcan.ctx.gasReport.name"));
        accounts.setStorage(address(vulcan.hevm), slot, b32Name);
        bytes32 valueSlot = keccak256(abi.encodePacked("vulcan.ctx.gasReport", b32Name));
        accounts.setStorage(address(vulcan.hevm), valueSlot, bytes32(gasleft()));
    }

    function endGasReport() internal view {
        uint256 gas = gasleft();
        bytes32 slot = keccak256(bytes("vulcan.ctx.gasReport.name"));
        bytes32 b32Name = accounts.readStorage(address(vulcan.hevm), slot);
        bytes32 valueSlot = keccak256(abi.encodePacked("vulcan.ctx.gasReport", b32Name));
        uint256 prevGas = uint256(accounts.readStorage(address(vulcan.hevm), valueSlot));
        if (gas > prevGas) {
            revert(_formatError("endGasReport", "Gas used can't have a negative value"));
        }
        println(string.concat("gas(", string(abi.encodePacked(b32Name)), "):", strings.toString(prevGas - gas)));
    }

    function _formatError(string memory func, string memory message) private pure returns (string memory) {
        return formatError("ctx", func, message);
    }
}

/// @dev Contract used to check if a call is static or not.
contract CallContext {
    uint256 private val = 0;

    /// @dev Function used to check if the call can mutate the storage.
    function mutate() external {
        val = 0;
    }

    /// @dev Function to check if the current call is a staticcall.
    function isStaticcall() external view returns (bool) {
        try IMutator(address(this)).mutate() {
            return true;
        } catch {
            return false;
        }
    }
}

library ctxUnsafe {
    /// @dev Deterministic address that will hold the code of the `CallContext` contract.
    address internal constant CALL_CONTEXT_ADDRESS = address(uint160(uint256(keccak256("vulcan.ctx.callContext"))));

    /// @dev Function to initialize and set the code of `CALL_CONTEXT_ADDRESS`.
    function init() internal {
        accounts.setCode(CALL_CONTEXT_ADDRESS, type(CallContext).runtimeCode);
    }

    function broadcast() internal {
        ctxSafe.broadcast();
    }

    function broadcast(address from) internal {
        ctxSafe.broadcast(from);
    }

    function broadcast(uint256 privKey) internal {
        ctxSafe.broadcast(privKey);
    }

    function startBroadcast() internal {
        ctxSafe.startBroadcast();
    }

    function startBroadcast(address from) internal {
        ctxSafe.startBroadcast(from);
    }

    function startBroadcast(uint256 privKey) internal {
        ctxSafe.startBroadcast(privKey);
    }

    function stopBroadcast() internal {
        ctxSafe.stopBroadcast();
    }

    function assume(bool condition) internal pure {
        ctxSafe.assume(condition);
    }

    function pauseGasMetering() internal {
        ctxSafe.pauseGasMetering();
    }

    function resumeGasMetering() internal {
        ctxSafe.resumeGasMetering();
    }

    function startGasReport(string memory name) internal {
        ctxSafe.startGasReport(name);
    }

    function endGasReport() internal view {
        ctxSafe.endGasReport();
    }

    /// @dev Checks whether the current call is a static call or not.
    /// @return True if the current call is a static call, false otherwise.
    function isStaticcall() internal view returns (bool) {
        return CallContext(CALL_CONTEXT_ADDRESS).isStaticcall();
    }

    /// @dev sets the `block.timestamp` to `ts`
    /// @param ts the new block timestamp
    function setBlockTimestamp(Context self, uint256 ts) internal returns (Context) {
        vulcan.hevm.warp(ts);
        return self;
    }

    /// @dev sets the `block.timestamp` to `ts`
    /// @param ts the new block timestamp
    function setBlockTimestamp(uint256 ts) internal returns (Context) {
        return setBlockTimestamp(Context.wrap(0), ts);
    }

    /// @dev sets the `block.number` to `blockNumber`
    /// @param blockNumber the new block number
    function setBlockNumber(Context self, uint256 blockNumber) internal returns (Context) {
        vulcan.hevm.roll(blockNumber);
        return self;
    }

    /// @dev sets the `block.number` to `blockNumber`
    /// @param blockNumber the new block number
    function setBlockNumber(uint256 blockNumber) internal returns (Context) {
        return setBlockNumber(Context.wrap(0), blockNumber);
    }

    /// @dev sets the `block.basefee` to `baseFee`
    /// @param baseFee the new block base fee
    function setBlockBaseFee(Context self, uint256 baseFee) internal returns (Context) {
        vulcan.hevm.fee(baseFee);
        return self;
    }

    /// @dev sets the `block.basefee` to `baseFee`
    /// @param baseFee the new block base fee
    function setBlockBaseFee(uint256 baseFee) internal returns (Context) {
        return setBlockBaseFee(Context.wrap(0), baseFee);
    }

    /// @dev Sets block.prevrandao.
    /// @param newPrevrandao The new `block.prevrandao`.
    function setBlockPrevrandao(Context self, bytes32 newPrevrandao) internal returns (Context) {
        vulcan.hevm.prevrandao(newPrevrandao);
        return self;
    }

    /// @dev Sets block.prevrandao.
    /// @param newPrevrandao The new `block.prevrandao`.
    function setBlockPrevrandao(bytes32 newPrevrandao) internal returns (Context) {
        return setBlockPrevrandao(Context.wrap(0), newPrevrandao);
    }

    /// @dev sets the `block.chainid` to `chainId`
    /// @param chainId the new block chain id
    function setChainId(Context self, uint64 chainId) internal returns (Context) {
        vulcan.hevm.chainId(chainId);
        return self;
    }

    /// @dev sets the `block.chainid` to `chainId`
    /// @param chainId the new block chain id
    function setChainId(uint64 chainId) internal returns (Context) {
        return setChainId(Context.wrap(0), chainId);
    }

    /// @dev Sets the block coinbase to `who`.
    /// @param self The context.
    /// @param who The address to set as the block coinbase.
    /// @return The same context in order to allow function chaining.
    function setBlockCoinbase(Context self, address who) internal returns (Context) {
        vulcan.hevm.coinbase(who);
        return self;
    }

    /// @dev Sets the block coinbase to `who`.
    /// @param who The address to set as the block coinbase.
    /// @return The same context to allow function chaining.
    function setBlockCoinbase(address who) internal returns (Context) {
        return setBlockCoinbase(Context.wrap(0), who);
    }

    /// @dev Sets the transaction gas price.
    /// @param newGasPrice The new transaction gas price.
    function setGasPrice(Context self, uint256 newGasPrice) internal returns (Context) {
        vulcan.hevm.txGasPrice(newGasPrice);
        return self;
    }

    /// @dev Sets the transaction gas price.
    /// @param newGasPrice The new transaction gas price.
    function setGasPrice(uint256 newGasPrice) internal returns (Context) {
        return setGasPrice(Context.wrap(0), newGasPrice);
    }

    /// @dev Function used to check whether the next call reverts or not.
    /// @param revertData The function call data that that is expected to fail.
    function expectRevert(bytes memory revertData) internal {
        vulcan.hevm.expectRevert(revertData);
    }

    /// @dev Function used to check whether the next call reverts or not.
    /// @param revertData The function call signature that that is expected to fail.
    function expectRevert(bytes4 revertData) internal {
        vulcan.hevm.expectRevert(revertData);
    }

    /// @dev Function used to check whether the next call reverts or not.
    function expectRevert() internal {
        vulcan.hevm.expectRevert();
    }

    /// @dev Checks if an event was emitted with the given properties.
    /// @param checkTopic1 Whether to check the first topic match.
    /// @param checkTopic2 Whether to check the second topic match.
    /// @param checkTopic3 Whether to check the third topic match.
    /// @param checkData Whether to check the data field match.
    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) internal {
        vulcan.hevm.expectEmit(checkTopic1, checkTopic2, checkTopic3, checkData);
    }

    /// @dev Checks if an event was emitted with the given properties.
    /// @param checkTopic1 Whether to check the first topic match.
    /// @param checkTopic2 Whether to check the second topic match.
    /// @param checkTopic3 Whether to check the third topic match.
    /// @param checkData Whether to check the data field match.
    /// @param emitter The address of the expected emitter.
    function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, address emitter)
        internal
    {
        vulcan.hevm.expectEmit(checkTopic1, checkTopic2, checkTopic3, checkData, emitter);
    }

    /// @dev Function to mock a call to a specified address.
    /// @param callee The address for which the call should be mocked.
    /// @param data The data for which the call should be mocked.
    /// @param returnData The data that should be returned if `data` matches the provided call data.
    function mockCall(address callee, bytes memory data, bytes memory returnData) internal {
        vulcan.hevm.mockCall(callee, data, returnData);
    }

    /// @dev Function to mock a call to a specified address.
    /// @param callee The address for which the call should be mocked.
    /// @param msgValue The `msg.value` for which the call should be mocked.
    /// @param data The data for which the call should be mocked.
    /// @param returnData The data that should be returned if `data` matches the provided call data.
    function mockCall(address callee, uint256 msgValue, bytes memory data, bytes memory returnData) internal {
        vulcan.hevm.mockCall(callee, msgValue, data, returnData);
    }

    /// @dev Function to clear all the mocked calls.
    function clearMockedCalls() internal {
        vulcan.hevm.clearMockedCalls();
    }

    /// @dev Used to check if a call to `callee` with `data` was made.
    /// @param callee The address that is expected to be called.
    /// @param data The call data that is expected to be used.
    function expectCall(address callee, bytes memory data) internal {
        vulcan.hevm.expectCall(callee, data);
    }

    /// @dev Used to check if a call to `callee` with `data` and `msgValue` was made.
    /// @param callee The address that is expected to be called.
    /// @param msgValue The `msg.value` that is expected to be sent.
    /// @param data The call data that is expected to be used.
    function expectCall(address callee, uint256 msgValue, bytes memory data) internal {
        vulcan.hevm.expectCall(callee, msgValue, data);
    }

    /// @dev Expect a call to an address with the specified msg.value and calldata, and a minimum amount of gas.
    /// @param callee The address that is expected to be called.
    /// @param msgValue The `msg.value` that is expected to be sent.
    /// @param minGas The expected minimum amount of gas for the call.
    /// @param data The call data that is expected to be used.
    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data) internal {
        vulcan.hevm.expectCallMinGas(callee, msgValue, minGas, data);
    }

    /// @dev Expect a number call to an address with the specified msg.value and calldata, and a minimum amount of gas.
    /// @param callee The address that is expected to be called.
    /// @param msgValue The `msg.value` that is expected to be sent.
    /// @param minGas The expected minimum amount of gas for the call.
    /// @param data The call data that is expected to be used.
    /// @param count The number of calls that are expected.
    function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data, uint64 count)
        external
    {
        vulcan.hevm.expectCallMinGas(callee, msgValue, minGas, data, count);
    }

    /// @dev Allows to  write on memory only between [0x00, 0x60) and [min, max) in the current.
    /// subcontext.
    /// @param min The lower limit of the allowed memory slot.
    /// @param max The upper limit of the allowed memory slot.
    function expectSafeMemory(uint64 min, uint64 max) external {
        vulcan.hevm.expectSafeMemory(min, max);
    }

    /// @dev Allows to  write on memory only between [0x00, 0x60) and [min, max) in the next
    // subcontext.
    /// @param min The lower limit of the allowed memory slot.
    /// @param max The upper limit of the allowed memory slot.
    function expectsafememorycall(uint64 min, uint64 max) external {
        vulcan.hevm.expectSafeMemoryCall(min, max);
    }

    /// @dev Takes a snapshot of the current state of the vm and returns an identifier.
    /// @return The snapshot identifier.
    function snapshot(Context) internal returns (uint256) {
        return vulcan.hevm.snapshot();
    }

    /// @dev Takes a snapshot of the current state of the vm and returns an identifier.
    /// @return The snapshot identifier.
    function snapshot() internal returns (uint256) {
        return snapshot(Context.wrap(0));
    }

    /// @dev Reverts the state of the vm to the snapshot with id `snapshotId`.
    /// @param snapshotId The id of the snapshot to revert to.
    /// @return true if the vm was reverted to the selected snapshot.
    function revertToSnapshot(Context, uint256 snapshotId) internal returns (bool) {
        return vulcan.hevm.revertTo(snapshotId);
    }

    /// @dev Reverts the state of the vm to the snapshot with id `snapshotId`.
    /// @param snapshotId The id of the snapshot to revert to.
    /// @return true if the vm was reverted to the selected snapshot.
    function revertToSnapshot(uint256 snapshotId) internal returns (bool) {
        return revertToSnapshot(Context.wrap(0), snapshotId);
    }

    /// @dev Creates a breakpoint to jump to in the debugger.
    /// @param name The name of the breakpoint.
    function addBreakpoint(Context self, string memory name) internal returns (Context) {
        vulcan.hevm.breakpoint(name);
        return self;
    }

    /// @dev Creates a breakpoint to jump to in the debugger.
    /// @param name The name of the breakpoint.
    function addBreakpoint(string memory name) internal returns (Context) {
        return addBreakpoint(Context.wrap(0), name);
    }

    /// @dev Creates a breakpoint to jump to in the debugger.
    /// @param name The name of the breakpoint.
    /// @param condition The condition that needs to be fulfilled in order to add the breakpoint.
    function addConditionalBreakpoint(Context self, string memory name, bool condition) internal returns (Context) {
        vulcan.hevm.breakpoint(name, condition);
        return self;
    }

    /// @dev Creates a breakpoint to jump to in the debugger.
    /// @param name The name of the breakpoint.
    /// @param condition The condition that needs to be fulfilled in order to add the breakpoint.
    function addConditionalBreakpoint(string memory name, bool condition) internal returns (Context) {
        return addConditionalBreakpoint(Context.wrap(0), name, condition);
    }
}

using ctxUnsafe for Context global;

lib/vulcan/src/_internal/Events.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import {Vm as Hevm} from "forge-std/Vm.sol";
import "./Vulcan.sol";

library events {
    /// @dev Obtains the topic representation of an `uint256` parameter.
    /// @param _param The `uint256` value.
    /// @return The representation of `_param` as an event topic.
    function topic(uint256 _param) internal pure returns (bytes32) {
        return bytes32(_param);
    }

    /// @dev Obtains the topic representation of a `string` parameter.
    /// @param _param The `string` value.
    /// @return The representation of `_param` as an event topic.
    function topic(string memory _param) internal pure returns (bytes32) {
        return keccak256(bytes(_param));
    }

    /// @dev Obtains the topic representation of an `address` parameter.
    /// @param _param The `address` value.
    /// @return The representation of `_param` as an event topic.
    function topic(address _param) internal pure returns (bytes32) {
        return bytes32(uint256(uint160(_param)));
    }

    /// @dev Obtains the topic representation of a `bytes32` parameter.
    /// @param _param The `bytes32` value.
    /// @return The representation of `_param` as an event topic.
    function topic(bytes32 _param) internal pure returns (bytes32) {
        return _param;
    }

    /// @dev Obtains the topic representation of a `bytes` parameter.
    /// @param _param The `bytes` value.
    /// @return The representation of `_param` as an event topic.
    function topic(bytes memory _param) internal pure returns (bytes32) {
        return keccak256(_param);
    }

    /// @dev Obtains the topic representation of a `bool` parameter.
    /// @param _param The `bool` value.
    /// @return The representation of `_param` as an event topic.
    function topic(bool _param) internal pure returns (bytes32) {
        return bytes32(uint256(_param ? 1 : 0));
    }

    /// @dev Obtains the topic representation of a `int256` parameter.
    /// @param _param The `int256` value.
    /// @return The representation of `_param` as an event topic.
    function topic(int256 _param) internal pure returns (bytes32) {
        return bytes32(uint256(_param));
    }

    /// @dev Starts recording all transactions logs.
    function recordLogs() internal {
        vulcan.hevm.recordLogs();
    }

    /// @dev Obtains all recorded transactions logs.
    function getRecordedLogs() internal returns (Log[] memory logs) {
        Hevm.Log[] memory recorded = vulcan.hevm.getRecordedLogs();
        assembly {
            logs := recorded
        }
    }
}

lib/vulcan/src/_internal/Fmt.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import "./Strings.sol";
import {formatError} from "./Utils.sol";

enum Type {
    Bool,
    Uint256,
    Int256,
    String,
    Address,
    Bytes32,
    Bytes
}

struct Placeholder {
    uint256 start;
    uint256 end;
    Type t;
    bytes mod;
}

library fmt {
    bytes32 constant ADDRESS_HASH = keccak256(bytes("address"));
    bytes32 constant ABBREVIATED_ADDRESS_HASH = keccak256(bytes("a"));
    bytes32 constant BYTES32_HASH = keccak256(bytes("bytes32"));
    bytes32 constant ABBREVIATED_BYTES32_HASH = keccak256(bytes("b32"));
    bytes32 constant STRING_HASH = keccak256(bytes("string"));
    bytes32 constant ABBREVIATED_STRING_HASH = keccak256(bytes("s"));
    bytes32 constant BYTES_HASH = keccak256(bytes("bytes"));
    bytes32 constant ABBREVIATED_BYTES_HASH = keccak256(bytes("b"));
    bytes32 constant UINT_HASH = keccak256(bytes("uint"));
    bytes32 constant ABBREVIATED_UINT_HASH = keccak256(bytes("u"));
    bytes32 constant INT_HASH = keccak256(bytes("int"));
    bytes32 constant ABBREVIATED_INT_HASH = keccak256(bytes("i"));
    bytes32 constant BOOL_HASH = keccak256(bytes("bool"));

    function format(string memory template, bytes memory args) internal pure returns (string memory) {
        Placeholder[] memory placeholders = _parseTemplate(template);
        string[] memory decoded = _decodeArgs(placeholders, args);
        return _format(template, decoded, placeholders);
    }

    function _parseTemplate(string memory template) private pure returns (Placeholder[] memory) {
        bytes memory templateBytes = bytes(template);

        Placeholder[] memory placeholders = new Placeholder[](_countPlaceholders(templateBytes));

        if (placeholders.length == 0) {
            return placeholders;
        }

        uint256 currentIndex = 0;

        for (uint256 i; i < placeholders.length; i++) {
            placeholders[i] = _findPlaceholder(templateBytes, currentIndex);
            currentIndex = placeholders[i].end;
        }

        return placeholders;
    }

    function _countPlaceholders(bytes memory template) private pure returns (uint256) {
        uint256 count = 0;
        uint256 currentIndex = 0;
        while (true) {
            uint256 placeholderStart = _findPlaceholderStart(template, currentIndex);
            if (placeholderStart == template.length) {
                break; // No more placeholders found
            }
            count++;
            currentIndex = _findPlaceholderEnd(template, placeholderStart);
        }
        return count;
    }

    function _findPlaceholderStart(bytes memory template, uint256 offset) private pure returns (uint256) {
        for (uint256 i = offset; i < template.length - 1; i++) {
            if (template[i] == "{") {
                return i;
            }
        }
        return template.length;
    }

    function _findPlaceholderEnd(bytes memory template, uint256 start) private pure returns (uint256) {
        for (uint256 i = start + 1; i < template.length; i++) {
            if (template[i] == "}") {
                return i + 1;
            }
        }
        return template.length;
    }

    function _findModifierStart(bytes memory template, uint256 start, uint256 end) private pure returns (uint256) {
        for (uint256 i = start + 1; i < end - 1; i++) {
            if (template[i] == ":") {
                return i + 1;
            }
        }

        return end;
    }

    function _findPlaceholder(bytes memory template, uint256 start) private pure returns (Placeholder memory) {
        uint256 placeholderStart = _findPlaceholderStart(template, start);

        uint256 placeholderEnd = _findPlaceholderEnd(template, placeholderStart);

        uint256 modifierStart = _findModifierStart(template, placeholderStart, placeholderEnd);

        bytes32 typeHash = keccak256(_readSlice(template, placeholderStart + 1, modifierStart - placeholderStart - 2));

        Type t;
        if (typeHash == UINT_HASH || typeHash == ABBREVIATED_UINT_HASH) {
            t = Type.Uint256;
        } else if (typeHash == ADDRESS_HASH || typeHash == ABBREVIATED_ADDRESS_HASH) {
            t = Type.Address;
        } else if (typeHash == BOOL_HASH) {
            t = Type.Bool;
        } else if (typeHash == STRING_HASH || typeHash == ABBREVIATED_STRING_HASH) {
            t = Type.String;
        } else if (typeHash == INT_HASH || typeHash == ABBREVIATED_INT_HASH) {
            t = Type.Int256;
        } else if (typeHash == BYTES_HASH || typeHash == ABBREVIATED_BYTES_HASH) {
            t = Type.Bytes;
        } else if (typeHash == BYTES32_HASH || typeHash == ABBREVIATED_BYTES32_HASH) {
            t = Type.Bytes32;
        } else {
            revert(_formatError("_findPlaceholder(bytes,uint256)", "Unsupported placeholder type"));
        }

        bytes memory mod = modifierStart == placeholderEnd
            ? new bytes(0)
            : _readSlice(template, modifierStart, placeholderEnd - modifierStart - 1);
        return Placeholder(placeholderStart, placeholderEnd, t, mod);
    }

    function _readWord(bytes memory data, uint256 offset) private pure returns (bytes32) {
        bytes32 result;

        assembly {
            result := mload(add(add(data, 0x20), offset))
        }

        return result;
    }

    function _readSlice(bytes memory data, uint256 start, uint256 len) private pure returns (bytes memory) {
        if (len == 0) {
            return new bytes(0);
        }

        require(start + len <= data.length, _formatError("_readSlice(bytes,uint256,uint256)", "Slice out of bounds"));

        bytes memory result = new bytes(len);

        for (uint256 i = 0; i < len; i++) {
            result[i] = data[start + i];
        }

        return result;
    }

    // @dev Performs abi decoding of the given data using the given placeholders.
    function _decodeArgs(Placeholder[] memory placeholders, bytes memory data) private pure returns (string[] memory) {
        string[] memory result = new string[](placeholders.length);
        for (uint256 i = 0; i < placeholders.length; i++) {
            Placeholder memory p = placeholders[i];
            uint256 offset = i * 32;
            string memory value;
            if (p.t == Type.Bool) {
                value = strings.toString(uint256(_readWord(data, offset)) == 1);
            } else if (p.t == Type.Uint256) {
                value = _display(uint256(_readWord(data, offset)), p.mod);
            } else if (p.t == Type.Int256) {
                value = strings.toString(int256(uint256(_readWord(data, offset))));
            } else if (p.t == Type.Address) {
                value = strings.toString(address(uint160(uint256(_readWord(data, offset)))));
            } else if (p.t == Type.Bytes32) {
                value = strings.toString(_readWord(data, offset));
            } else if (p.t == Type.Bytes) {
                offset = uint256(_readWord(data, offset));
                uint256 len = uint256(_readWord(data, offset));
                value = strings.toString(_readSlice(data, offset + 32, len));
            } else if (p.t == Type.String) {
                offset = uint256(_readWord(data, offset));
                uint256 len = uint256(_readWord(data, offset));
                value = string(_readSlice(data, offset + 32, len));
            } else {
                revert(_formatError("_decodeArgs(Placeholder[],bytes)", "Unsupported type"));
            }
            result[i] = value;
        }

        return result;
    }

    // Note: create other display functions for different types if necessary
    function _display(uint256 value, bytes memory mod) private pure returns (string memory) {
        if (mod.length == 0) {
            return strings.toString(value);
        } else if (mod[0] == "d" && mod.length <= 4) {
            // Max decimals is 256
            uint8 decimals = uint8(strings.parseUint(string(_readSlice(mod, 1, mod.length - 1))));
            string memory integer = strings.toString(value / 10 ** decimals);

            // Get decimal part and pad with zeroes
            string memory remainder = strings.toString(value % 10 ** decimals);

            while (bytes(remainder).length < decimals) {
                remainder = string.concat("0", remainder);
            }

            // Get expected remainder length without trailing zeroes
            uint256 len = decimals;
            while (len > 1 && bytes(remainder)[len - 1] == "0") {
                len--;
            }

            // Set new length to remove trailing zeroes
            assembly {
                mstore(remainder, len)
            }

            return string.concat(integer, ".", remainder);
        } else {
            revert(_formatError("_display(uint256,bytes)", "Unsupported modifier"));
        }
    }

    function _format(string memory template, string[] memory decoded, Placeholder[] memory placeholders)
        private
        pure
        returns (string memory)
    {
        uint256 resultLength = bytes(template).length;

        for (uint256 i = 0; i < decoded.length; i++) {
            resultLength += bytes(decoded[i]).length;
        }

        for (uint256 i = 0; i < placeholders.length; i++) {
            Placeholder memory p = placeholders[i];
            resultLength -= p.end - p.start;
        }

        bytes memory result = new bytes(resultLength);

        // Copy template to result, replacing placeholders with decoded values
        uint256 resultIndex = 0;
        uint256 placeholderIndex = 0;
        for (uint256 i = 0; i < bytes(template).length; i++) {
            if (placeholderIndex < placeholders.length && i == placeholders[placeholderIndex].start) {
                // Copy decoded value
                bytes memory decodedValue = bytes(decoded[placeholderIndex]);
                for (uint256 j = 0; j < decodedValue.length; j++) {
                    result[resultIndex++] = decodedValue[j];
                }
                i = placeholders[placeholderIndex].end - 1;
                placeholderIndex++;
            } else {
                result[resultIndex++] = bytes(template)[i];
            }
        }

        return string(result);
    }

    function _formatError(string memory func, string memory message) private pure returns (string memory) {
        return formatError("fmt", func, message);
    }
}

lib/vulcan/src/_internal/Strings.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import "./Vulcan.sol";
import {fmt} from "./Fmt.sol";

library strings {
    function format(string memory template, bytes memory args) public pure returns (string memory) {
        return fmt.format(template, args);
    }

    /// @dev Transforms an address to a string.
    /// @param value The address to parse.
    /// @return The string representation of `value`.
    function toString(address value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Transforms a byte array to a string.
    /// @param value The byte array to parse.
    /// @return The string representation of `value`.
    function toString(bytes memory value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Transforms a bytes32 to a string.
    /// @param value The bytes32 to parse.
    /// @return The string representation of `value`.
    function toString(bytes32 value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Transforms a boolean to a string.
    /// @param value The boolean to parse.
    /// @return The string representation of `value`.
    function toString(bool value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Transforms an uint256 to a string.
    /// @param value The uint256 to parse.
    /// @return The string representation of `value`.
    function toString(uint256 value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Transforms an int256 to a string.
    /// @param value The int256 to parse.
    /// @return The string representation of `value`.
    function toString(int256 value) internal pure returns (string memory) {
        return vulcan.hevm.toString(value);
    }

    /// @dev Parses a byte array string.
    /// @param value The string to parse.
    /// @return The parsed byte array.
    function parseBytes(string memory value) internal pure returns (bytes memory) {
        return vulcan.hevm.parseBytes(value);
    }

    /// @dev Parses an address string.
    /// @param value The string to parse.
    /// @return The parsed address.
    function parseAddress(string memory value) internal pure returns (address) {
        return vulcan.hevm.parseAddress(value);
    }

    /// @dev Parses an uint256 string.
    /// @param value The string to parse.
    /// @return The parsed uint256.
    function parseUint(string memory value) internal pure returns (uint256) {
        return vulcan.hevm.parseUint(value);
    }

    /// @dev Parses an int256 string.
    /// @param value The string to parse.
    /// @return The parsed int256.
    function parseInt(string memory value) internal pure returns (int256) {
        return vulcan.hevm.parseInt(value);
    }

    /// @dev Parses a bytes32 string.
    /// @param value The string to parse.
    /// @return The parsed bytes32.
    function parseBytes32(string memory value) internal pure returns (bytes32) {
        return vulcan.hevm.parseBytes32(value);
    }

    /// @dev Parses a boolean string.
    /// @param value The string to parse.
    /// @return The parsed boolean.
    function parseBool(string memory value) internal pure returns (bool) {
        return vulcan.hevm.parseBool(value);
    }
}

lib/vulcan/src/_internal/Utils.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import {fmt} from "./Fmt.sol";

uint256 constant UINT256_MAX = type(uint256).max;
uint256 constant INT256_MIN_ABS = uint256(type(int256).max) + 1;

// Extracted from forge-std stdUtils: https://github.com/foundry-rs/forge-std/blob/7b4876e8de2a232a54159035f173e35421000c19/src/StdUtils.sol
// The main difference is that we use file-level functions instead of an abstract contract.
function bound(uint256 x, uint256 min, uint256 max) pure returns (uint256 result) {
    require(min <= max, formatError("_utils", "bound(uint256,uint256,uint256)", "Max is less than min."));
    // If x is between min and max, return x directly. This is to ensure that dictionary values
    // do not get shifted if the min is nonzero. More info: https://github.com/foundry-rs/forge-std/issues/188
    if (x >= min && x <= max) return x;

    uint256 size = max - min + 1;

    // If the value is 0, 1, 2, 3, wrap that to min, min+1, min+2, min+3. Similarly for the UINT256_MAX side.
    // This helps ensure coverage of the min/max values.
    if (x <= 3 && size > x) return min + x;
    if (x >= UINT256_MAX - 3 && size > UINT256_MAX - x) return max - (UINT256_MAX - x);

    // Otherwise, wrap x into the range [min, max], i.e. the range is inclusive.
    if (x > max) {
        uint256 diff = x - max;
        uint256 rem = diff % size;
        if (rem == 0) return max;
        result = min + rem - 1;
    } else if (x < min) {
        uint256 diff = min - x;
        uint256 rem = diff % size;
        if (rem == 0) return min;
        result = max - rem + 1;
    }
}

function bound(int256 x, int256 min, int256 max) pure returns (int256 result) {
    require(min <= max, formatError("_utils", "bound(int256,int256,int256)", "Max is less than min."));

    // Shifting all int256 values to uint256 to use _bound function. The range of two types are:
    // int256 : -(2**255) ~ (2**255 - 1)
    // uint256:     0     ~ (2**256 - 1)
    // So, add 2**255, INT256_MIN_ABS to the integer values.
    //
    // If the given integer value is -2**255, we cannot use `-uint256(-x)` because of the overflow.
    // So, use `~uint256(x) + 1` instead.
    uint256 _x = x < 0 ? (INT256_MIN_ABS - ~uint256(x) - 1) : (uint256(x) + INT256_MIN_ABS);
    uint256 _min = min < 0 ? (INT256_MIN_ABS - ~uint256(min) - 1) : (uint256(min) + INT256_MIN_ABS);
    uint256 _max = max < 0 ? (INT256_MIN_ABS - ~uint256(max) - 1) : (uint256(max) + INT256_MIN_ABS);

    uint256 y = bound(_x, _min, _max);

    // To move it back to int256 value, subtract INT256_MIN_ABS at here.
    result = y < INT256_MIN_ABS ? int256(~(INT256_MIN_ABS - y) + 1) : int256(y - INT256_MIN_ABS);
}

// Adapted from forge-std stdMath https://github.com/foundry-rs/forge-std/blob/c2236853aadb8e2d9909bbecdc490099519b70a4/src/StdMath.sol#L7
function abs(int256 a) pure returns (uint256) {
    if (a == type(int256).min) {
        return uint256(type(int256).max) + 1;
    }

    return uint256(a > 0 ? a : -a);
}

function delta(uint256 a, uint256 b) pure returns (uint256) {
    return a > b ? a - b : b - a;
}

// Adapted from forge-std stdMath https://github.com/foundry-rs/forge-std/blob/c2236853aadb8e2d9909bbecdc490099519b70a4/src/StdMath.sol#L20
function delta(int256 a, int256 b) pure returns (uint256) {
    uint256 absA = abs(a);
    uint256 absB = abs(b);

    // Same sign
    if ((a ^ b) > -1) {
        return delta(absA, absB);
    } else {
        return absA + absB;
    }
}

function format(string memory template, bytes memory args) pure returns (string memory) {
    return fmt.format(template, args);
}

function formatError(string memory module, string memory func, string memory message) pure returns (string memory) {
    return string.concat("vulcan.", module, ".", func, ": ", message);
}

function println(string memory template, bytes memory args) view {
    rawConsoleLog(fmt.format(template, args));
}

function println(string memory arg) view {
    rawConsoleLog(arg);
}

function rawConsoleLog(string memory arg) view {
    address console2Addr = 0x000000000000000000636F6e736F6c652e6c6f67;
    (bool status,) = console2Addr.staticcall(abi.encodeWithSignature("log(string)", arg));
    status;
}

function removeSelector(bytes memory data) pure returns (bytes memory) {
    require(data.length >= 4, "Input data is too short");

    // Create a new bytes variable to store the result
    bytes memory result = new bytes(data.length - 4);

    // Copy the remaining data (excluding the first 4 bytes) into the result
    for (uint256 i = 4; i < data.length; i++) {
        result[i - 4] = data[i];
    }

    return result;
}

lib/vulcan/src/_internal/Vulcan.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.8.13 <0.9.0;

import {Vm as Hevm} from "forge-std/Vm.sol";
import {watchersUnsafe as _watchersUnsafe, Call, Watcher} from "./Watchers.sol";
import {ctxUnsafe as _ctxUnsafe} from "./Context.sol";

/// @dev Struct that represent an EVM log
struct Log {
    bytes32[] topics;
    bytes data;
    address emitter;
}

library vulcan {
    using vulcan for *;

    bytes32 constant GLOBAL_FAILED_SLOT = bytes32("failed");

    /// @dev forge-std VM
    Hevm internal constant hevm = Hevm(address(bytes20(uint160(uint256(keccak256("hevm cheat code"))))));

    /// @dev Initializes the context module
    function init() internal {
        _ctxUnsafe.init();
    }

    /// @dev Checks if `fail` was called at some point.
    /// @return true if `fail` was called, false otherwise
    function failed() internal view returns (bool) {
        bytes32 globalFailed = vulcan.hevm.load(address(hevm), GLOBAL_FAILED_SLOT);
        return globalFailed == bytes32(uint256(1));
    }

    /// @dev Signal that an expectation/assertion failed.
    function fail() internal {
        vulcan.hevm.store(address(hevm), GLOBAL_FAILED_SLOT, bytes32(uint256(1)));
    }

    /// @dev Resets the failed state.
    function clearFailure() internal {
        vulcan.hevm.store(address(hevm), GLOBAL_FAILED_SLOT, bytes32(uint256(0)));
    }

    /// @dev Starts monitoring an address.
    /// @param _target The address to monitor.
    /// @return The Watcher contract that monitors the `_target` address.
    function watch(address _target) internal returns (Watcher) {
        return _watchersUnsafe.watch(_target);
    }

    /// @dev Stops monitoring an address.
    /// @param _target The address to stop monitoring.
    function stopWatcher(address _target) internal {
        _watchersUnsafe.stop(_target);
    }
}

lib/vulcan/src/_internal/Watchers.sol

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.13 <0.9.0;

import "./Vulcan.sol";
import "./Events.sol";
import {accountsUnsafe as accounts} from "./Accounts.sol";
import {ctxUnsafe as ctx} from "./Context.sol";
import {formatError} from "./Utils.sol";

struct Call {
    bytes callData;
    bool success;
    bytes returnData;
    Log[] logs;
}

library watchersUnsafe {
    using watchersUnsafe for *;

    /// @dev Magic.
    bytes32 constant WATCHERS_MAGIC = keccak256("vulcan.watchers.magic");

    /// @dev Obtains the address of the watcher for `target`.
    /// @param target The address for which we need to get the watcher address.
    /// @return The address of the watcher.
    function watcherAddress(address target) internal pure returns (address) {
        return address(uint160(uint256(uint160(target)) ^ uint256(WATCHERS_MAGIC)));
    }

    /// @dev Obtains the address of the target for `_target`.
    /// @param _watcher The address for which we need to get the target address.
    /// @return The address of the target.
    function targetAddress(address _watcher) internal pure returns (address) {
        return address(uint160(uint256(uint160(_watcher)) ^ uint256(WATCHERS_MAGIC)));
    }

    /// @dev Obtains the Watcher implementation for the `target` address.
    /// @param target The address used to obtain the watcher implementation address.
    /// @return The Watcher implementation.
    function watcher(address target) internal view returns (Watcher) {
        address _watcher = watcherAddress(target);
        require(_watcher.code.length != 0, _formatError("watcher(address)", "Address doesn't have a watcher"));

        return Watcher(_watcher);
    }

    /// @dev Starts watching a `target` address.
    /// @param target The address to watch.
    /// @return The Watcher implementation.
    function watch(address target) internal returns (Watcher) {
        address _watcher = watcherAddress(target);
        require(_watcher.code.length == 0, _formatError("watch(address)", "Address already has a watcher"));

        accounts.setCode(_watcher, type(Watcher).runtimeCode);

        WatcherProxy proxy = new WatcherProxy();

        bytes memory targetCode = target.code;

        // Switcheroo
        accounts.setCode(target, address(proxy).code);
        accounts.setCode(address(proxy), targetCode);

        Watcher(_watcher).setImplementationAddress(address(proxy));

        return Watcher(_watcher);
    }

    /// @dev Stops watching the `target` address.
    /// @param target The address to stop watching.
    function stop(address target) internal {
        target.stopWatcher();
    }

    /// @dev Stops watching the `target` address.
    /// @param target The address to stop watching.
    function stopWatcher(address target) internal {
        watcher(target).stop();
    }

    /// @dev Obtains all the calls made to the `target` address.
    /// @param target The address of the target contract to query.
    /// @return An array of `Call` structs, each containing information about a call.
    function calls(address target) internal view returns (Call[] memory) {
        return watcher(target).calls();
    }

    /// @dev Obtains an specific call made to the `target` address at an specific index.
    /// @param target The address of the target contract to query.
    /// @param index The index of the call to query.
    /// @return A `Call` struct that contains the information about the call.
    function getCall(address target, uint256 index) internal view returns (Call memory) {
        return watcher(target).getCall(index);
    }

    /// @dev Obtains the first call made to the `target` address.
    /// @param target The address of the target contract to query.
    /// @return A `Call` struct that contains the information about the call.
    function firstCall(address target) internal view returns (Call memory) {
        return watcher(target).firstCall();
    }

    /// @dev Obtains the last call made to the `target` address.
    /// @param target The address of the target contract to query.
    /// @return A `Call` struct that contains the information about the call.
    function lastCall(address target) internal view returns (Call memory) {
        return watcher(target).lastCall();
    }

    /// @dev Starts capturing reverts for the `target` address. This will prevent the `target` contract to
    /// revert until `disableCaptureReverts` is called. This is meant to be used in conjunction with the `toHaveReverted` and
    /// `toHaveRevertedWith` functions from the expect library.
    /// @param target The address for which the reverts are going to be captured.
    /// @return The Watcher implementation.
    function captureReverts(address target) internal returns (Watcher) {
        Watcher _watcher = watcher(target);
        _watcher.captureReverts();
        return _watcher;
    }

    /// @dev Stops capturing reverts for the `target` address.
    /// @param target The target address.
    /// @return The Watcher implementation.
    function disableCaptureReverts(address target) internal returns (Watcher) {
        Watcher _watcher = watcher(target);
        _watcher.disableCaptureReverts();
        return _watcher;
    }

    function _formatError(string memory func, string memory message) private pure returns (string memory) {
        return formatError("watchers", func, message);
    }
}

contract Watcher {
    /// @dev Whether to capture reverts or not.
    bool public shouldCaptureReverts;
    /// @dev The address of the implementation.
    address public implementation;

    /// @dev Stores all the calls made.
    Call[] private _calls;

    /// @dev Stores a call.
    /// @param _callData The data for the call.
    /// @param _success True if the call succeeded, false otherwise.
    /// @param _returnData The data that was returned from the call.
    /// @param _logs The logs that were emitted on the call.
    function storeCall(bytes memory _callData, bool _success, bytes memory _returnData, Log[] memory _logs) external {
        Call storage call = _calls.push();
        call.callData = _callData;
        call.success = _success;
        call.returnData = _returnData;

        Log[] storage logs = call.logs;

        for (uint256 i; i < _logs.length; ++i) {
            logs.push(_logs[i]);
        }
    }

    /// @dev Returns all the calls that were made to the `implementation` contract.
    /// @return An array of `Call` structs, each containing information about a call.
    function calls() external view returns (Call[] memory) {
        return _calls;
    }

    /// @dev Returns a specific call that was made to the `implementation` contract.
    /// @return A `Call` struct containing information about a call.
    function getCall(uint256 index) external view returns (Call memory) {
        return _calls[index];
    }

    /// @dev Returns the first call that was made to the `implementation` contract.
    /// @return A `Call` struct containing information about a call.
    function firstCall() external view returns (Call memory) {
        return _calls[0];
    }

    /// @dev Returns the last call that was made to the `implementation` contract.
    /// @return A `Call` struct containing information about a call.
    function lastCall() external view returns (Call memory) {
        Call[] memory currentCalls = _calls;

        return currentCalls[currentCalls.length - 1];
    }

    /// @dev Starts capturing reverts for the `implementation` contract.
    function captureReverts() external {
        shouldCaptureReverts = true;
    }

    /// @dev Stops capturing reverts for the `implementation` contract.
    function disableCaptureReverts() external {
        shouldCaptureReverts = false;
    }

    /// @dev Stops watching calls for the `implementation` contract.
    function stop() external {
        address target = watchersUnsafe.targetAddress(address(this));
        accounts.setCode(target, implementation.code);

        shouldCaptureReverts = false;
        implementation = address(0);
        // Sets the array length to 0. Invoking `storeCall` after `stop` will override the items on
        // the array
        delete _calls;

        accounts.setCode(address(this), bytes(""));
    }

    /// @dev Sets the address of the `implementation` contract.
    /// @param _implementation The address of the implementation contract.
    function setImplementationAddress(address _implementation) external {
        implementation = _implementation;
    }
}

contract WatcherProxy {
    using vulcan for *;

    /// @dev The target contract
    address private immutable _target;

    constructor() {
        _target = address(this);
    }

    /// @dev A fallback function that will capture every call made to this contract and proxy them
    /// to `_target`.
    /// @param _callData The call data.
    /// @return The data returnded from the `_target` contract proxied call.
    fallback(bytes calldata _callData) external payable returns (bytes memory) {
        ctx.pauseGasMetering();
        bool isStatic = ctx.isStaticcall();

        if (!isStatic) {
            events.recordLogs();
        }

        ctx.resumeGasMetering();

        (bool success, bytes memory returnData) = _target.delegatecall(_callData);

        ctx.pauseGasMetering();

        // TODO: ugly, try to clean up
        if (!isStatic) {
            Log[] memory logs = events.getRecordedLogs();

            // Filter logs by address and replace in place
            uint256 watcherLogCount = 0;
            for (uint256 i = 0; i < logs.length; i++) {
                if (logs[i].emitter == address(this)) {
                    logs[watcherLogCount] = logs[i];
                    watcherLogCount++;
                }
            }

            Log[] memory filteredLogs = new Log[](watcherLogCount);

            // Add logs to call
            for (uint256 i = 0; i < watcherLogCount; i++) {
                filteredLogs[i] = logs[i];
            }

            Watcher watcher = watchersUnsafe.watcher(address(this));
            watcher.storeCall(_callData, success, returnData, filteredLogs);

            if (!watcher.shouldCaptureReverts() && !success) {
                ctx.resumeGasMetering();
                assembly {
                    revert(add(returnData, 32), mload(returnData))
                }
            }
        } else if (!success) {
            ctx.resumeGasMetering();
            assembly {
                revert(add(returnData, 32), mload(returnData))
            }
        }

        ctx.resumeGasMetering();

        return returnData;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "@solidstate/=lib/solidstate-solidity/contracts/",
    "lib/forge-std:ds-test/=lib/forge-std/lib/ds-test/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "solmate/=lib/solmate/",
    "@vulcan/=lib/vulcan/src/",
    "@permit2/=lib/permit2/src/",
    "@permit2-test/=lib/permit2/test/",
    "@mocks/=contracts-mocks/src/",
    "@internal/=contracts-internal/src/",
    "@common/=contracts-common/src/",
    "@auth/=contracts-auth/src/",
    "@exchange/=contracts-exchange/src/",
    "@dyor/=contracts-dyor/src/",
    "@signatures/=contracts-signatures/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/openzeppelin-contracts/contracts/",
    "permit2/=lib/permit2/",
    "solidstate-solidity/=lib/solidstate-solidity/contracts/",
    "vulcan/=lib/vulcan/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.