Skip to content
Verified contractExactApache-2.0

DaoCollateral

Address0xdfbef524f172df7e37ccbe56e97ec5f8ce3c0c92
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.20

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.20+commit.a1b79de6
Language
solidity
Optimization
Yes, 200 runs
EVM version
shanghai
License
Apache-2.0
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
20,374,350
Creation transaction
0x2fc3ee8105…6c8ec37d4d

33 files

src/daoCollateral/DaoCollateral.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {SafeERC20} from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "openzeppelin-contracts/token/ERC20/IERC20.sol";
import {EIP712Upgradeable} from
    "openzeppelin-contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import {IERC20Permit} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SignatureChecker} from "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC20Permit} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Permit.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {ReentrancyGuardUpgradeable} from
    "openzeppelin-contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {IERC20Permit} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Permit.sol";
import {PausableUpgradeable} from "openzeppelin-contracts-upgradeable/utils/PausableUpgradeable.sol";
import {Initializable} from "openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";
import {NoncesUpgradeable} from "src/utils/NoncesUpgradeable.sol";

import {IRegistryAccess} from "src/interfaces/registry/IRegistryAccess.sol";
import {IUsd0} from "src/interfaces/token/IUsd0.sol";
import {IRegistryContract} from "src/interfaces/registry/IRegistryContract.sol";
import {ITokenMapping} from "src/interfaces/tokenManager/ITokenMapping.sol";
import {IOracle} from "src/interfaces/oracles/IOracle.sol";
import {IDaoCollateral, Approval, Intent} from "src/interfaces/IDaoCollateral.sol";
import {CheckAccessControl} from "src/utils/CheckAccessControl.sol";
import {Normalize} from "src/utils/normalize.sol";
import {ISwapperEngine} from "src/interfaces/ISwapperEngine.sol";
import {
    SCALAR_ONE,
    DEFAULT_ADMIN_ROLE,
    MAX_REDEEM_FEE,
    SCALAR_TEN_KWEI,
    CONTRACT_REGISTRY_ACCESS,
    CONTRACT_TOKEN_MAPPING,
    CONTRACT_ORACLE,
    CONTRACT_TREASURY,
    CONTRACT_USD0,
    CONTRACT_SWAPPER_ENGINE,
    INTENT_TYPE_HASH,
    INTENT_MATCHING_ROLE,
    NONCE_THRESHOLD_SETTER_ROLE
} from "src/constants.sol";

import {
    NullContract,
    InvalidToken,
    AmountIsZero,
    AmountTooLow,
    AmountTooBig,
    ApprovalFailed,
    RedeemMustNotBePaused,
    RedeemMustBePaused,
    SwapMustNotBePaused,
    SwapMustBePaused,
    SameValue,
    CBRIsTooHigh,
    CBRIsNull,
    RedeemFeeTooBig,
    InvalidSigner,
    InvalidDeadline,
    ExpiredSignature,
    NoOrdersIdsProvided,
    InvalidOrderAmount
} from "src/errors.sol";

