ProxyFirewall

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "lib/forta-firewall-contracts/src/ProxyFirewall.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import {Proxy} from "@openzeppelin/contracts/proxy/Proxy.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Firewall} from "./Firewall.sol";
import "./interfaces/IProxyFirewall.sol";
import "./interfaces/FirewallDependencies.sol";

/**
 * @notice This contract provides firewall functionality as an intermediary contract
 * between a proxy and a logic contract, acting as a proxy firewall. It automatically
 * intercepts any calls to the logic contract, tries to execute checkpoints if needed and
 * falls back to the original logic contract with delegatecall.
 *
 * The storage used by the Firewall contract and the proxy firewall contract is namespaced
 * and causes no collision. The checkpoints must be adjusted by calling the setCheckpoint(Checkpoint)
 * function.
 *
 * When used with an ERC1967 proxy and a UUPSUpgradeable logic contract, the proxy storage points
 * to the proxy firewall and the proxy firewall points to the logic contract, in the proxy
 * storage. Both of the proxy firewall and the logic contract operate on the proxy storage.
 *
 * The UUPSUpgradeable logic contract keeps the privileges to modify the implementation specified
 * at ERC1967 proxy storage. The proxy firewall is able to point to a next implementation on the
 * proxy storage. To upgrade to the proxy firewall atomically, the logic contract should be invoked
 * to modify the implementation storage on the proxy, in order to point to the proxy firewall logic.
 * As a next action in the same transaction, the proxy firewall should be pointed to the logic contract.
 * For such upgrade cases, upgradeToAndCall() and upgradeNextAndCall() functions are made available
 * from the UUPSUpgradeable and ProxyFirewall contracts, respectively.
 *
 * This contract preserves msg.sender, msg.sig and msg.data because it falls back to doing a DELEGATECALL
 * on the next implementation with the same call data.
 */
contract ProxyFirewall is IProxyFirewall, Firewall, Proxy, Initializable {
    error UpgradeNonPayable();

    /// @custom:storage-location erc7201:forta.ProxyFirewall.next.implementation
    bytes32 internal constant NEXT_IMPLEMENTATION_SLOT =
        0x9e3fe722f43dfec528e68fcd2db9596358ca7182739c61c40dd16fd5eb878300;

    constructor() {
        _disableInitializers();
    }

    /**
     * @notice Initializes the security config for the first time.
     * @param _validator Validator used for checkpoint execution calls.
     * @param _attesterControllerId The ID of the external controller which keeps settings related
     * to the attesters.
     * @param _firewallAccess Firewall access controller.
     */
    function initializeFirewallConfig(
        ISecurityValidator _validator,
        ICheckpointHook _checkpointHook,
        bytes32 _attesterControllerId,
        IFirewallAccess _firewallAccess
    ) public initializer {
        _updateFirewallConfig(_validator, _checkpointHook, _attesterControllerId, _firewallAccess);
    }

    /**
     * @notice Sets the next implementation contract which the fallback function will delegatecall to.
     * Copied and adapted from OpenZeppelin ERC1967Utils.upgradeToAndCall().
     * @param newImplementation The next implementation contract
     * @param data Call data
     */
    function upgradeNextAndCall(address newImplementation, bytes memory data) public payable onlyLogicUpgrader {
        require(newImplementation != address(0), "next implementation after proxy firewall cannot be zero address");
        StorageSlot.getAddressSlot(NEXT_IMPLEMENTATION_SLOT).value = newImplementation;
        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /// @inheritdoc Proxy
    function _implementation() internal view override returns (address) {
        return StorageSlot.getAddressSlot(NEXT_IMPLEMENTATION_SLOT).value;
    }

    /// @inheritdoc Proxy
    function _fallback() internal override {
        _secureExecution();
        super._fallback();
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     * Copied from OpenZeppelin ERC1967Utils library.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert UpgradeNonPayable();
        }
    }

    receive() external payable virtual {
        _fallback();
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/proxy/Proxy.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol)

pragma solidity ^0.8.20;

/**
 * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
 * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
 * be specified by overriding the virtual {_implementation} function.
 *
 * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
 * different contract through the {_delegate} function.
 *
 * The success and return data of the delegated call will be returned back to the caller of the proxy.
 */
abstract contract Proxy {
    /**
     * @dev Delegates the current call to `implementation`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _delegate(address implementation) internal virtual {
        assembly {
            // Copy msg.data. We take full control of memory in this inline assembly
            // block because it will not return to Solidity code. We overwrite the
            // Solidity scratch pad at memory position 0.
            calldatacopy(0, 0, calldatasize())

            // Call the implementation.
            // out and outsize are 0 because we don't know the size yet.
            let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)

            // Copy the returned data.
            returndatacopy(0, 0, returndatasize())

            switch result
            // delegatecall returns 0 on error.
            case 0 {
                revert(0, returndatasize())
            }
            default {
                return(0, returndatasize())
            }
        }
    }

    /**
     * @dev This is a virtual function that should be overridden so it returns the address to which the fallback
     * function and {_fallback} should delegate.
     */
    function _implementation() internal view virtual returns (address);

    /**
     * @dev Delegates the current call to the address returned by `_implementation()`.
     *
     * This function does not return to its internal call site, it will return directly to the external caller.
     */
    function _fallback() internal virtual {
        _delegate(_implementation());
    }

    /**
     * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
     * function in the contract matches the call data.
     */
    fallback() external payable virtual {
        _fallback();
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}
"
    },
    "lib/forta-firewall-contracts/src/Firewall.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import {Proxy} from "@openzeppelin/contracts/proxy/Proxy.sol";
import {StorageSlot} from "@openzeppelin/contracts/utils/StorageSlot.sol";
import {TransientSlot} from "@openzeppelin/contracts/utils/TransientSlot.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {FirewallPermissions} from "./FirewallPermissions.sol";
import {Quantization} from "./Quantization.sol";
import "./interfaces/IFirewall.sol";
import "./interfaces/FirewallDependencies.sol";
import "./interfaces/IAttesterInfo.sol";

/**
 * @notice Firewall is a base contract which provides protection against exploits.
 * It keeps a collection of configurable checkpoints per function, in its namespaced storage,
 * and makes available internal functions to the child contract in order to help intercept
 * function calls.
 *
 * When a function call is intercepted, one of the arguments can be used as a reference to compare
 * with a configured threshold. Exceeding the threshold causes checkpoint execution which requires
 * a corresponding attestation to be present in the SecurityValidator.
 */
abstract contract Firewall is IFirewall, IAttesterInfo, FirewallPermissions {
    using StorageSlot for bytes32;
    using TransientSlot for bytes32;
    using Quantization for uint256;

    error InvalidActivationType();
    error UntrustedAttester(address attester);
    error CheckpointBlocked();
    error RefStartLargerThanEnd();

    struct FirewallStorage {
        ISecurityValidator validator;
        ICheckpointHook checkpointHook;
        bytes32 attesterControllerId;
        mapping(bytes4 funcSelector => Checkpoint checkpoint) checkpoints;
    }

    /// @custom:storage-location erc7201:forta.Firewall.storage
    bytes32 private constant STORAGE_SLOT = 0x993f81a6354aa9d98fa5ac249e63371dfc7f5589eeb8a5b081145c8ed289c400;

    /**
     * @notice Updates the firewall config.
     * @param _validator Validator used for checkpoint execution calls.
     * @param _checkpointHook Checkpoint hook contract which is called before every checkpoint.
     * @param _attesterControllerId The ID of the external controller which keeps settings related
     * to the attesters.
     * @param _firewallAccess Firewall access controller.
     */
    function updateFirewallConfig(
        ISecurityValidator _validator,
        ICheckpointHook _checkpointHook,
        bytes32 _attesterControllerId,
        IFirewallAccess _firewallAccess
    ) public virtual onlyFirewallAdmin {
        _updateFirewallConfig(_validator, _checkpointHook, _attesterControllerId, _firewallAccess);
    }

    /**
     * @notice Updates the firewall config.
     * @param _validator The security validator which the firewall calls for saving
     * the attestation and executing checkpoints.
     * @param _checkpointHook Checkpoint hook contract which is called before every checkpoint.
     * @param _attesterControllerId The id of the controller that lives on Forta chain. Attesters
     * regards this value to find out the settings for this contract before creating an attestation.
     * @param _firewallAccess The access control contract that knows the accounts which can manage
     * the settings of a firewall.
     */
    function _updateFirewallConfig(
        ISecurityValidator _validator,
        ICheckpointHook _checkpointHook,
        bytes32 _attesterControllerId,
        IFirewallAccess _firewallAccess
    ) internal virtual {
        FirewallStorage storage $ = _getFirewallStorage();
        $.validator = _validator;
        $.checkpointHook = _checkpointHook;
        $.attesterControllerId = _attesterControllerId;
        _updateFirewallAccess(_firewallAccess);
        emit SecurityConfigUpdated(_validator, _firewallAccess);
        emit AttesterControllerUpdated(_attesterControllerId);
    }

    /**
     * @notice Returns the firewall configuration.
     * @return validator The security validator which the firewall calls for saving
     * the attestation and executing checkpoints.
     * @return checkpointHook Checkpoint hook contract which is called before every checkpoint.
     * @return attesterControllerId The id of the controller that lives on Forta chain. Attesters
     * regards this value to find out the settings for this contract before creating an attestation.
     * @return firewallAccess The access control contract that knows the accounts which can manage
     * the settings of a firewall.
     */
    function getFirewallConfig() public view returns (ISecurityValidator, ICheckpointHook, bytes32, IFirewallAccess) {
        FirewallStorage storage $ = _getFirewallStorage();
        IFirewallAccess firewallAccess = _getFirewallAccess();
        return ($.validator, $.checkpointHook, $.attesterControllerId, firewallAccess);
    }

    /**
     * Updates the trusted attesters contract. This contract is used for checking current attester
     * against the trusted ones only if set. If it is set as zero address (or is unset) then the check
     * defaults to the firewall access contract.
     * @param _trustedAttesters The contract which knows the set of trusted attesters.
     */
    function updateTrustedAttesters(ITrustedAttesters _trustedAttesters) public virtual onlyFirewallAdmin {
        _updateTrustedAttesters(_trustedAttesters);
        emit TrustedAttestersUpdated(_trustedAttesters);
    }

    /**
     * @notice Returns the attester controller id from the configuration.
     * @return Attester controller ID
     */
    function getAttesterControllerId() public view returns (bytes32) {
        return _getFirewallStorage().attesterControllerId;
    }

    /**
     * @notice Sets checkpoint values for given function selector, call data byte range
     * and with given threshold type.
     * @param selector Selector of the function.
     * @param checkpoint Checkpoint data.
     */
    function setCheckpoint(bytes4 selector, Checkpoint memory checkpoint) public virtual onlyCheckpointManager {
        if (checkpoint.refStart > checkpoint.refEnd) revert RefStartLargerThanEnd();
        _getFirewallStorage().checkpoints[selector] = checkpoint;
    }

    /**
     * @notice Sets the checkpoint activation type.
     * @param selector Selector of the function.
     * @param activation Activation type.
     */
    function setCheckpointActivation(bytes4 selector, Activation activation) public virtual onlyCheckpointManager {
        _getFirewallStorage().checkpoints[selector].activation = activation;
    }

    /**
     * @notice Gets the checkpoint values for given function selector.
     * @param selector Selector of the function.
     * @return Checkpoint threshold
     * @return Checkpoint reference start
     * @return Checkpoint reference end
     * @return Checkpoint activation mode
     * @return Checkpoint trusted origin mode enablement state
     */
    function getCheckpoint(bytes4 selector) public view virtual returns (uint192, uint16, uint16, Activation, bool) {
        Checkpoint storage checkpoint = _getFirewallStorage().checkpoints[selector];
        return (
            checkpoint.threshold,
            checkpoint.refStart,
            checkpoint.refEnd,
            checkpoint.activation,
            checkpoint.trustedOrigin
        );
    }

    /**
     * @notice Helps write an attestation and call any function of this contract.
     * @param attestation The set of fields that correspond to and enable the execution of call(s)
     * @param attestationSignature Signature of EIP-712 message
     * @param data Call data which contains the function selector and the encoded arguments
     */
    function attestedCall(Attestation calldata attestation, bytes calldata attestationSignature, bytes calldata data)
        public
        returns (bytes memory)
    {
        _getFirewallStorage().validator.saveAttestation(attestation, attestationSignature);
        return Address.functionDelegateCall(address(this), data);
    }

    function _secureExecution() internal virtual {
        Checkpoint memory checkpoint = _getFirewallStorage().checkpoints[msg.sig];
        /// Default to msg data length.
        uint256 refEnd = checkpoint.refEnd;
        if (refEnd > msg.data.length) refEnd = msg.data.length;
        if (msg.sig == 0 || (checkpoint.refEnd == 0 && checkpoint.refStart == 0)) {
            /// Ether transaction or paid transaction with no ref range: use msg.value as ref
            _secureExecution(msg.sender, msg.sig, msg.value);
        } else if (refEnd - checkpoint.refStart > 32) {
            /// Support larger data ranges as direct input hashes instead of deriving a reference.
            bytes calldata byteRange = msg.data[checkpoint.refStart:refEnd];
            bytes32 input = keccak256(byteRange);
            _secureExecution(msg.sender, msg.sig, input);
        } else {
            bytes calldata byteRange = msg.data[checkpoint.refStart:refEnd];
            uint256 ref = uint256(bytes32(byteRange));
            _secureExecution(msg.sender, msg.sig, ref);
        }
    }

    function _secureExecution(address caller, bytes4 selector, uint256 ref) internal virtual {
        Checkpoint memory checkpoint = _getFirewallStorage().checkpoints[selector];
        bool ok;
        (ref, ok) = _checkpointActivated(checkpoint, caller, selector, ref);
        if (ok) _executeCheckpoint(checkpoint, caller, bytes32(ref.quantize()), selector);
    }

    function _secureExecution(address caller, bytes4 selector, bytes32 input) internal virtual {
        Checkpoint memory checkpoint = _getFirewallStorage().checkpoints[selector];
        bool ok = _checkpointActivated(checkpoint, caller, selector);
        if (ok) _executeCheckpoint(checkpoint, caller, input, selector);
    }

    function _executeCheckpoint(Checkpoint memory checkpoint, address caller, bytes32 input, bytes4 selector)
        internal
        virtual
    {
        FirewallStorage storage $ = _getFirewallStorage();

        /// Short-circuit if the trusted origin pattern is supported and is available.
        /// Otherwise, continue with checkpoint execution.
        if (_isTrustedOrigin(checkpoint)) return;

        $.validator.executeCheckpoint(keccak256(abi.encode(caller, address(this), selector, input)));

        /// Ensure first that the current attester can be trusted.
        /// If the current attester is zero address, let the security validator deal with that.
        address currentAttester = $.validator.getCurrentAttester();
        if (currentAttester != address(0) && !_isTrustedAttester(currentAttester)) {
            revert UntrustedAttester(currentAttester);
        }
    }

    function _checkpointActivated(Checkpoint memory checkpoint, address caller, bytes4 selector, uint256 ref)
        internal
        virtual
        returns (uint256, bool)
    {
        ICheckpointHook checkpointHook = _getFirewallStorage().checkpointHook;
        if (address(checkpointHook) != address(0)) {
            HookResult result = checkpointHook.handleCheckpointWithRef(caller, selector, ref);
            if (result == HookResult.ForceActivation) return (ref, true);
            if (result == HookResult.ForceDeactivation) return (ref, false);
            // Otherwise, just keep on with default checkpoint configuration and logic.
        }
        if (checkpoint.activation == Activation.Inactive) return (ref, false);
        if (checkpoint.activation == Activation.AlwaysBlocked) revert CheckpointBlocked();
        if (checkpoint.activation == Activation.AlwaysActive) return (ref, true);
        if (checkpoint.activation == Activation.ConstantThreshold) return (ref, ref >= checkpoint.threshold);
        if (checkpoint.activation != Activation.AccumulatedThreshold) {
            revert InvalidActivationType();
        }
        /// Continue with the "accumulated threshold" logic.
        bytes32 slot = keccak256(abi.encode(selector, msg.sender));
        uint256 acc = TransientSlot.tload(slot.asUint256());
        acc += ref;
        TransientSlot.tstore(slot.asUint256(), acc);
        return (ref, acc >= checkpoint.threshold);
    }

    function _checkpointActivated(Checkpoint memory checkpoint, address caller, bytes4 selector)
        internal
        virtual
        returns (bool)
    {
        ICheckpointHook checkpointHook = _getFirewallStorage().checkpointHook;
        if (address(checkpointHook) != address(0)) {
            HookResult result = checkpointHook.handleCheckpoint(caller, selector);
            if (result == HookResult.ForceActivation) return true;
            if (result == HookResult.ForceDeactivation) return false;
            // Otherwise, just keep on with default checkpoint configuration and logic.
        }
        if (checkpoint.activation == Activation.Inactive) return false;
        if (checkpoint.activation == Activation.AlwaysBlocked) revert CheckpointBlocked();
        if (checkpoint.activation == Activation.AlwaysActive) return true;
        return false;
    }

    function _isTrustedOrigin(Checkpoint memory checkpoint) internal virtual returns (bool) {
        if (checkpoint.trustedOrigin) {
            emit SupportsTrustedOrigin(address(this));
            return _isTrustedAttester(tx.origin);
        }
        return false;
    }

    function _getFirewallStorage() internal pure virtual returns (FirewallStorage storage $) {
        assembly {
            $.slot := STORAGE_SLOT
        }
    }
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/IProxyFirewall.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import "./IFirewall.sol";

interface IProxyFirewall is IFirewall {
    function initializeFirewallConfig(
        ISecurityValidator _validator,
        ICheckpointHook _checkpointHook,
        bytes32 _attesterControllerId,
        IFirewallAccess _firewallAccess
    ) external;

    function upgradeNextAndCall(address newImplementation, bytes memory data) external payable;
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/FirewallDependencies.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import "./ISecurityValidator.sol";
import "./ICheckpointHook.sol";
import "./IFirewallAccess.sol";
import "./ITrustedAttesters.sol";
"
    },
    "lib/openzeppelin-contracts/contracts/utils/Errors.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}
"
    },
    "lib/forta-firewall-contracts/src/FirewallPermissions.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import "./interfaces/IFirewallAccess.sol";
import "./interfaces/ITrustedAttesters.sol";

/**
 * @notice Simplifies interactions with a firewall access contract.
 */
abstract contract FirewallPermissions {
    error CallerNotFirewallAdmin(address caller);
    error CallerNotCheckpointManager(address caller);
    error CallerNotLogicUpgrader(address caller);
    error CallerNotCheckpointExecutor(address caller);
    error ZeroFirewallAccess();

    struct FirewallPermissionsStorage {
        IFirewallAccess firewallAccess;
        ITrustedAttesters trustedAttesters;
    }

    /// @custom:storage-location erc7201:forta.FirewallPermissions.storage
    bytes32 private constant STORAGE_SLOT = 0x5a36dfc2750cc10abe5f95f24b6fce874396e21527ff7f50fb33b5ccc8b7d500;

    modifier onlyFirewallAdmin() {
        if (!_getFirewallPermissionsStorage().firewallAccess.isFirewallAdmin(msg.sender)) {
            revert CallerNotFirewallAdmin(msg.sender);
        }
        _;
    }

    modifier onlyCheckpointManager() {
        if (!_getFirewallPermissionsStorage().firewallAccess.isCheckpointManager(msg.sender)) {
            revert CallerNotCheckpointManager(msg.sender);
        }
        _;
    }

    modifier onlyLogicUpgrader() {
        if (!_getFirewallPermissionsStorage().firewallAccess.isLogicUpgrader(msg.sender)) {
            revert CallerNotLogicUpgrader(msg.sender);
        }
        _;
    }

    modifier onlyCheckpointExecutor() {
        if (!_getFirewallPermissionsStorage().firewallAccess.isCheckpointExecutor(msg.sender)) {
            revert CallerNotCheckpointExecutor(msg.sender);
        }
        _;
    }

    function _updateFirewallAccess(IFirewallAccess firewallAccess) internal {
        if (address(firewallAccess) == address(0)) revert ZeroFirewallAccess();
        _getFirewallPermissionsStorage().firewallAccess = firewallAccess;
    }

    function _getFirewallAccess() internal view returns (IFirewallAccess) {
        return _getFirewallPermissionsStorage().firewallAccess;
    }

    function _updateTrustedAttesters(ITrustedAttesters trustedAttesters) internal {
        _getFirewallPermissionsStorage().trustedAttesters = trustedAttesters;
    }

    function _getTrustedAttesters() internal view returns (ITrustedAttesters) {
        return _getFirewallPermissionsStorage().trustedAttesters;
    }

    function _getFirewallPermissionsStorage() private pure returns (FirewallPermissionsStorage storage $) {
        assembly {
            $.slot := STORAGE_SLOT
        }
    }

    function _isTrustedAttester(address attester) internal view returns (bool) {
        FirewallPermissionsStorage storage $ = _getFirewallPermissionsStorage();
        if (address($.trustedAttesters) != address(0)) {
            return $.trustedAttesters.isTrustedAttester(attester);
        }
        return $.firewallAccess.isTrustedAttester(attester);
    }
}
"
    },
    "lib/forta-firewall-contracts/src/Quantization.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