/// @title   DaoCollateral Contract
/// @notice  Manages the swapping of collateral tokens for stablecoins, with functionalities for swap (direct mint) and redeeming tokens
/// @dev     Provides mechanisms for token swap operations, fee management, called Dao Collateral for historical reasons
/// @author  Usual Tech team
contract DaoCollateral is
    IDaoCollateral,
    Initializable,
    ReentrancyGuardUpgradeable,
    PausableUpgradeable,
    NoncesUpgradeable,
    EIP712Upgradeable
{
    using SafeERC20 for IERC20Metadata;
    using CheckAccessControl for IRegistryAccess;
    using Normalize for uint256;

    struct DaoCollateralStorageV0 {
        /// @notice Indicates if the redeem functionality is paused.
        bool _redeemPaused;
        /// @notice Indicates if the swap functionality is paused.
        bool _swapPaused;
        /// @notice Indicates if the Counter Bank Run (CBR) functionality is active.
        bool isCBROn;
        /// @notice The fee for redeeming tokens, in basis points.
        uint256 redeemFee;
        /// @notice The coefficient for calculating the returned rwaToken amount when CBR is active.
        uint256 cbrCoef;
        /// @notice The RegistryAccess contract instance for role checks.
        IRegistryAccess registryAccess;
        /// @notice The RegistryContract instance for contract interactions.
        IRegistryContract registryContract;
        /// @notice The TokenMapping contract instance for managing token mappings.
        ITokenMapping tokenMapping;
        /// @notice The USD0 token contract instance.
        IUsd0 usd0;
        /// @notice The Oracle contract instance for price feeds.
        IOracle oracle;
        /// @notice The address of treasury holding RWA tokens.
        address treasury;
        /// @notice The SwapperEngine contract instance for managing token swaps.
        ISwapperEngine swapperEngine;
        /// @notice the threshold for intents to be considered used in USD0 _getPriceAndDecimals
        uint256 nonceThreshold;
        /// @notice The mapping of the amount of the order taken that matches up to current nonce for each account
        mapping(address account => uint256) _orderAmountTaken;
    }

    // keccak256(abi.encode(uint256(keccak256("daoCollateral.storage.v0")) - 1)) & ~bytes32(uint256(0xff))
    // solhint-disable-next-line
    bytes32 public constant DaoCollateralStorageV0Location =
        0xb6b5806749b83e5a37ff64f3aa7a7ce3ac6e8a80a998e853c1d3efe545237c00;

    /*//////////////////////////////////////////////////////////////
                                Events
    //////////////////////////////////////////////////////////////*/

    /// @notice Emitted when tokens are swapped.
    event Swap(
        address indexed owner, address indexed tokenSwapped, uint256 amount, uint256 amountInUSD
    );

    /// @notice Emitted when tokens are redeemed.
    event Redeem(
        address indexed redeemer,
        address indexed rwaToken,
        uint256 amountRedeemed,
        uint256 returnedRwaAmount,
        uint256 stableFeeAmount
    );

    /// @notice Emitted when an intent is matched.
    event IntentMatched(
        address indexed owner,
        uint256 indexed nonce,
        address indexed tokenSwapped,
        uint256 amountInTokenDecimals,
        uint256 amountInUSD
    );

    /// @notice Emitted when an intent and associated nonce is consumed.
    event IntentConsumed(
        address indexed owner,
        uint256 indexed nonce,
        address indexed tokenSwapped,
        uint256 totalAmountInTokenDecimals
    );

    /// @notice Emitted when a nonce is invalidated.
    event NonceInvalidated(address indexed signer, uint256 indexed nonceInvalidated);

    /// @notice Emitted when redeem functionality is paused.
    event RedeemPaused();

    /// @notice Emitted when redeem functionality is unpaused.
    event RedeemUnPaused();

    /// @notice Emitted when swap functionality is paused.
    event SwapPaused();

    /// @notice Emitted when swap functionality is unpaused.
    event SwapUnPaused();

    /// @notice Emitted when the Counter Bank Run (CBR) mechanism is activated.
    /// @param cbrCoef The Counter Bank Run (CBR) coefficient.
    event CBRActivated(uint256 cbrCoef);

    /// @notice Emitted when the Counter Bank Run (CBR) mechanism is deactivated.
    event CBRDeactivated();

    /// @notice Emitted when the redeem fee is updated.
    /// @param redeemFee The new redeem fee.
    event RedeemFeeUpdated(uint256 redeemFee);

    /// @notice Emitted when the nonce threshold is set.
    event NonceThresholdSet(uint256 newThreshold);

    /*//////////////////////////////////////////////////////////////
                                Modifiers
    //////////////////////////////////////////////////////////////*/

    /// @notice Ensures the function is called only when the redeem is not paused.
    modifier whenRedeemNotPaused() {
        _requireRedeemNotPaused();
        _;
    }

    /// @notice Ensures the function is called only when the redeem is paused.
    modifier whenRedeemPaused() {
        _requireRedeemPaused();
        _;
    }

    /// @notice Ensures the function is called only when the swap is not paused.
    modifier whenSwapNotPaused() {
        _requireSwapNotPaused();
        _;
    }

    /// @notice Ensures the function is called only when the swap is paused.
    modifier whenSwapPaused() {
        _requireSwapPaused();
        _;
    }

    /// @notice  _requireRedeemNotPaused method will check if the redeem is not paused
    /// @dev Throws if the contract is paused.
    function _requireRedeemNotPaused() internal view virtual {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if ($._redeemPaused) {
            revert RedeemMustNotBePaused();
        }
    }

    /// @notice  _requireRedeemPaused method will check if the redeem is paused
    /// @dev Throws if the contract is not paused.
    function _requireRedeemPaused() internal view virtual {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if (!$._redeemPaused) {
            revert RedeemMustBePaused();
        }
    }

    /// @notice  _requireSwapNotPaused method will check if the redeem is not paused
    /// @dev Throws if the contract is paused.

    function _requireSwapNotPaused() internal view virtual {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if ($._swapPaused) {
            revert SwapMustNotBePaused();
        }
    }

    /// @notice  _requireSwapPaused method will check if the redeem is paused
    /// @dev Throws if the contract is not paused.
    function _requireSwapPaused() internal view virtual {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if (!$._swapPaused) {
            revert SwapMustBePaused();
        }
    }

    /// @notice Ensures the caller is authorized as part of the Usual Tech team.
    function _requireOnlyAdmin() internal view {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.registryAccess.onlyMatchingRole(DEFAULT_ADMIN_ROLE);
    }

    /*//////////////////////////////////////////////////////////////
                             Constructor
    //////////////////////////////////////////////////////////////*/

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    /// @notice Returns the storage struct of the contract.
    /// @return $ The pointer to the storage struct of the contract.
    function _daoCollateralStorageV0() internal pure returns (DaoCollateralStorageV0 storage $) {
        bytes32 position = DaoCollateralStorageV0Location;
        // solhint-disable-next-line no-inline-assembly
        assembly {
            $.slot := position
        }
    }

    /// @notice Initializes the DaoCollateral contract with registry information and initial configuration.
    /// @param _registryContract The address of the registry contract.
    /// @param _redeemFee The initial redeem fee, in basis points.
    function initialize(address _registryContract, uint256 _redeemFee) public initializer {
        // can't have a redeem fee greater than 25%
        if (_redeemFee > MAX_REDEEM_FEE) {
            revert RedeemFeeTooBig();
        }

        if (_registryContract == address(0)) {
            revert NullContract();
        }

        __EIP712_init_unchained("DaoCollateral", "1");
        __Nonces_init_unchained();
        __Pausable_init_unchained();
        __ReentrancyGuard_init_unchained();

        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.redeemFee = _redeemFee;

        IRegistryContract registryContract = IRegistryContract(_registryContract);
        $.registryAccess = IRegistryAccess(registryContract.getContract(CONTRACT_REGISTRY_ACCESS));

        $.treasury = address(registryContract.getContract(CONTRACT_TREASURY));
        $.tokenMapping = ITokenMapping(registryContract.getContract(CONTRACT_TOKEN_MAPPING));
        $.usd0 = IUsd0(registryContract.getContract(CONTRACT_USD0));

        $.oracle = IOracle(registryContract.getContract(CONTRACT_ORACLE));

        $.swapperEngine = ISwapperEngine(registryContract.getContract(CONTRACT_SWAPPER_ENGINE));
    }

    /// @notice Initializes the DaoCollateral contract with registry information and update configuration.
    /// @param _registryContract The address of the registry contract.
    /* cspell:disable-next-line */
    function initializeV1(address _registryContract) public reinitializer(2) {
        if (_registryContract == address(0)) {
            revert NullContract();
        }

        __EIP712_init_unchained("DaoCollateral", "1");
        __Nonces_init_unchained();

        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.registryContract = IRegistryContract(_registryContract);
        $.swapperEngine = ISwapperEngine(
            IRegistryContract(_registryContract).getContract(CONTRACT_SWAPPER_ENGINE)
        );
    }

    /*//////////////////////////////////////////////////////////////
                               Setters
    //////////////////////////////////////////////////////////////*/

    /// @notice Activates the Counter Bank Run (CBR) mechanism.
    /// @dev Enables the CBR
    /// @param coefficient the CBR coefficient to activate
    function activateCBR(uint256 coefficient) external {
        // we should revert if the coef is greater than 1
        if (coefficient > SCALAR_ONE) {
            revert CBRIsTooHigh();
        } else if (coefficient == 0) {
            revert CBRIsNull();
        }
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.isCBROn = true;
        $._swapPaused = true;
        $.cbrCoef = coefficient;
        emit CBRActivated($.cbrCoef);
        emit SwapPaused();
    }

    /// @notice Deactivates the Counter Bank Run (CBR) mechanism.
    /// @dev Disables the CBR functionality.
    function deactivateCBR() external {
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if ($.isCBROn == false) revert SameValue();
        $.isCBROn = false;
        emit CBRDeactivated();
    }

    /// @notice Sets the redeem fee.
    /// @dev Updates the fee for redeeming tokens, in basis points.
    /// @param _redeemFee The new redeem fee to set.
    function setRedeemFee(uint256 _redeemFee) external {
        if (_redeemFee > MAX_REDEEM_FEE) revert RedeemFeeTooBig();
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if ($.redeemFee == _redeemFee) revert SameValue();
        $.redeemFee = _redeemFee;
        emit RedeemFeeUpdated(_redeemFee);
    }

    /// @notice Pauses the redeem functionality.
    /// @dev Triggers the stopped state, preventing redeem operations.
    function pauseRedeem() external whenRedeemNotPaused {
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $._redeemPaused = true;
        emit RedeemPaused();
    }

    /// @notice Unpauses the redeem functionality.
    /// @dev Returns to normal state, allowing redeem operations.
    function unpauseRedeem() external whenRedeemPaused {
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $._redeemPaused = false;
        emit RedeemUnPaused();
    }

    /// @notice Pauses the swap functionality.
    /// @dev Triggers the stopped state, preventing swap operations.
    function pauseSwap() external whenSwapNotPaused {
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $._swapPaused = true;
        emit SwapPaused();
    }

    /// @notice Unpauses the swap functionality.
    /// @dev Returns to normal state, allowing swap operations.
    function unpauseSwap() external whenSwapPaused {
        _requireOnlyAdmin();
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $._swapPaused = false;
        emit SwapUnPaused();
    }

    /// @notice Pauses the contract.
    /// @dev Can be called by the DAO to pause all contract operations.
    function pause() external {
        _requireOnlyAdmin();
        _pause();
    }

    /// @notice Unpauses the contract.
    /// @dev Can be called by the DAO to unpause all contract operations.
    function unpause() external {
        _requireOnlyAdmin();
        _unpause();
    }

    /*//////////////////////////////////////////////////////////////
                               Internal
    //////////////////////////////////////////////////////////////*/

    /// @notice  _swapCheckAndGetUSDQuote method will check if the token is a USD0-supported RWA token and if the amount is not 0
    /// @dev     Function that do sanity check on the inputs
    /// @dev      and return the normalized USD quoted price of RWA tokens for the given amount
    /// @param   rwaToken  address of the token to swap MUST be a rwa token.
    /// @param   amountInToken  amount of RWA token to swap.
    /// @return  wadQuoteInUSD The quoted amount in USD with 18 decimals for the specified token and amount.
    function _swapCheckAndGetUSDQuote(address rwaToken, uint256 amountInToken)
        internal
        view
        returns (uint256 wadQuoteInUSD)
    {
        if (amountInToken == 0) {
            revert AmountIsZero();
        }

        // Amount can't be greater than uint128
        if (amountInToken > type(uint128).max) {
            revert AmountTooBig();
        }

        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if (!$.tokenMapping.isUsd0Collateral(rwaToken)) {
            revert InvalidToken();
        }
        wadQuoteInUSD = _getQuoteInUsd(amountInToken, rwaToken);
        //slither-disable-next-line incorrect-equality
        if (wadQuoteInUSD == 0) {
            revert AmountTooLow();
        }
    }

    /// @notice  transfers RWA Token And Mint Stable
    /// @dev     will transfer the RWA to the treasury and mints the corresponding stableAmount in USD0 stablecoin
    /// @param   rwaToken  address of the token to swap MUST be a RWA token.
    /// @param   amount  amount of rwa token to swap.
    /// @param   wadAmountInUSD amount of USD0 stablecoin to mint.
    function _transferRWATokenAndMintStable(
        address rwaToken,
        uint256 amount,
        uint256 wadAmountInUSD
    ) internal {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        // Should revert if balance is insufficient
        IERC20Metadata(address(rwaToken)).safeTransferFrom(msg.sender, $.treasury, amount);
        // Mint some stablecoin
        $.usd0.mint(msg.sender, wadAmountInUSD);
    }

    /// @dev call the oracle to get the price in USD
    /// @param rwaToken the collateral token address
    /// @return wadPriceInUSD the price in USD with 18 decimals
    /// @return decimals number of decimals of the token
    function _getPriceAndDecimals(address rwaToken)
        internal
        view
        returns (uint256 wadPriceInUSD, uint8 decimals)
    {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        wadPriceInUSD = uint256($.oracle.getPrice(rwaToken));
        decimals = uint8(IERC20Metadata(rwaToken).decimals());
    }

    /// @notice  get the price in USD of an `tokenAmount` of `rwaToken`
    /// @dev call the oracle to get the price in USD of `tokenAmount` of token with 18 decimals
    /// @param tokenAmount the amount of token to convert in USD with 18 decimals
    /// @param rwaToken the collateral token address
    /// @return wadAmountInUSD the amount in USD with 18 decimals
    function _getQuoteInUsd(uint256 tokenAmount, address rwaToken)
        internal
        view
        returns (uint256 wadAmountInUSD)
    {
        (uint256 wadPriceInUSD, uint8 decimals) = _getPriceAndDecimals(rwaToken);
        uint256 wadAmount = tokenAmount.tokenAmountToWad(decimals);
        wadAmountInUSD = Math.mulDiv(wadAmount, wadPriceInUSD, SCALAR_ONE, Math.Rounding.Floor);
    }

    /// @notice  get the amount of token for an amount of USD
    /// @dev call the oracle to get the price in USD of `amount` of token with 18 decimals
    /// @param wadStableAmount the amount of USD with 18 decimals
    /// @param rwaToken the RWA token address
    /// @return amountInToken the amount in token corresponding to the amount of USD
    function _getQuoteInToken(uint256 wadStableAmount, address rwaToken)
        internal
        view
        returns (uint256 amountInToken)
    {
        (uint256 wadPriceInUSD, uint8 decimals) = _getPriceAndDecimals(rwaToken);
        // will result in an amount with the same 'decimals' as the token
        amountInToken = wadStableAmount.wadTokenAmountForPrice(wadPriceInUSD, decimals);
    }

    /// @notice Calculates the returned amount of rwaToken give an amount of USD
    /// @dev return the amountInToken of token for `wadStableAmount` of USD at the current price
    /// @param wadStableAmount the amount of USD
    /// @param rwaToken the RWA token address
    /// @return amountInToken the amount of token that is worth `wadStableAmount` of USD with 18 decimals
    function _getTokenAmountForAmountInUSD(uint256 wadStableAmount, address rwaToken)
        internal
        view
        returns (uint256 amountInToken)
    {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        amountInToken = _getQuoteInToken(wadStableAmount, rwaToken);
        // if cbr is on we need to apply the coef to the rwa price
        // cbrCoef should be less than 1e18
        if ($.isCBROn) {
            amountInToken = Math.mulDiv(amountInToken, $.cbrCoef, SCALAR_ONE, Math.Rounding.Floor);
        }
    }

    /// @notice  _transferFee method will transfer the fee to the treasury
    /// @dev     Function that transfer the fee to the treasury
    /// @dev     The fee is calculated as a percentage of the amount of USD0 stablecoin to redeem
    /// @dev     The fee is minted to avoid transfer and allowance as the whole USD0 amount is burnt afterwards
    /// @param   usd0Amount  Amount of USD0 to transfer to treasury.
    /// @param   rwaToken  address of the token to swap should be a rwa token.
    /// @return stableFee The amount of stablecoin minted as fees for the treasury.
    function _transferFee(uint256 usd0Amount, address rwaToken)
        internal
        returns (uint256 stableFee)
    {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        stableFee = Math.mulDiv(usd0Amount, $.redeemFee, SCALAR_TEN_KWEI, Math.Rounding.Floor);
        uint8 tokenDecimals = IERC20Metadata(rwaToken).decimals();
        // if the token has less decimals than USD0 we need to normalize the fee
        if (tokenDecimals < 18) {
            // we scale down the fee to the token decimals
            // and we scale it up to 18 decimals
            stableFee = Normalize.tokenAmountToWad(
                Normalize.wadAmountToDecimals(stableFee, tokenDecimals), tokenDecimals
            );
        }
        // transfer the fee to the treasury
        if (stableFee > 0) {
            $.usd0.mint($.treasury, stableFee);
        }
    }

    /// @notice  _burnStableTokenAndTransferCollateral method will burn the stable token and transfer the collateral token
    /// @dev     Function that burns the stable token and transfer the collateral token
    /// @param   rwaToken  address of the token to swap should be a rwa token.
    /// @param   stableAmount  amount of token to swap.
    /// @param   stableFee  amount of fee in stablecoin.
    /// @return returnedCollateral The amount of collateral token returned.
    function _burnStableTokenAndTransferCollateral(
        address rwaToken,
        uint256 stableAmount,
        uint256 stableFee
    ) internal returns (uint256 returnedCollateral) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        // we burn the remaining stable token
        uint256 burnedStable = stableAmount - stableFee;
        // we burn all the stable token USD0
        $.usd0.burnFrom(msg.sender, stableAmount);

        // get the amount of collateral token for the amount of stablecoin burned by calling the oracle
        returnedCollateral = _getTokenAmountForAmountInUSD(burnedStable, rwaToken);
        if (returnedCollateral == 0) {
            revert AmountTooLow();
        }

        // we distribute the collateral token from the treasury to the user
        // slither-disable-next-line arbitrary-send-erc20
        IERC20Metadata(rwaToken).safeTransferFrom($.treasury, msg.sender, returnedCollateral);
    }

    /// @notice Swap RWA for USDC through offers on the SwapperContract
    /// @dev Takes USYC, mints USD0 and provides it to the Swapper Contract directly
    /// Sends USD0 to the offer's creator and sends USDC to the recipient
    /// @dev the recipient Address to receive the USDC is msg.sender
    /// @param caller Address of the caller (msg.sender or intent recipient)
    /// @param rwaToken Address of the RWA to swap for USDC
    /// @param amountInTokenDecimals Amount of the RWA to swap for USDC
    /// @param partialMatching flag to allow partial matching
    /// @param orderIdsToTake orderIds to be taken
    /// @param approval ERC20Permit approval data and signature of data
    /// @return matchedAmountInTokenDecimals The amount of RWA tokens which have been matched.
    /// @return matchedAmountInUSD           The net amount of USD0 tokens minted.
    // solhint-disable-next-line code-complexity
    function _swapRWAtoStbc(
        address caller,
        address rwaToken,
        uint256 amountInTokenDecimals,
        bool partialMatching,
        uint256[] calldata orderIdsToTake,
        Approval calldata approval
    ) internal returns (uint256 matchedAmountInTokenDecimals, uint256 matchedAmountInUSD) {
        if (amountInTokenDecimals == 0) {
            revert AmountIsZero();
        }
        if (amountInTokenDecimals > type(uint128).max) {
            revert AmountTooBig();
        }
        if (orderIdsToTake.length == 0) {
            revert NoOrdersIdsProvided();
        }
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        if (!$.tokenMapping.isUsd0Collateral(rwaToken)) {
            revert InvalidToken();
        }

        // Check if the approval isn't null, if it isn't, use it for the permit
        if (approval.deadline != 0 && approval.v != 0 && approval.r != 0 && approval.s != 0) {
            // Authorization transfer
            try IERC20Permit(rwaToken).permit( //NOTE: this will fail if permit already used but that's ok as long as there is enough allowance
                caller,
                address(this),
                type(uint256).max,
                approval.deadline,
                approval.v,
                approval.r,
                approval.s
            ) {} catch {} // solhint-disable-line no-empty-blocks
        }

        // Take the RWA token from the recipient
        IERC20Metadata(rwaToken).safeTransferFrom(caller, address(this), amountInTokenDecimals);
        // Get the price quote of the RWA token to mint USD0
        uint256 wadRwaQuoteInUSD = _getQuoteInUsd(amountInTokenDecimals, rwaToken);
        // Mint the corresponding amount of USD0 stablecoin
        $.usd0.mint(address(this), wadRwaQuoteInUSD);
        if (!IERC20($.usd0).approve(address($.swapperEngine), wadRwaQuoteInUSD)) {
            revert ApprovalFailed();
        }
        // Provide the USD0 to the SwapperEngine and receive USDC for the caller
        uint256 wadRwaNotTakenInUSD =
            $.swapperEngine.swapUsd0(caller, wadRwaQuoteInUSD, orderIdsToTake, partialMatching);

        // Burn any unmatched USD0 and return the RWA
        if (wadRwaNotTakenInUSD > 0) {
            if (!IERC20($.usd0).approve(address($.swapperEngine), 0)) {
                revert ApprovalFailed();
            }
            $.usd0.burnFrom(address(this), wadRwaNotTakenInUSD);

            // Get amount of RWA for the wadRwaNotTakenInUSD pricing
            uint256 rwaTokensToReturn = _getQuoteInToken(wadRwaNotTakenInUSD, rwaToken);

            // Transfer back the remaining RWA tokens to the recipient
            IERC20Metadata(rwaToken).safeTransfer(caller, rwaTokensToReturn);

            matchedAmountInTokenDecimals = amountInTokenDecimals - rwaTokensToReturn;
        } else {
            matchedAmountInTokenDecimals = amountInTokenDecimals;
        }

        // Send the matched RWA to the treasury
        IERC20Metadata(rwaToken).safeTransfer($.treasury, matchedAmountInTokenDecimals);

        matchedAmountInUSD = wadRwaQuoteInUSD - wadRwaNotTakenInUSD;
        emit Swap(caller, rwaToken, matchedAmountInTokenDecimals, matchedAmountInUSD);

        return (matchedAmountInTokenDecimals, matchedAmountInUSD);
    }

    /*//////////////////////////////////////////////////////////////
                               External
    //////////////////////////////////////////////////////////////*/

    /// @inheritdoc IDaoCollateral
    function swap(address rwaToken, uint256 amount, uint256 minAmountOut)
        public
        nonReentrant
        whenSwapNotPaused
        whenNotPaused
    {
        uint256 wadQuoteInUSD = _swapCheckAndGetUSDQuote(rwaToken, amount);
        // Check if the amount is greater than the minAmountOut
        if (wadQuoteInUSD < minAmountOut) {
            revert AmountTooLow();
        }
        _transferRWATokenAndMintStable(rwaToken, amount, wadQuoteInUSD);
        // Emit the event
        emit Swap(msg.sender, rwaToken, amount, wadQuoteInUSD);
    }

    /// @inheritdoc IDaoCollateral
    function swapWithPermit(
        address rwaToken,
        uint256 amount,
        uint256 minAmountOut,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external {
        // solhint-disable-next-line no-empty-blocks
        try IERC20Permit(rwaToken).permit(msg.sender, address(this), amount, deadline, v, r, s) {}
            catch {} // solhint-disable-line no-empty-blocks
        swap(rwaToken, amount, minAmountOut);
    }

    /// @inheritdoc IDaoCollateral
    function redeem(address rwaToken, uint256 amount, uint256 minAmountOut)
        external
        nonReentrant
        whenRedeemNotPaused
        whenNotPaused
    {
        // Amount can't be 0
        if (amount == 0) {
            revert AmountIsZero();
        }

        // check that rwaToken is a RWA token
        if (!_daoCollateralStorageV0().tokenMapping.isUsd0Collateral(rwaToken)) {
            revert InvalidToken();
        }
        uint256 stableFee = _transferFee(amount, rwaToken);
        uint256 returnedCollateral =
            _burnStableTokenAndTransferCollateral(rwaToken, amount, stableFee);
        // Check if the amount is greater than the minAmountOut
        if (returnedCollateral < minAmountOut) {
            revert AmountTooLow();
        }
        emit Redeem(msg.sender, rwaToken, amount, returnedCollateral, stableFee);
    }

    /// @inheritdoc IDaoCollateral
    function redeemDao(address rwaToken, uint256 amount) external nonReentrant {
        // Amount can't be 0
        if (amount == 0) {
            revert AmountIsZero();
        }

        _requireOnlyAdmin();
        // check that rwaToken is a RWA token
        if (!_daoCollateralStorageV0().tokenMapping.isUsd0Collateral(rwaToken)) {
            revert InvalidToken();
        }
        uint256 returnedCollateral = _burnStableTokenAndTransferCollateral(rwaToken, amount, 0);
        emit Redeem(msg.sender, rwaToken, amount, returnedCollateral, 0);
    }

    /// @inheritdoc IDaoCollateral
    function swapRWAtoStbc(
        address rwaToken,
        uint256 amountInTokenDecimals,
        bool partialMatching,
        uint256[] calldata orderIdsToTake,
        Approval calldata approval
    ) external nonReentrant whenNotPaused whenSwapNotPaused {
        _swapRWAtoStbc(
            msg.sender, rwaToken, amountInTokenDecimals, partialMatching, orderIdsToTake, approval
        );
    }

    /// @inheritdoc IDaoCollateral
    function invalidateNonce() external {
        uint256 nonceUsed = _useNonce(msg.sender);
        _daoCollateralStorageV0()._orderAmountTaken[msg.sender] = 0;
        emit NonceInvalidated(msg.sender, nonceUsed);
    }

    /// @inheritdoc IDaoCollateral
    function invalidateUpToNonce(uint256 newNonce) external {
        _invalidateUpToNonce(msg.sender, newNonce);
        _daoCollateralStorageV0()._orderAmountTaken[msg.sender] = 0;
        emit NonceInvalidated(msg.sender, newNonce - 1);
    }

    /// @inheritdoc IDaoCollateral
    function setNonceThreshold(uint256 threshold) external {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.registryAccess.onlyMatchingRole(NONCE_THRESHOLD_SETTER_ROLE);
        $.nonceThreshold = threshold;
        emit NonceThresholdSet(threshold);
    }

    /// @inheritdoc IDaoCollateral
    function nonceThreshold() external view returns (uint256) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $.nonceThreshold;
    }

    /// @notice Checks if an Intent is valid by verifying its signature and returns the remaining amount unmatched
    /// @dev Function should be called internally before any fields from intent are used in contract logic
    /// @param intent Intent data and signature of data
    /// @return remainingAmountUnmatched Amount left in the current intent for swap
    /// @return nonce The current nonce for this reusable intent
    function _isValidIntent(Intent calldata intent)
        internal
        virtual
        returns (uint256 remainingAmountUnmatched, uint256 nonce)
    {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        //if we increment the nonce this wont match so the user can cancel the order essentially
        uint256 currentOrderNonce = nonces(intent.recipient);
        // check the signature w/ nonce
        bytes32 structHash = keccak256(
            abi.encode(
                INTENT_TYPE_HASH,
                intent.recipient,
                intent.rwaToken,
                intent.amountInTokenDecimals,
                currentOrderNonce,
                intent.deadline
            )
        );

        bytes32 hash = _hashTypedDataV4(structHash);

        if (!SignatureChecker.isValidSignatureNow(intent.recipient, hash, intent.signature)) {
            revert InvalidSigner(intent.recipient);
        }

        if ($._orderAmountTaken[intent.recipient] > intent.amountInTokenDecimals) {
            revert InvalidOrderAmount(intent.recipient, intent.amountInTokenDecimals);
        }

        // return the amount left to be filled
        remainingAmountUnmatched =
            (intent.amountInTokenDecimals - $._orderAmountTaken[intent.recipient]);
        return (remainingAmountUnmatched, currentOrderNonce);
    }

    /// @notice Partially or fully consumes an amount of an intent
    /// @dev Function should be called internally after verifying the intent is valid
    /// @param amount The amount to consume from the remaining reusable intent
    /// @param intent Intent data and signature of data
    /// @return remainingAmountUnmatched Amount left in the current intent for swap
    function _useIntentAmount(uint256 amount, Intent memory intent)
        internal
        virtual
        returns (uint256 remainingAmountUnmatched)
    {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        // check that the amount they want to use is less than the remaining amount unmatched in the smart order
        remainingAmountUnmatched =
            (intent.amountInTokenDecimals - $._orderAmountTaken[intent.recipient]);

        if (amount > remainingAmountUnmatched) {
            revert InvalidOrderAmount(intent.recipient, amount);
        } else if ((remainingAmountUnmatched - amount) <= $.nonceThreshold) {
            emit IntentConsumed(
                intent.recipient,
                nonces(intent.recipient),
                intent.rwaToken,
                intent.amountInTokenDecimals
            );
            _useNonce(intent.recipient);
            //reset the intent amount taken for the next nonce
            $._orderAmountTaken[intent.recipient] = 0;
            return 0;
        } else {
            $._orderAmountTaken[intent.recipient] += amount;
        }

        remainingAmountUnmatched =
            intent.amountInTokenDecimals - $._orderAmountTaken[intent.recipient];
        return remainingAmountUnmatched;
    }

    function orderAmountTakenCurrentNonce(address owner) public view virtual returns (uint256) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $._orderAmountTaken[owner];
    }

    /// @inheritdoc IDaoCollateral
    function swapRWAtoStbcIntent(
        uint256[] calldata orderIdsToTake,
        Approval calldata approval,
        Intent calldata intent,
        bool partialMatching
    ) external nonReentrant whenNotPaused whenSwapNotPaused {
        if (block.timestamp > intent.deadline) {
            revert ExpiredSignature(intent.deadline);
        }
        if (approval.deadline != intent.deadline) {
            revert InvalidDeadline(approval.deadline, intent.deadline);
        }

        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        $.registryAccess.onlyMatchingRole(INTENT_MATCHING_ROLE);

        (uint256 remainingAmountUnmatched, uint256 nonce) = _isValidIntent(intent);
        //NOTE: if its a full match then we increment the nonce
        if (!partialMatching) {
            emit IntentConsumed(
                intent.recipient, nonce, intent.rwaToken, intent.amountInTokenDecimals
            );
            _useNonce(intent.recipient);
            $._orderAmountTaken[intent.recipient] = 0;
        }

        (uint256 matchedAmountInTokenDecimals, uint256 matchedAmountInUSD) = _swapRWAtoStbc(
            intent.recipient,
            intent.rwaToken,
            remainingAmountUnmatched,
            partialMatching,
            orderIdsToTake,
            approval
        );
        //NOTE: if it is a partial match then we deduct the matched amount from the remaining unmatched, if the intent is used up then increment the nonce
        if (partialMatching) {
            _useIntentAmount(matchedAmountInTokenDecimals, intent);
        }

        emit IntentMatched(
            intent.recipient,
            nonce,
            intent.rwaToken,
            matchedAmountInTokenDecimals,
            matchedAmountInUSD
        );
    }

    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
        return _domainSeparatorV4();
    }

    /// @inheritdoc IDaoCollateral

    function isCBROn() external view returns (bool) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $.isCBROn;
    }

    /// @notice Returns the cbrCoef value.
    function cbrCoef() public view returns (uint256) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $.cbrCoef;
    }

    /// @inheritdoc IDaoCollateral
    function redeemFee() public view returns (uint256) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $.redeemFee;
    }

    /// @inheritdoc IDaoCollateral
    function isRedeemPaused() public view returns (bool) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $._redeemPaused;
    }

    /// @inheritdoc IDaoCollateral
    function isSwapPaused() public view returns (bool) {
        DaoCollateralStorageV0 storage $ = _daoCollateralStorageV0();
        return $._swapPaused;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol

// 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-upgradeable/contracts/utils/ContextUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        PausableStorage storage $ = _getPausableStorage();
        return $._paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = false;
        emit Unpaused(_msgSender());
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        $._status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 */
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @custom:storage-location erc7201:openzeppelin.storage.EIP712
    struct EIP712Storage {
        /// @custom:oz-renamed-from _HASHED_NAME
        bytes32 _hashedName;
        /// @custom:oz-renamed-from _HASHED_VERSION
        bytes32 _hashedVersion;

        string _name;
        string _version;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;

    function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
        assembly {
            $.slot := EIP712StorageLocation
        }
    }

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
        __EIP712_init_unchained(name, version);
    }

    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
        EIP712Storage storage $ = _getEIP712Storage();
        $._name = name;
        $._version = version;

        // Reset prior values in storage if upgrading
        $._hashedName = 0;
        $._hashedVersion = 0;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        EIP712Storage storage $ = _getEIP712Storage();
        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
        // and the EIP712 domain is not reliable, as it will be missing name and version.
        require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");

        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Name() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._name;
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Version() internal view virtual returns (string memory) {
        EIP712Storage storage $ = _getEIP712Storage();
        return $._version;
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
     */
    function _EIP712NameHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory name = _EIP712Name();
        if (bytes(name).length > 0) {
            return keccak256(bytes(name));
        } else {
            // If the name is empty, the contract may have been upgraded without initializing the new storage.
            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
            bytes32 hashedName = $._hashedName;
            if (hashedName != 0) {
                return hashedName;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
     */
    function _EIP712VersionHash() internal view returns (bytes32) {
        EIP712Storage storage $ = _getEIP712Storage();
        string memory version = _EIP712Version();
        if (bytes(version).length > 0) {
            return keccak256(bytes(version));
        } else {
            // If the version is empty, the contract may have been upgraded without initializing the new storage.
            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
            bytes32 hashedVersion = $._hashedVersion;
            if (hashedVersion != 0) {
                return hashedVersion;
            } else {
                return keccak256("");
            }
        }
    }
}

lib/openzeppelin-contracts/contracts/access/IAccessControl.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

lib/openzeppelin-contracts/contracts/access/extensions/IAccessControlDefaultAdminRules.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlDefaultAdminRules.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection.
 */
interface IAccessControlDefaultAdminRules is IAccessControl {
    /**
     * @dev The new default admin is not a valid default admin.
     */
    error AccessControlInvalidDefaultAdmin(address defaultAdmin);

    /**
     * @dev At least one of the following rules was violated:
     *
     * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself.
     * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time.
     * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps.
     */
    error AccessControlEnforcedDefaultAdminRules();

    /**
     * @dev The delay for transferring the default admin delay is enforced and
     * the operation must wait until `schedule`.
     *
     * NOTE: `schedule` can be 0 indicating there's no transfer scheduled.
     */
    error AccessControlEnforcedDefaultAdminDelay(uint48 schedule);

    /**
     * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next
     * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule`
     * passes.
     */
    event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule.
     */
    event DefaultAdminTransferCanceled();

    /**
     * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next
     * delay to be applied between default admin transfer after `effectSchedule` has passed.
     */
    event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass.
     */
    event DefaultAdminDelayChangeCanceled();

    /**
     * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder.
     */
    function defaultAdmin() external view returns (address);

    /**
     * @dev Returns a tuple of a `newAdmin` and an accept schedule.
     *
     * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role
     * by calling {acceptDefaultAdminTransfer}, completing the role transfer.
     *
     * A zero value only in `acceptSchedule` indicates no pending admin transfer.
     *
     * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced.
     */
    function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule);

    /**
     * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started.
     *
     * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set
     * the acceptance schedule.
     *
     * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this
     * function returns the new delay. See {changeDefaultAdminDelay}.
     */
    function defaultAdminDelay() external view returns (uint48);

    /**
     * @dev Returns a tuple of `newDelay` and an effect schedule.
     *
     * After the `schedule` passes, the `newDelay` will get into effect immediately for every
     * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}.
     *
     * A zero value only in `effectSchedule` indicates no pending delay change.
     *
     * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay}
     * will be zero after the effect schedule.
     */
    function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule);

    /**
     * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance
     * after the current timestamp plus a {defaultAdminDelay}.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminRoleChangeStarted event.
     */
    function beginDefaultAdminTransfer(address newAdmin) external;

    /**
     * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminTransferCanceled event.
     */
    function cancelDefaultAdminTransfer() external;

    /**
     * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}.
     *
     * After calling the function:
     *
     * - `DEFAULT_ADMIN_ROLE` should be granted to the caller.
     * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder.
     * - {pendingDefaultAdmin} should be reset to zero values.
     *
     * Requirements:
     *
     * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`.
     * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed.
     */
    function acceptDefaultAdminTransfer() external;

    /**
     * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting
     * into effect after the current timestamp plus a {defaultAdminDelay}.
     *
     * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this
     * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay}
     * set before calling.
     *
     * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then
     * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin}
     * complete transfer (including acceptance).
     *
     * The schedule is designed for two scenarios:
     *
     * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by
     * {defaultAdminDelayIncreaseWait}.
     * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`.
     *
     * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event.
     */
    function changeDefaultAdminDelay(uint48 newDelay) external;

    /**
     * @dev Cancels a scheduled {defaultAdminDelay} change.
     *
     * Requirements:
     *
     * - Only can be called by the current {defaultAdmin}.
     *
     * May emit a DefaultAdminDelayChangeCanceled event.
     */
    function rollbackDefaultAdminDelay() external;

    /**
     * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay})
     * to take effect. Default to 5 days.
     *
     * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with
     * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds)
     * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can
     * be overrode for a custom {defaultAdminDelay} increase scheduling.
     *
     * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise,
     * there's a risk of setting a high new delay that goes into effect almost immediately without the
     * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds).
     */
    function defaultAdminDelayIncreaseWait() external view returns (uint48);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1271.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with _data
     */
    function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.20;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev An operation with an ERC20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data);
        if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)

pragma solidity ^0.8.20;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error AddressInsufficientBalance(address account);

    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

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

    /**
     * @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 AddressInsufficientBalance(address(this));
        }

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

    /**
     * @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
     * {FailedInnerCall} 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 AddressInsufficientBalance(address(this));
        }
        (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 {FailedInnerCall}) 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 {FailedInnerCall} 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 {FailedInnerCall}.
     */
    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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert FailedInnerCall();
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";

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

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @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), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(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) {
        uint256 localValue = value;
        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] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        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 bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError, bytes32) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/SignatureChecker.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/SignatureChecker.sol)

pragma solidity ^0.8.20;

import {ECDSA} from "./ECDSA.sol";
import {IERC1271} from "../../interfaces/IERC1271.sol";

/**
 * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA
 * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like
 * Argent and Safe Wallet (previously Gnosis Safe).
 */
library SignatureChecker {
    /**
     * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
     * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {
        (address recovered, ECDSA.RecoverError error, ) = ECDSA.tryRecover(hash, signature);
        return
            (error == ECDSA.RecoverError.NoError && recovered == signer) ||
            isValidERC1271SignatureNow(signer, hash, signature);
    }

    /**
     * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
     * against the signer smart contract using ERC1271.
     *
     * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
     * change through time. It could return true at block N and false at block N+1 (or the opposite).
     */
    function isValidERC1271SignatureNow(
        address signer,
        bytes32 hash,
        bytes memory signature
    ) internal view returns (bool) {
        (bool success, bytes memory result) = signer.staticcall(
            abi.encodeCall(IERC1271.isValidSignature, (hash, signature))
        );
        return (success &&
            result.length >= 32 &&
            abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    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 overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

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

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        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 division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

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

    /**
     * @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 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.
            return a / b;
        }

        // (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 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                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.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

            ///////////////////////////////////////////////
            // 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.

            uint256 twos = denominator & (0 - denominator);
            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 (unsignedRoundsUp(rounding) && 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
     * towards zero.
     *
     * 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @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);
        }
    }
}

src/constants.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

bytes32 constant ADMIN = keccak256("ADMIN");
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
bytes32 constant DAO_COLLATERAL = keccak256("DAO_COLLATERAL_CONTRACT");
bytes32 constant USD0_MINT = keccak256("USD0_MINT");
bytes32 constant USD0_BURN = keccak256("USD0_BURN");
bytes32 constant USUAL_MINT = keccak256("USUAL_MINT");
bytes32 constant USUAL_BURN = keccak256("USUAL_BURN");
bytes32 constant INTENT_MATCHING_ROLE = keccak256("INTENT_MATCHING_ROLE");
bytes32 constant NONCE_THRESHOLD_SETTER_ROLE = keccak256("NONCE_THRESHOLD_SETTER_ROLE");
bytes32 constant PEG_MAINTAINER_ROLE = keccak256("PEG_MAINTAINER_ROLE");
bytes32 constant SWAPPER_ENGINE = keccak256("SWAPPER_ENGINE");
bytes32 constant INTENT_TYPE_HASH = keccak256(
    "SwapIntent(address recipient,address rwaToken,uint256 amountInTokenDecimals,uint256 nonce,uint256 deadline)"
);
/* Contracts */

bytes32 constant CONTRACT_REGISTRY_ACCESS = keccak256("CONTRACT_REGISTRY_ACCESS");
bytes32 constant CONTRACT_DAO_COLLATERAL = keccak256("CONTRACT_DAO_COLLATERAL");
bytes32 constant CONTRACT_USD0PP = keccak256("CONTRACT_USD0PP");
bytes32 constant CONTRACT_TOKEN_MAPPING = keccak256("CONTRACT_TOKEN_MAPPING");
bytes32 constant CONTRACT_ORACLE = keccak256("CONTRACT_ORACLE");
bytes32 constant CONTRACT_ORACLE_USUAL = keccak256("CONTRACT_ORACLE_USUAL");
bytes32 constant CONTRACT_DATA_PUBLISHER = keccak256("CONTRACT_DATA_PUBLISHER");
bytes32 constant CONTRACT_TREASURY = keccak256("CONTRACT_TREASURY");
bytes32 constant CONTRACT_SWAPPER_ENGINE = keccak256("CONTRACT_SWAPPER_ENGINE");
/* Contract tokens */
bytes32 constant CONTRACT_USD0 = keccak256("CONTRACT_USD0");
bytes32 constant CONTRACT_USUAL = keccak256("CONTRACT_USUAL");
bytes32 constant CONTRACT_USDC = keccak256("CONTRACT_USDC");
/* Constants */
uint256 constant SCALAR_ONE = 1e18;
uint256 constant SCALAR_TEN_KWEI = 10_000;
uint256 constant MAX_REDEEM_FEE = 2500;
uint256 constant MINIMUM_USDC_PROVIDED = 100e6; //minimum of 100 USDC deposit;
// we take 12sec as the average block time
// 1 year = 3600sec * 24 hours * 365 days * 4 years  = 126144000 + 1 day // adding a leap day
uint256 constant BOND_DURATION_FOUR_YEAR = 126_230_400; //including a leap day;
uint256 constant BOND_START_DATE = 1_719_489_600; // Thu Jun 27 2024 12:00:00 GMT+0000
uint256 constant BASIS_POINT_BASE = 10_000;
uint64 constant ONE_WEEK = 604_800;
uint256 constant ONE_USDC = 1e6;

/* Token Addresses */

address constant USYC = 0x136471a34f6ef19fE571EFFC1CA711fdb8E49f2b;

/*
 * The maximum relative price difference between two oracle responses allowed in order for the PriceFeed
 * to return to using the Oracle oracle. 18-digit precision.
 */

uint256 constant INITIAL_MAX_DEPEG_THRESHOLD = 100;

/* Maximum number of RWA tokens that can be associated with USD0 */
uint256 constant MAX_RWA_COUNT = 10;

/* Curvepool Addresses */
address constant CURVE_POOL_USD0_USD0PP = 0x1d08E7adC263CfC70b1BaBe6dC5Bb339c16Eec52;
int128 constant CURVE_POOL_USD0_USD0PP_INTEGER_FOR_USD0 = 0;
int128 constant CURVE_POOL_USD0_USD0PP_INTEGER_FOR_USD0PP = 1;

src/errors.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

error AlreadyClaimed();
error AlreadyWhitelisted();
error AmountTooBig();
error AmountTooLow();
error AmountIsZero();
error Blacklisted();

error Empty();
error ExpiredSignature(uint256 deadline);
error SameValue();

error Invalid();
error InvalidToken();
error InvalidName();
error InvalidSigner(address owner);
error InvalidDeadline(uint256 approvalDeadline, uint256 intentDeadline);
error NoOrdersIdsProvided();
error InvalidSymbol();

error LockedOffer();

error NotAuthorized();
error NotClaimableYet();
error NullAddress();
error NullContract();

error OracleNotWorkingNotCurrent();
error OracleNotInitialized();
error OutOfBounds();
error InvalidTimeout();

error RedeemMustNotBePaused();
error RedeemMustBePaused();
error SwapMustNotBePaused();
error SwapMustBePaused();

error StablecoinDepeg();
error DepegThresholdTooHigh();

error TokenNotWhitelist();

error BondNotStarted();
error BondFinished();
error BondNotFinished();

error BeginInPast();

error CBRIsTooHigh();
error CBRIsNull();

error RedeemFeeTooBig();
error CancelFeeTooBig();
error MinterRewardTooBig();
error CollateralProviderRewardTooBig();
error DistributionRatioInvalid();
error TooManyRWA();
error FailingTransfer();

error InsufficientUSD0Balance();
error USDCAmountNotFullyMatched();
error OrderNotActive();
error NotRequester();
error InsufficientUSD0Allowance();
error ApprovalFailed();

error AmountExceedBacking();
error InvalidOrderAmount(address account, uint256 amount);
error PARNotRequired();
error PARNotSuccessful();
error PARUSD0InputExceedsBalance();

src/interfaces/IDaoCollateral.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

struct Approval {
    uint256 deadline;
    uint8 v; // Changes at each new signature because of ERC20 Permit nonce
    bytes32 r;
    bytes32 s;
}

struct Intent {
    address recipient;
    address rwaToken;
    uint256 amountInTokenDecimals;
    uint256 deadline;
    bytes signature;
}

interface IDaoCollateral {
    /// @notice  swap method
    /// @dev     Function that enable you to swap your rwaToken for stablecoin
    /// @dev     Will exchange RWA (rwaToken) for USD0 (stableToken)
    /// @param   rwaToken  address of the token to swap
    /// @param   amount  amount of rwaToken to swap
    /// @param   minAmountOut minimum amount of stableToken to receive
    function swap(address rwaToken, uint256 amount, uint256 minAmountOut) external;

    /// @notice  swap method with permit
    /// @dev     Function that enable you to swap your rwaToken for stablecoin with permit
    /// @dev     Will exchange RWA (rwaToken) for USD0 (stableToken)
    /// @param   rwaToken  address of the token to swap
    /// @param   amount  amount of rwaToken to swap
    /// @param   deadline The deadline for the permit
    /// @param   v The v value for the permit
    /// @param   r The r value for the permit
    /// @param   s The s value for the permit
    function swapWithPermit(
        address rwaToken,
        uint256 amount,
        uint256 minAmountOut,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /// @notice  redeem method
    /// @dev     Function that enable you to redeem your stable token for rwaToken
    /// @dev     Will exchange USD0 (stableToken) for RWA (rwaToken)
    /// @param   rwaToken address of the token that will be sent to the you
    /// @param   amount  amount of stableToken to redeem
    /// @param   minAmountOut minimum amount of rwaToken to receive
    function redeem(address rwaToken, uint256 amount, uint256 minAmountOut) external;

    /// @notice Swap RWA for USDC through offers on the SwapperContract
    /// @dev Takes USYC, mints USD0 and provides it to the Swapper Contract directly
    /// Sends USD0 to the offer's creator and sends USDC to the recipient
    /// @dev the recipient Address to receive the USDC is msg.sender
    /// @param rwaToken Address of the RWA to swap for USDC
    /// @param amountInTokenDecimals Address of the RWA to swap for USDC
    /// @param orderIdsToTake orderIds to be taken
    /// @param approval ERC20Permit approval data and signature of data
    /// @param partialMatching flag to allow partial matching
    function swapRWAtoStbc(
        address rwaToken,
        uint256 amountInTokenDecimals,
        bool partialMatching,
        uint256[] calldata orderIdsToTake,
        Approval calldata approval
    ) external;

    /// @notice Swap RWA for USDC through offers on the SwapperContract
    /// @dev Takes USYC, mints USD0 and provides it to the Swapper Contract directly
    /// Sends USD0 to the offer's creator and sends USDC to the recipient
    /// @dev the recipient Address to receive the USDC is the offer's creator
    /// @param orderIdsToTake orderIds to be taken
    /// @param approval ERC20Permit approval data and signature of data
    /// @param intent Intent data and signature of data
    /// @param partialMatching flag to allow partial matching
    function swapRWAtoStbcIntent(
        uint256[] calldata orderIdsToTake,
        Approval calldata approval,
        Intent calldata intent,
        bool partialMatching
    ) external;

    // * Getter functions

    /// @notice get the redeem fee percentage
    /// @return the fee value
    function redeemFee() external view returns (uint256);

    /// @notice check if the CBR (Counter Bank Run) is activated
    /// @dev flag indicate the status of the CBR (see documentation for more details)
    /// @return the status of the CBR
    function isCBROn() external view returns (bool);

    /// @notice get the status of pause for the redeem function
    /// @return the status of the pause
    function isRedeemPaused() external view returns (bool);

    /// @notice get the status of pause for the swap function
    /// @return the status of the pause
    function isSwapPaused() external view returns (bool);

    // * Restricted functions

    /// @notice  redeem method for DAO
    /// @dev     Function that enables DAO to redeem stableToken for rwaToken
    /// @dev     Will exchange USD0 (stableToken) for RWA (rwaToken)
    /// @param   rwaToken address of the token that will be sent to the you
    /// @param   amount  amount of stableToken to redeem
    function redeemDao(address rwaToken, uint256 amount) external;

    /// @notice Invalidates the current nonce for the message sender
    /// @dev This function increments the nonce counter for the msg.sender and emits a NonceInvalidated event
    function invalidateNonce() external;

    /// @notice Invalidates all nonces up to a certain value for the message sender
    /// @dev This function increments the nonce counter for the msg.sender and emits a NonceInvalidated event
    function invalidateUpToNonce(uint256 newNonce) external;

    /// @notice Set the lower bound for the intent nonce to be considered consumed
    /// @dev An intent with an amount less than this threshold after a partial match will be invalidated by incrementing the nonce
    /// @dev emits a NonceThresholdSet event
    /// @param threshold The new threshold value
    function setNonceThreshold(uint256 threshold) external;

    /// @notice Check the current threshold for the intent nonce to be considered consumed
    /// @return The current threshold value
    function nonceThreshold() external view returns (uint256);
}

src/interfaces/ISwapperEngine.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface ISwapperEngine {
    /// @notice Allows a user to deposit USDC tokens and create a new order.
    /// @dev This function transfers the specified amount of USDC tokens from the caller to the contract
    ///      and creates a new order with the deposited amount and the caller as the requester.
    /// @param amountToDeposit The amount of USDC tokens to deposit.
    function depositUSDC(uint256 amountToDeposit) external;

    /// @notice Allows a user to deposit USDC tokens with permit and create a new order.
    /// @dev This function transfers the specified amount of USDC tokens from the caller to the contract
    ///      and creates a new order with the deposited amount and the caller as the requester.
    /// @param amountToDeposit The amount of USDC tokens to deposit.
    /// @param deadline The deadline for the permit
    /// @param v The v value for the permit
    /// @param r The r value for the permit
    /// @param s The s value for the permit
    function depositUSDCWithPermit(
        uint256 amountToDeposit,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /// @notice Allows the requester of an order to withdraw their deposited USDC tokens and cancel the order.
    /// @dev This function deactivates the specified order, sets its token amount to zero, and transfers
    ///      the deposited USDC tokens back to the requester.
    /// @param orderToCancel The ID of the order to cancel and withdraw from.
    function withdrawUSDC(uint256 orderToCancel) external;

    /// @notice Allows a user to provide USD0 tokens and receive USDC tokens by matching against existing orders.
    /// @dev This function allows users to specify an amount of USDC tokens they want, calculating the corresponding
    ///      USD0 tokens they need and exchanging it against active orders.
    /// @param recipient The address to receive the USDC tokens.
    /// @param amountUsdcToTakeInNativeDecimals The amount of USDC tokens to take, in the token's native decimal representation.
    /// @param orderIdsToTake An array of order IDs to match against.
    /// @param partialMatchingAllowed A flag indicating whether partial matching is allowed.
    /// @return The unmatched amount of USDC tokens.
    function provideUsd0ReceiveUSDC(
        address recipient,
        uint256 amountUsdcToTakeInNativeDecimals,
        uint256[] memory orderIdsToTake,
        bool partialMatchingAllowed
    ) external returns (uint256);

    /// @notice provideUsd0ReceiveUSDC method with permit
    /// @dev This function allows users to to swap their USD0 for USDC with permit
    /// @param recipient The address to receive the USDC tokens.
    /// @param amountUsdcToTakeInNativeDecimals The amount of USDC tokens to take, in the token's native decimal representation.
    /// @param orderIdsToTake An array of order IDs to match against.
    /// @param partialMatchingAllowed A flag indicating whether partial matching is allowed.
    /// @param deadline The deadline for the permit
    /// @param usd0ToPermit The amount of USD0 tokens to permit, must be greater than the equivalent amount of USDC tokens to take.
    /// @param v The v value for the permit
    /// @param r The r value for the permit
    /// @param s The s value for the permit
    /// @return The unmatched amount of USDC tokens.
    function provideUsd0ReceiveUSDCWithPermit(
        address recipient,
        uint256 amountUsdcToTakeInNativeDecimals,
        uint256[] memory orderIdsToTake,
        bool partialMatchingAllowed,
        uint256 usd0ToPermit,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256);

    /// @notice Allows users to specify an amount of USD0 tokens to swap and receive USDC tokens by matching against existing orders.
    /// @dev This function handles the precision differences between USD0 and USDC taking dust into account
    ///      to ensure accurate conversion. It returns the unmatched USD0 amount in WAD format, including the dust.
    /// @param recipient The address to receive the USDC tokens.
    /// @param amountUsd0ToProvideInWad The amount of USD0 to provide in WAD format.
    /// @param orderIdsToTake An array of order IDs to match against.
    /// @param partialMatchingAllowed A flag indicating whether partial matching is allowed.
    /// @return The unmatched amount of Usd0 tokens in WAD format.
    function swapUsd0(
        address recipient,
        uint256 amountUsd0ToProvideInWad,
        uint256[] memory orderIdsToTake,
        bool partialMatchingAllowed
    ) external returns (uint256);

    /// @notice Get the next order ID.
    /// @dev This function returns the next order ID, which is the total number of orders created.
    /// @return The next order ID.
    function getNextOrderId() external view returns (uint256);
}

src/interfaces/oracles/IOracle.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IOracle {
    /// @notice Get the latest price of a token from the underlying oracle.
    /// @dev    View function which fetches the latest available oracle price from a Chainlink-compatible feed.
    /// @dev    The result is scaled to 18 decimals.
    /// @param  token The address of the token.
    /// @return The price of the token in USD with 18 decimals.
    function getPrice(address token) external view returns (uint256);

    /// @notice Compute a quote for the specified token and amount.
    /// @dev    This function fetches the latest available price from a Chainlink-compatible feed for the token and computes the quote based on the given amount.
    /// @dev    The quote is computed by multiplying the amount of tokens by the token price.
    /// @dev    The result is returned with as many decimals as the input amount.
    /// @param  token  The address of the token to calculate the quote for.
    /// @param  amount The amount of tokens for which to compute the quote.
    /// @return The computed quote in USD with as many decimals as the input.
    function getQuote(address token, uint256 amount) external returns (uint256);

    /// @notice Set the maximum allowed depeg threshold for stablecoins.
    /// @dev    The provided value should be in basis points relative to 1 USD.
    /// @dev    Valid values are from 0 (exact 1:1 peg required) to 10_000 ($0.00-$2.00 allowed).
    /// @dev    getPrice will revert if the price falls outside of this range.
    /// @param  maxAuthorizedDepegPrice The new maximum allowed depeg threshold.
    function setMaxDepegThreshold(uint256 maxAuthorizedDepegPrice) external;
}

src/interfaces/registry/IRegistryAccess.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IAccessControlDefaultAdminRules} from
    "openzeppelin-contracts/access/extensions/IAccessControlDefaultAdminRules.sol";

// solhint-disable-next-line no-empty-blocks
interface IRegistryAccess is IAccessControlDefaultAdminRules {}

src/interfaces/registry/IRegistryContract.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface IRegistryContract {
    function setContract(bytes32 name, address contractAddress) external;

    function getContract(bytes32 name) external view returns (address);
}

src/interfaces/token/IUsd0.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IUsd0 is IERC20Metadata {
    /// @notice mint Usd0 token
    /// @dev Can only be called by USD0_MINT role
    /// @param to address of the account who want to mint their token
    /// @param amount the amount of tokens to mint
    function mint(address to, uint256 amount) external;

    /// @notice burnFrom Usd0 token
    /// @dev Can only be called by USD0_BURN role
    /// @param account address of the account who want to burn
    /// @param amount the amount of tokens to burn
    function burnFrom(address account, uint256 amount) external;

    /// @notice burn Usd0 token
    /// @dev Can only be called by USD0_BURN role
    /// @param amount the amount of tokens to burn
    function burn(uint256 amount) external;

    /// @notice check if the account is blacklisted
    /// @param account address of the account to check
    /// @return bool
    function isBlacklisted(address account) external view returns (bool);
}

src/interfaces/tokenManager/ITokenMapping.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

interface ITokenMapping {
    /// @notice Links an RWA token to USD0 token.
    /// @dev Only the admin can link the RWA token to USD0 token.
    /// @dev Ensures the RWA token is valid and not already linked to USD0 token.
    /// @param rwa The address of the RWA token.
    /// @return A boolean value indicating success.
    function addUsd0Rwa(address rwa) external returns (bool);

    /// @notice Retrieves the RWA token linked to USD0 token.
    /// @dev Returns the address of the Rwa token associated with USD0 token.
    /// @param rwaId The ID of the RWA token.
    /// @return The address of the associated Rwa token.
    function getUsd0RwaById(uint256 rwaId) external view returns (address);

    /// @notice Retrieves all RWA tokens linked to USD0 token.
    /// @dev Returns an array of addresses of all RWA tokens associated with USD0 token.
    /// @dev the maximum number of RWA tokens that can be associated with USD0 token is 10.
    /// @return An array of addresses of associated RWA tokens.
    function getAllUsd0Rwa() external view returns (address[] memory);

    /// @notice Retrieves the last RWA ID for USD0 token.
    /// @dev Returns the highest index used for the RWA tokens associated with the USD0 token.
    /// @return The last RWA ID used in the STBC to RWA mapping.
    function getLastUsd0RwaId() external view returns (uint256);

    /// @notice Checks if the RWA token is linked to USD0 token.
    /// @dev Returns a boolean value indicating if the RWA token is linked to USD0 token.
    /// @param rwa The address of the RWA token.
    /// @return A boolean value indicating if the RWA token is linked to USD0 token.
    function isUsd0Collateral(address rwa) external view returns (bool);
}

src/utils/CheckAccessControl.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IRegistryAccess} from "src/interfaces/registry/IRegistryAccess.sol";

import {NotAuthorized} from "src/errors.sol";

/// @title Check Access control library
library CheckAccessControl {
    /// @dev Function to restrict to one access role.
    /// @param registryAccess The registry access contract.
    /// @param role The role being checked.
    function onlyMatchingRole(IRegistryAccess registryAccess, bytes32 role) internal view {
        if (!registryAccess.hasRole(role, msg.sender)) {
            revert NotAuthorized();
        }
    }
}

src/utils/NoncesUpgradeable.sol

// SPDX-License-Identifier: MIT
// Copyright (c) 2023 zOS Global Limited
pragma solidity ^0.8.20;

import {Initializable} from "openzeppelin-contracts-upgradeable/proxy/utils/Initializable.sol";

/**
 * @dev Provides tracking nonces for addresses. Nonces will only increment.
 */
abstract contract NoncesUpgradeable is Initializable {
    /**
     * @dev The nonce used for an `account` is not the expected current nonce.
     */
    error InvalidAccountNonce(address account, uint256 currentNonce);

    /// @custom:storage-location erc7201:openzeppelin.storage.Nonces
    struct NoncesStorage {
        mapping(address account => uint256) _nonces;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff))
    // solhint-disable-next-line
    bytes32 private constant NoncesStorageLocation =
        0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;

    function _getNoncesStorage() private pure returns (NoncesStorage storage $) {
        // solhint-disable-next-line
        assembly {
            $.slot := NoncesStorageLocation
        }
    }

    // solhint-disable-next-line
    function __Nonces_init() internal onlyInitializing {}
    // solhint-disable-next-line
    function __Nonces_init_unchained() internal onlyInitializing {}
    /**
     * @dev Returns the next unused nonce for an address.
     */

    function nonces(address owner) public view virtual returns (uint256) {
        NoncesStorage storage $ = _getNoncesStorage();
        return $._nonces[owner];
    }

    /**
     * @dev Consumes a nonce.
     *
     * Returns the current value and increments nonce.
     */
    function _useNonce(address owner) internal virtual returns (uint256) {
        NoncesStorage storage $ = _getNoncesStorage();
        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
        // decremented or reset. This guarantees that the nonce never overflows.
        unchecked {
            // It is important to do x++ and not ++x here.
            return $._nonces[owner]++;
        }
    }

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }

    /**
     * @dev Invalidate all nonces up to a certain value.
     *
     */
    function _invalidateUpToNonce(address owner, uint256 newNonce)
        internal
        virtual
        returns (uint256)
    {
        NoncesStorage storage $ = _getNoncesStorage();
        if (newNonce <= $._nonces[owner]) {
            revert InvalidAccountNonce(owner, newNonce);
        }
        unchecked {
            $._nonces[owner] = newNonce;
        }
        return newNonce - 1;
    }
}

src/utils/normalize.sol

// SPDX-License-Identifier: Apache-2.0

pragma solidity 0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {SCALAR_ONE} from "src/constants.sol";

/// @title Normalize decimals between tokens
library Normalize {
    /// @notice Normalize token amount to target decimals
    /// @notice i.e 100 USDC with 6 decimals to 100e18 USDC with 18 decimals
    /// @param tokenAmount The token amount
    /// @param tokenDecimals The token decimals
    /// @param targetDecimals The target decimals
    function tokenAmountToDecimals(uint256 tokenAmount, uint8 tokenDecimals, uint8 targetDecimals)
        internal
        pure
        returns (uint256)
    {
        if (tokenDecimals < targetDecimals) {
            return tokenAmount * (10 ** uint256(targetDecimals - tokenDecimals));
        } else if (tokenDecimals > targetDecimals) {
            return tokenAmount / (10 ** uint256(tokenDecimals - targetDecimals));
        } else {
            return tokenAmount;
        }
    }

    /// @notice Normalize token amount to 18 decimals
    /// @notice i.e 100 USDC with 6 decimals to 100e18 USDC with 18 decimals
    /// @param tokenAmount The token amount
    /// @param tokenDecimals The token decimals
    function tokenAmountToWad(uint256 tokenAmount, uint8 tokenDecimals)
        internal
        pure
        returns (uint256)
    {
        return tokenAmountToDecimals(tokenAmount, tokenDecimals, 18);
    }

    /// @notice Normalize token amount to wad
    /// @notice i.e 10e6 USYC with 6 decimals will result in wadAmount = 10e18 and  tokenDecimals = 6
    /// @param token The token address
    /// @param tokenAmount The token amount
    /// @return wadAmount The normalized token amount in wad
    /// @return tokenDecimals The token decimals
    function tokenAmountToWadWithTokenAddress(uint256 tokenAmount, address token)
        internal
        view
        returns (uint256, uint8)
    {
        uint8 tokenDecimals = uint8(IERC20Metadata(token).decimals());
        uint256 wadAmount = tokenAmountToWad(tokenAmount, uint8(tokenDecimals));
        return (wadAmount, tokenDecimals);
    }

    /// @notice Returns wad amount of token at wad price.
    /// @notice i.e 10e6 USYC with 6 decimals will be wadAmount = 10e18
    /// @notice if wadPrice is 1e18 USD then 10e18 USD0 will be worth 10e18 USD
    /// @param wadAmount The wad amount (18 decimals)
    /// @param wadPrice The wad price (18 decimals)
    /// @return The normalized token amount for price
    function wadAmountByPrice(uint256 wadAmount, uint256 wadPrice)
        internal
        pure
        returns (uint256)
    {
        return Math.mulDiv(wadAmount, wadPrice, SCALAR_ONE, Math.Rounding.Floor);
    }

    /// @notice return how much token we can have for stable amount.
    /// @notice i.e 10 (10e18) USD0 with 18 decimals worth 2$ each (2e18) will return 5e6 USYC with 6 decimals
    /// @param wadStableAmount The wad stable token amount
    /// @param wadPrice The wad price with for the token in stable
    /// @param tokenDecimals The token decimals
    /// @return The token amount for price with token decimals
    function wadTokenAmountForPrice(uint256 wadStableAmount, uint256 wadPrice, uint8 tokenDecimals)
        internal
        pure
        returns (uint256)
    {
        return Math.mulDiv(wadStableAmount, 10 ** tokenDecimals, wadPrice, Math.Rounding.Floor);
    }

    /// @dev Converts a WAD amount to a different number of decimals.
    /// @param wadAmount The WAD amount to convert.
    /// @param targetDecimals The number of decimals to convert to.
    /// @return The converted amount with the target number of decimals.
    function wadAmountToDecimals(uint256 wadAmount, uint8 targetDecimals)
        internal
        pure
        returns (uint256)
    {
        return tokenAmountToDecimals(wadAmount, 18, targetDecimals);
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "shanghai",
  "remappings": [
    ":@openzeppelin/=lib/openzeppelin-contracts/",
    ":ds-test/=lib/forge-std/lib/ds-test/src/",
    ":forge-std/=lib/forge-std/src/",
    ":openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    ":openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    ":openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    ":solidity-stringutils/=lib/openzeppelin-foundry-upgrades/lib/solidity-stringutils/",
    ":src/=src/",
    ":utils/=lib/utils/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.