/**
 * @notice Until the attestation can arrive on chain and the user transaction can be executed,
 * the asset amounts that will be processed can fluctuate slightly and cause different hashes
 * to be produced during the real execution and a mismatch with the values in the attestation.
 * This library solves this problem by quantizing the reference value used in checkpoint hash
 * computation.
 */
library Quantization {
    /**
     * @notice Quantizes the given value by zeroing the smaller digits.
     * @param n Input value.
     */
    function quantize(uint256 n) public pure returns (uint256) {
        uint256 offset = 8 * Math.log256(n);
        return ((n >> offset) << offset) + (2 ** offset - 1);
    }
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/IFirewall.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import "./ISecurityValidator.sol";
import "./IFirewallAccess.sol";
import "./Checkpoint.sol";
import "./ICheckpointHook.sol";
import "./ITrustedAttesters.sol";

interface IFirewall {
    event SecurityConfigUpdated(ISecurityValidator indexed validator, IFirewallAccess indexed firewallAccess);
    event TrustedAttestersUpdated(ITrustedAttesters indexed trustedAttesters);
    event SupportsTrustedOrigin(address indexed firewall);
    event CheckpointUpdated(bytes4 selector, Checkpoint checkpoint);

    function updateFirewallConfig(
        ISecurityValidator _validator,
        ICheckpointHook _checkpointHook,
        bytes32 _attesterControllerId,
        IFirewallAccess _firewallAccess
    ) external;

    function getFirewallConfig()
        external
        view
        returns (
            ISecurityValidator _validator,
            ICheckpointHook _checkpointHook,
            bytes32 _attesterControllerId,
            IFirewallAccess _firewallAccess
        );

    function updateTrustedAttesters(ITrustedAttesters _trustedAttesters) external;

    function setCheckpoint(bytes4 selector, Checkpoint memory checkpoint) external;

    function setCheckpointActivation(bytes4 selector, Activation activation) external;

    function getCheckpoint(bytes4 selector) external view returns (uint192, uint16, uint16, Activation, bool);

    function attestedCall(Attestation calldata attestation, bytes calldata attestationSignature, bytes calldata data)
        external
        returns (bytes memory);
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/IAttesterInfo.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

interface IAttesterInfo {
    event AttesterControllerUpdated(bytes32 indexed attesterControllerId);

    function getAttesterControllerId() external view returns (bytes32);
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/ISecurityValidator.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

import "./Attestation.sol";

interface ISecurityValidator {
    function hashAttestation(Attestation calldata attestation) external view returns (bytes32);
    function getCurrentAttester() external view returns (address);
    function validateFinalState() external view;
    function executionHashFrom(bytes32 checkpointHash, address caller, bytes32 executionHash)
        external
        pure
        returns (bytes32);

    function storeAttestation(Attestation calldata attestation, bytes calldata attestationSignature) external;
    function storeAttestationForOrigin(
        Attestation calldata attestation,
        bytes calldata attestationSignature,
        address origin
    ) external;
    function saveAttestation(Attestation calldata attestation, bytes calldata attestationSignature) external;

    function executeCheckpoint(bytes32 checkpointHash) external returns (bytes32);
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/ICheckpointHook.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

/**
 * @notice External checkpoint activation values to enforce on the firewall when the firewall
 * calls the configured checkpoint hook contract.
 */
enum HookResult {
    Inconclusive,
    ForceActivation,
    ForceDeactivation
}

/**
 * @notice An interface for a custom contract implement and point the firewall to. This allows
 * building custom external logic that enforces what the firewall should think about an executing
 * checkpoint which will require an attestation. For example, by using this, a checkpoint can be
 * force activated or deactivated based on the caller. Returning HookResult.Inconclusive lets
 * the firewall fall back to its own configuration and logic to execute a checkpoint.
 */
interface ICheckpointHook {
    /**
     * @notice Called by a firewall when the address is configured in settings and the checkpoint
     * is based on a hash of the call data.
     * @param caller The caller observed and reported by the firewall.
     * @param selector The function selector which the checkpoint is configured for.
     */
    function handleCheckpoint(address caller, bytes4 selector) external view returns (HookResult);
    /**
     * @notice Called by a firewall when the address is configured in settings and the checkpoint
     * is based on a reference number selected from the call data. The difference from handleCheckpoint()
     * is the ability to reason about
     * @param caller The caller observed and reported by the firewall.
     * @param selector The function selector which the checkpoint is configured for.
     * @param ref The reference value which can normally be compared to a threshold value. The firewall
     * implementations use this value when deciding whether a checkpoint should activate and this hook
     * function can help add custom reasoning.
     */
    function handleCheckpointWithRef(address caller, bytes4 selector, uint256 ref) external view returns (HookResult);
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/IFirewallAccess.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See license at: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE-GPLv3.md

pragma solidity ^0.8.25;

interface IFirewallAccess {
    function isFirewallAdmin(address caller) external view returns (bool);
    function isProtocolAdmin(address caller) external view returns (bool);
    function isCheckpointManager(address caller) external view returns (bool);
    function isLogicUpgrader(address caller) external view returns (bool);
    function isCheckpointExecutor(address caller) external view returns (bool);
    function isAttesterManager(address caller) external view returns (bool);
    function isTrustedAttester(address caller) external view returns (bool);
}
"
    },
    "lib/forta-firewall-contracts/src/interfaces/ITrustedAttesters.sol": {
      "content": "// SPDX-License-Identifier: GNU General Public License Version 3
// See Forta Network License: https://github.com/forta-network/forta-firewall-contracts/blob/master/LICENSE.md

pragma solidity ^0.8.25;

interface ITrustedAttesters {
    function isTrustedAttester(address caller) external view returns (bool);
}
"
    },
    "lib/openzeppelin-contracts/contracts/utils/math/Math.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(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 towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since

Tags:
Multisig, Upgradeable, Multi-Signature, Factory|addr:0x99c4044574123f8657bc221bd269ca59864a0e45|verified:true|block:23422093|tx:0x7f7ac852a74a1d6960e20f2c8d1ababce25b694a9bdd7b5fca2eaff7b48933c9|first_check:1758717616

Submitted on: 2025-09-24 14:40:20

Comments

Log in to comment.

No comments yet.