ETH Price: $2,940.82 (-4.96%)

Contract

0xbabA24610681FDf6A8fcb921C3074B0dd6dc57ae

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

ContractCreator

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
55049872025-07-11 15:29:58157 days ago1752247798  Contract Creation0 ETH

Cross-Chain Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
InventoryPoolDefaultAccessManager01

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 200 runs

Other Settings:
prague EvmVersion, GNU GPLv3 license
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/*=================================================================================================*
 *   Nomial::InventoryPoolDefaultAccessManager01.sol                                               *
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
 *   ____________________ ______(_)_____ ___  /                                                    *
 *   __  __ \  __ \_  __ `__ \_  /_  __ `/_  /                                                     *
 *   _  / / / /_/ /  / / / / /  / / /_/ /_  /                                                      *
 *   /_/ /_/\____//_/ /_/ /_//_/  \__,_/ /_/                                                       *
 *=================================================================================================*/

import {AccessControlEnumerable} from "@openzeppelin/contracts/access/extensions/AccessControlEnumerable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IInventoryPoolAccessManager01} from "../interfaces/IInventoryPoolAccessManager01.sol";
import {IInventoryPoolParams01} from "../interfaces/IInventoryPoolParams01.sol";
import {OwnableParams01} from "../OwnableParams01.sol";
import {InventoryPool01} from "../InventoryPool01.sol";
import {CollateralPool01} from "../CollateralPool01.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";

/**
 * @title InventoryPoolDefaultAccessManager01
 * @notice Access control contract for management of InventoryPool01 contracts
 * @dev Implements a multi-signature validator system where a threshold of validator signatures
 * is required for all operations. The contract uses EIP-712 for secure message signing and
 * implements replay protection through signature tracking.
 */
contract InventoryPoolDefaultAccessManager01 is AccessControlEnumerable, IInventoryPoolAccessManager01, EIP712, ReentrancyGuardTransient {
    bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");
    bytes32 public constant BORROWER_ROLE = keccak256("BORROWER_ROLE");

    bytes32 public constant BORROW_TYPEHASH = keccak256("Borrow(address pool,address borrower,uint256 amount,address recipient,uint256 expiry,uint256 chainId,bytes32 salt)");
    bytes32 public constant FORGIVE_DEBT_TYPEHASH = keccak256("ForgiveDebt(address pool,uint256 amount,address borrower,bytes32 salt)");
    bytes32 public constant ADD_VALIDATOR_TYPEHASH = keccak256("AddValidator(address validator,uint16 signatureThreshold,bytes32 salt)");
    bytes32 public constant REMOVE_VALIDATOR_TYPEHASH = keccak256("RemoveValidator(address validator,uint16 signatureThreshold,bytes32 salt)");
    bytes32 public constant ADD_BORROWER_TYPEHASH = keccak256("AddBorrower(address borrower,bytes32 salt)");
    bytes32 public constant REMOVE_BORROWER_TYPEHASH = keccak256("RemoveBorrower(address borrower,bytes32 salt)");
    bytes32 public constant UPDATE_BASE_FEE_TYPEHASH = keccak256("UpdateBaseFee(address paramsContract,uint256 newBaseFee,bytes32 salt)");
    bytes32 public constant UPDATE_INTEREST_RATE_TYPEHASH = keccak256("UpdateInterestRate(address paramsContract,uint256 newInterestRate,bytes32 salt)");
    bytes32 public constant UPDATE_PENALTY_RATE_TYPEHASH = keccak256("UpdatePenaltyRate(address paramsContract,uint256 newPenaltyRate,bytes32 salt)");
    bytes32 public constant UPDATE_PENALTY_PERIOD_TYPEHASH = keccak256("UpdatePenaltyPeriod(address paramsContract,uint256 newPenaltyPeriod,bytes32 salt)");
    bytes32 public constant UPGRADE_PARAMS_CONTRACT_TYPEHASH = keccak256("UpgradeParamsContract(address pool,address paramsContract,bytes32 salt)");
    bytes32 public constant OVERWRITE_CORE_STATE_TYPEHASH = keccak256("OverwriteCoreState(address pool,uint256 newStoredAccInterestFactor,uint256 newLastAccumulatedInterestUpdate,uint256 newScaledReceivables,bytes32 salt)");
    bytes32 public constant TRANSFER_OWNERSHIP_TYPEHASH = keccak256("TransferOwnership(address ownedContract,address newOwner,bytes32 salt)");
    bytes32 public constant SET_SIGNATURE_THRESHOLD_TYPEHASH = keccak256("SetSignatureThreshold(uint16 newSignatureThreshold,bytes32 salt)");
    bytes32 public constant LIQUIDATE_BALANCE_TYPEHASH = keccak256("LiquidateBalance(address pool,address depositor,address token,uint256 amount,address recipient,bytes32 salt)");
    bytes32 public constant LIQUIDATE_WITHDRAW_TYPEHASH = keccak256("LiquidateWithdraw(address pool,uint256 nonce,address depositor,uint256 amount,address recipient,bytes32 salt)");
    bytes32 public constant UPDATE_WITHDRAW_PERIOD_TYPEHASH = keccak256("UpdateWithdrawPeriod(address pool,uint256 newWithdrawPeriod,bytes32 salt)");

    // Track used signatures to prevent replay
    mapping(bytes32 => bool) public usedSigHashes;

    uint16 public signatureThreshold;

    mapping(bytes32 => mapping(address => bool)) private _seenSigners;

    /**
     * @notice Initializes the contract with an admin and initial set of validators
     * @dev Sets up the initial validator set and signature threshold. The threshold must be greater
     * than half the number of validators.
     * @param admin Address to be granted the DEFAULT_ADMIN_ROLE
     * @param validators Array of addresses to be granted the VALIDATOR_ROLE
     * @param borrowers Array of addresses to be granted the BORROWER_ROLE
     * @param signatureThreshold_ The minimum number of validator signatures required for operations
     */
    constructor(
        address admin,
        address[] memory validators,
        address[] memory borrowers,
        uint16 signatureThreshold_
    ) EIP712("InventoryPoolDefaultAccessManager01", "1") {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        if (uint16(validators.length) == 0) {
            revert ZeroValidatorsNotAllowed();
        }
        for (uint i = 0; i < validators.length; i++) {
            _grantValidatorRole(validators[i]);
        }
        for (uint i = 0; i < borrowers.length; i++) {
            _grantBorrowerRole(borrowers[i]);
        }
        _setSignatureThreshold(signatureThreshold_);
    }

    /**
     * @notice Execute borrow on an inventory pool
     * @dev Requires signatures from the threshold number of validators.
     * @param pool Address of the inventory pool contract
     * @param amount Amount to borrow from pool
     * @param recipient Address to receive the borrowed assets
     * @param expiry Timestamp after which the borrow is no longer valid
     * @param salt Unique value to prevent signature replay
     * @param signatures Array of validator signatures
     */
    function borrow(
        InventoryPool01 pool,
        uint amount,
        address recipient,
        uint expiry,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(BORROWER_ROLE) {
        address borrower = _msgSender();

        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(BORROW_TYPEHASH, pool, borrower, amount, recipient, expiry, block.chainid, salt)));
        _validateSignatures(digest, signatures);

        pool.borrow(amount, borrower, recipient, expiry, block.chainid);
    }

    /**
     * @notice Forgives a specified amount of debt for a borrower
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The inventory pool where the debt exists
     * @param amount The amount of debt to forgive
     * @param borrower The borrower whose debt should be forgiven
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function forgiveDebt(
        InventoryPool01 pool,
        uint amount,
        address borrower,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(FORGIVE_DEBT_TYPEHASH, pool, amount, borrower, salt)));
        _validateSignatures(digest, signatures);

        pool.forgiveDebt(amount, borrower);
    }

    /**
     * @notice Updates the base fee in the params contract
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param paramsContract The params contract to update
     * @param newBaseFee The new base fee value to set
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function updateBaseFee(
        OwnableParams01 paramsContract,
        uint newBaseFee,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPDATE_BASE_FEE_TYPEHASH, paramsContract, newBaseFee, salt)));
        _validateSignatures(digest, signatures);

        paramsContract.updateBaseFee(newBaseFee);
    }

    /**
     * @notice Updates the interest rate in the params contract
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param paramsContract The params contract to update
     * @param newInterestRate The new interest rate value to set
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function updateInterestRate(
        OwnableParams01 paramsContract,
        uint newInterestRate,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPDATE_INTEREST_RATE_TYPEHASH, paramsContract, newInterestRate, salt)));
        _validateSignatures(digest, signatures);

        paramsContract.updateInterestRate(newInterestRate);
    }

    /**
     * @notice Updates the penalty rate in the params contract
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param paramsContract The params contract to update
     * @param newPenaltyRate The new penalty rate value to set
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function updatePenaltyRate(
        OwnableParams01 paramsContract,
        uint newPenaltyRate,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPDATE_PENALTY_RATE_TYPEHASH, paramsContract, newPenaltyRate, salt)));
        _validateSignatures(digest, signatures);

        paramsContract.updatePenaltyRate(newPenaltyRate);
    }

    /**
     * @notice Updates the penalty period in the params contract
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param paramsContract The params contract to update
     * @param newPenaltyPeriod The new penalty period value to set
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function updatePenaltyPeriod(
        OwnableParams01 paramsContract,
        uint newPenaltyPeriod,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPDATE_PENALTY_PERIOD_TYPEHASH, paramsContract, newPenaltyPeriod, salt)));
        _validateSignatures(digest, signatures);

        paramsContract.updatePenaltyPeriod(newPenaltyPeriod);
    }

    /**
     * @notice Upgrades the params contract for an inventory pool
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The inventory pool to upgrade
     * @param paramsContract The new params contract to use
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function upgradeParamsContract(
        InventoryPool01 pool,
        IInventoryPoolParams01 paramsContract,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPGRADE_PARAMS_CONTRACT_TYPEHASH, pool, paramsContract, salt)));
        _validateSignatures(digest, signatures);

        pool.upgradeParamsContract(paramsContract);
    }

    /**
     * @notice Overwrites core state variables in an inventory pool
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The inventory pool to overwrite core state
     * @param newStoredAccInterestFactor New value for stored accumulated interest factor
     * @param newLastAccumulatedInterestUpdate New value for last accumulated interest update timestamp
     * @param newScaledReceivables New value for scaled receivables
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function overwriteCoreState(
        InventoryPool01 pool,
        uint newStoredAccInterestFactor,
        uint newLastAccumulatedInterestUpdate,
        uint newScaledReceivables,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(OVERWRITE_CORE_STATE_TYPEHASH, pool, newStoredAccInterestFactor, newLastAccumulatedInterestUpdate, newScaledReceivables, salt)));
        _validateSignatures(digest, signatures);

        pool.overwriteCoreState(newStoredAccInterestFactor, newLastAccumulatedInterestUpdate, newScaledReceivables);
    }

    /**
     * @notice Liquidates a depositor's balance of token from collateral pool
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The collateral pool to liquidate the balance from
     * @param depositor The address of the depositor
     * @param token The ERC20 token to liquidate
     * @param amount The amount of tokens to liquidate
     * @param recipient The address to receive the liquidated tokens
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function liquidateBalance(
        CollateralPool01 pool,
        address depositor,
        IERC20 token,
        uint amount,
        address recipient,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(LIQUIDATE_BALANCE_TYPEHASH, pool, depositor, token, amount, recipient, salt)));
        _validateSignatures(digest, signatures);

        pool.liquidateBalance(depositor, token, amount, recipient);
    }

    /**
     * @notice Liquidates a pending withdrawal request from a collateral pool
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The collateral pool to liquidate the withdrawal from
     * @param nonce The identifier of the withdrawal request to liquidate
     * @param depositor The address whose withdrawal is being liquidated
     * @param amount The amount of tokens to liquidate from the withdrawal
     * @param recipient The address that will receive the liquidated tokens
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function liquidateWithdraw(
        CollateralPool01 pool,
        uint nonce,
        address depositor,
        uint amount,
        address recipient,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(LIQUIDATE_WITHDRAW_TYPEHASH, pool, nonce, depositor, amount, recipient, salt)));
        _validateSignatures(digest, signatures);

        pool.liquidateWithdraw(nonce, depositor, amount, recipient);
    }

    /**
     * @notice Updates the withdrawal period in a collateral pool
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param pool The collateral pool to update the withdrawal period for
     * @param newWithdrawPeriod The new withdrawal period in seconds
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function updateWithdrawPeriod(
        CollateralPool01 pool,
        uint newWithdrawPeriod,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(UPDATE_WITHDRAW_PERIOD_TYPEHASH, pool, newWithdrawPeriod, salt)));
        _validateSignatures(digest, signatures);

        pool.updateWithdrawPeriod(newWithdrawPeriod);
    }

    /**
     * @notice Transfers ownership of a contract owned by this contract
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param ownedContract The contract to transfer ownership of
     * @param newOwner The address to transfer ownership to
     * @param salt Unique value to prevent signature replay
     * @param signatures Array of validator signatures
     */
    function transferOwnership(
        Ownable ownedContract,
        address newOwner,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(TRANSFER_OWNERSHIP_TYPEHASH, ownedContract, newOwner, salt)));
        _validateSignatures(digest, signatures);

        ownedContract.transferOwnership(newOwner);
    }

    function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        revert GrantRoleNotAllowed();
    }

    function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        revert RevokeRoleNotAllowed();
    }

    function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
        revert RenounceRoleNotAllowed();
    }

    /**
     * @notice Adds a new validator to the system
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param validator Address to be granted the VALIDATOR_ROLE
     * @param newSignatureThreshold New signature threshold to set after adding validator
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function addValidator(
        address validator,
        uint16 newSignatureThreshold,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(ADD_VALIDATOR_TYPEHASH, validator, newSignatureThreshold, salt)));
        _validateSignatures(digest, signatures);

        _grantValidatorRole(validator);
        _setSignatureThreshold(newSignatureThreshold);
    }

    /**
     * @notice Removes a validator from the system
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param validator Address to have VALIDATOR_ROLE revoked
     * @param newSignatureThreshold New signature threshold to set after removing validator
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function removeValidator(
        address validator,
        uint16 newSignatureThreshold,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        if (validatorCount() == 1) {
            revert ZeroValidatorsNotAllowed();
        }

        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(REMOVE_VALIDATOR_TYPEHASH, validator, newSignatureThreshold, salt)));
        _validateSignatures(digest, signatures);

        _revokeValidatorRole(validator);
        _setSignatureThreshold(newSignatureThreshold);
    }

    /**
     * @notice Adds a new borrower to the system
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param borrower Address to be granted the BORROWER_ROLE
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function addBorrower(
        address borrower,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(ADD_BORROWER_TYPEHASH, borrower, salt)));
        _validateSignatures(digest, signatures);

        _grantBorrowerRole(borrower);
    }

    /**
     * @notice Removes a borrower from the system
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param borrower Address to have BORROWER_ROLE revoked
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function removeBorrower(
        address borrower,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(REMOVE_BORROWER_TYPEHASH, borrower, salt)));
        _validateSignatures(digest, signatures);

        _revokeBorrowerRole(borrower);
    }

    /**
     * @notice Sets the signature threshold
     * @dev Requires signatures from the threshold number of validators. Can only be called by DEFAULT_ADMIN_ROLE
     * @param newSignatureThreshold The new signature threshold to set
     * @param salt Value to ensure digest is unique
     * @param signatures Array of validator signatures
     */
    function setSignatureThreshold(
        uint16 newSignatureThreshold,
        bytes32 salt,
        bytes[] calldata signatures
    ) external nonReentrant() onlyRole(DEFAULT_ADMIN_ROLE) {
        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(SET_SIGNATURE_THRESHOLD_TYPEHASH, newSignatureThreshold, salt)));
        _validateSignatures(digest, signatures);

        _setSignatureThreshold(newSignatureThreshold);
    }

    /**
     * @notice Returns the number of validators
     * @return The number of validators
     */
    function validatorCount() public view returns (uint) {
        return getRoleMemberCount(VALIDATOR_ROLE);
    }

    /**
     * @notice Returns the number of borrowers
     * @return The number of borrowers
     */
    function borrowerCount() public view returns (uint) {
        return getRoleMemberCount(BORROWER_ROLE);
    }

    /**
     * @notice Returns the EIP-712 domain separator
     * @return The domain separator used in EIP-712 signatures
     */
    function domainSeparator() external view returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @notice Returns the EIP-712 hash of a structured data
     * @param structHash The hash of the struct data to be signed
     * @return The EIP-712 typed data hash
     */
    function hashTypedData(bytes32 structHash) external view returns (bytes32) {
        return _hashTypedDataV4(structHash);
    }

    /**
     * @notice Internal function to validate multiple signatures
     * @dev Verifies that enough valid signatures from unique validators are provided
     * and that the signature hash hasn't been used before.
     * @param digest The EIP-712 message hash that was signed
     * @param signatures Array of validator signatures to verify
     */
    function _validateSignatures(bytes32 digest, bytes[] calldata signatures) internal {
        if (usedSigHashes[digest]) {
            revert SignatureUsed(digest);
        }
        usedSigHashes[digest] = true;

        uint validSignatures = 0;
        address[] memory signers = new address[](signatures.length);

        for (uint i = 0; i < signatures.length; i++) {
            address signer = ECDSA.recover(digest, signatures[i]);
            signers[i] = signer;

            if (_seenSigners[digest][signer]) {
                revert ValidatorNotUnique(signer);
            }

            _checkRole(VALIDATOR_ROLE, signer);

            _seenSigners[digest][signer] = true;
            validSignatures++;
        }

        if (validSignatures < signatureThreshold) {
            revert InvalidSignatureCount(validSignatures, signatureThreshold);
        }

        for (uint i = 0; i < signers.length; i++) {
            delete _seenSigners[digest][signers[i]];
        }
    }

    /**
     * @notice Internal function to update the signature threshold
     * @dev Ensures the new threshold is greater than half the validator count for security
     * @param newSignatureThreshold The new threshold value to set
     */
    function _setSignatureThreshold(uint16 newSignatureThreshold) internal {
        uint validatorCount_ = validatorCount();
        if (newSignatureThreshold <= validatorCount_ / 2) {
            revert SignatureThresholdTooLow(newSignatureThreshold, validatorCount_);
        } else if (newSignatureThreshold > validatorCount_) {
            revert SignatureThresholdTooHigh(newSignatureThreshold, validatorCount_);
        }
        signatureThreshold = newSignatureThreshold;

        emit SignatureThresholdUpdated(newSignatureThreshold);
    }

    /**
     * @notice Internal function to grant the validator role to an address
     * @dev Wraps AccessControl._grantRole
     * @param validator The address to be granted the validator role
     * @custom:revert ValidatorExists If the address already has the validator role
     */
    function _grantValidatorRole(address validator) internal {
        if(!_grantRole(VALIDATOR_ROLE, validator)) {
            revert ValidatorExists(validator);
        }
    }

    /**
     * @notice Internal function to revoke the validator role from an address
     * @dev Wraps AccessControl._revokeRole
     * @param validator The address to have the validator role revoked
     * @custom:revert ValidatorDoesNotExist If the address does not have the validator role
     */
    function _revokeValidatorRole(address validator) internal {
        if(!_revokeRole(VALIDATOR_ROLE, validator)) {
            revert ValidatorDoesNotExist(validator);
        }
    }

    /**
     * @notice Internal function to grant the borrower role to an address
     * @dev Wraps AccessControl._grantRole
     * @param borrower The address to be granted the borrower role
     * @custom:revert BorrowerExists If the address already has the borrower role
     */
    function _grantBorrowerRole(address borrower) internal {
        if(!_grantRole(BORROWER_ROLE, borrower)) {
            revert BorrowerExists(borrower);
        }
    }

    /**
     * @notice Internal function to revoke the borrower role from an address
     * @dev Wraps AccessControl._revokeRole
     * @param borrower The address to have the borrower role revoked
     * @custom:revert BorrowerDoesNotExist If the address does not have the borrower role
     */
    function _revokeBorrowerRole(address borrower) internal {
        if(!_revokeRole(BORROWER_ROLE, borrower)) {
            revert BorrowerDoesNotExist(borrower);
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/*=================================================================================================*
 *   Nomial::InventoryPool01.sol                                                                   *
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
 *   ____________________ ______(_)_____ ___  /                                                    *
 *   __  __ \  __ \_  __ `__ \_  /_  __ `/_  /                                                     *
 *   _  / / / /_/ /  / / / / /  / / /_/ /_  /                                                      *
 *   /_/ /_/\____//_/ /_/ /_//_/  \__,_/ /_/                                                       *
 *=================================================================================================*/

import {ERC4626, IERC20, ERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IInventoryPool01} from "./interfaces/IInventoryPool01.sol";
import {IInventoryPoolParams01} from "./interfaces/IInventoryPoolParams01.sol";
import {WadMath} from "./utils/WadMath.sol";

/**
 * @title InventoryPool01
 * @dev An ERC4626-compliant lending pool that allows borrowing by the pool owner and tracks debt
 * Features include:
 * - Variable interest rates based on pool utilization
 * - Penalty interest for overdue loans
 * - Repayment of both base debt and penalty debt
 * All rates and calculations use WAD (1e18) precision
 */
contract InventoryPool01 is ERC4626, Ownable, IInventoryPool01, ReentrancyGuardTransient {
    using Math for uint256;
    using SafeERC20 for IERC20;

    uint constant WAD = 1e18;
    address constant DEAD_ADDRESS = 0x000000000000000000000000000000000000dEaD;

    // 500% annual interest rate (per-second), in WAD (1e18) precision
    // 500n * 10n**16n / (60n * 60n * 24n * 365n)
    uint constant MAX_INTEREST_RATE = 158548959918;

    /**
     * @dev Represents a borrower's debt position and penalty status
     * @param scaledDebt The borrower's debt amount scaled by the global accumulated interest factor
     * @param penaltyCounterStart The timestamp when the penalty counter started for this borrower. 0 if not in penalty period
     */
    struct Borrower {
        uint scaledDebt;
        uint penaltyCounterStart;
    }

    /// @notice The contract that defines interest rates, fees, and penalty settings for this pool
    IInventoryPoolParams01 public params;

    /// @notice The global accumulated interest factor used for debt scaling, stored in WAD (1e18) precision
    /// @dev Although this is public, it is not recommended to read it directly. Instead use the `accumulatedInterestFactor()`
    /// function which will calculate the interest factor based on the current time and the last update timestamp.
    uint public storedAccInterestFactor;

    /// @notice The timestamp of the last stored accumulated interest factor update
    uint public lastAccumulatedInterestUpdate;

    /// @notice The total scaled debt of all borrowers, used to calculate total receivables
    uint public scaledReceivables;

    /// @notice Maps borrower addresses to their debt positions and penalty status data
    mapping(address => Borrower) public borrowers;

    constructor(
        IERC20 asset_,
        string memory name,
        string memory symbol,
        uint initAmount,
        address owner,
        IInventoryPoolParams01 paramsContract
    ) ERC4626(IERC20(asset_)) ERC20(name, symbol) Ownable(owner) {
        /**
         * deployer is responsible for burning a small deposit to mitigate inflation attack.
         * this ERC4626 implementation uses offset to make inflation attack un-profitable
         * but burning a small initial deposit eliminates the possibility of a griefing attack
         */
        if (initAmount > 0) {
            deposit(initAmount, DEAD_ADDRESS);
        }

        params = paramsContract;
    }

    /**
     * @notice Creates a new borrow position
     * @dev Only callable by owner. Creates a new borrow position with the specified amount
     * and transfers the borrowed assets to the recipient. Interest starts accruing immediately.
     * @param amount The amount of assets to borrow
     * @param borrower The address that will own the debt position
     * @param recipient The address that will receive the borrowed assets
     * @param expiry The timestamp after which this borrow request is no longer valid
     * @param chainId The chain ID where this borrow should be executed (for cross-chain safety)
     * @custom:revert Expired If the current timestamp is past the expiry
     * @custom:revert WrongChainId If executed on a different chain than specified
     */
    function borrow(uint amount, address borrower, address recipient, uint expiry, uint chainId) external nonReentrant() onlyOwner() {
        if (block.timestamp > expiry) revert Expired();
        if (block.chainid != chainId) revert WrongChainId(chainId);

        _updateAccumulatedInterestFactor();

        uint scaledDebt_ = amount.mulDiv(WAD, storedAccInterestFactor, Math.Rounding.Ceil) + amount.mulDiv(params.baseFee(), WAD, Math.Rounding.Ceil);
        borrowers[borrower].scaledDebt += scaledDebt_;
        scaledReceivables += scaledDebt_;
        if (borrowers[borrower].penaltyCounterStart == 0) {
            borrowers[borrower].penaltyCounterStart = block.timestamp;
        }

        IERC20(asset()).safeTransfer(recipient, amount);

        emit Borrowed(borrower, recipient, amount);
    }

    /**
     * @notice Repays debt for a borrower
     * @dev Accepts repayment for both base debt and penalty debt. Penalty debt is paid first.
     * Partial repayments of penalty debt proportionally reduce the penalty time
     * Partial repayments of base debt proportionally reduce the time until penalties start.
     * @param amount The amount of assets to repay
     * @param borrower The address whose debt is being repaid
     * @custom:revert ZeroRepayment If amount is 0
     * @custom:revert NoDebt If the borrower has no outstanding debt
     */
    function repay(uint amount, address borrower) public {
        _repay(amount, borrower, false);
    }

    /**
     * @notice Allows owner to forgive debt without requiring asset transfer
     * @dev Similar to repay() but doesn't require actual asset transfer
     * @param amount The amount of debt to forgive
     * @param borrower The address whose debt is being forgiven
     * @custom:revert ZeroRepayment If amount is 0
     * @custom:revert NoDebt If the borrower has no outstanding debt
     */
    function forgiveDebt(uint amount, address borrower) public onlyOwner() {
        _repay(amount, borrower, true);
    }

    /**
     * @notice Updates the IInventoryPoolParams01 contract address
     * @dev Allows upgrading to a new parameters contract while maintaining the same pool
     * @param paramsContract The address of the new IInventoryPoolParams01 contract
     */
    function upgradeParamsContract(IInventoryPoolParams01 paramsContract) public onlyOwner() {
        if (paramsContract == params) {
            revert ParamsContractNotChanged();
        }

        params = paramsContract;

        emit ParamsContractUpgraded(paramsContract);
    }

    /**
     * @notice Overwrites core state of the pool
     * @dev Only callable by owner. This is an emergency function that allows the pool to be recovered
     * from an unexpected state, such as accumulated interest factor arithmetic overflow.
     * @param newStoredAccInterestFactor The new value for storedAccInterestFactor
     * @param newLastAccumulatedInterestUpdate The new timestamp for lastAccumulatedInterestUpdate
     * @param newScaledReceivables The new value for scaledReceivables
     */
    function overwriteCoreState(
        uint newStoredAccInterestFactor,
        uint newLastAccumulatedInterestUpdate,
        uint newScaledReceivables
    ) public onlyOwner() {
        storedAccInterestFactor = newStoredAccInterestFactor;
        lastAccumulatedInterestUpdate = newLastAccumulatedInterestUpdate;
        scaledReceivables = newScaledReceivables;
    }

    /**
     * @notice Returns the total assets managed by this pool
     * @dev Includes both the actual balance and all outstanding receivables
     * @return The total assets in the pool
     */
    function totalAssets() public view override(ERC4626, IInventoryPool01) returns (uint) {
        return totalReceivables() + IERC20(asset()).balanceOf(address(this));
    }

    /**
     * @notice Returns the total amount of debt owed to the pool
     * @dev Includes both base debt and accrued interest for all borrowers. Does not include penalty debt
     * @return The total receivables amount
     */
    function totalReceivables() public view returns (uint) {
        return _totalReceivables(accumulatedInterestFactor());
    }

    /**
     * @notice Calculates the current utilization rate of the pool
     * @dev Utilization = Total Receivables / Total Assets
     * @return The utilization rate in WAD (1e18) precision
     */
    function utilizationRate() public view returns (uint) {
        uint totalReceivables_ = totalReceivables();
        uint totalAssets_ = totalReceivables_ + IERC20(asset()).balanceOf(address(this));
        return totalReceivables_.mulDiv(WAD, totalAssets_);
    }

    /**
     * @notice Returns the current base debt for a borrower
     * @dev Base debt includes the original borrowed amount plus accrued interest,
     * but excludes any penalty interest
     * @param borrower The borrower's address
     * @return The current base debt amount for the borrower
     */
    function baseDebt(address borrower) public view returns (uint) {
        return _baseDebt(borrower, accumulatedInterestFactor());
    }

    /**
     * @notice Returns the current penalty debt for a borrower
     * @dev Penalty debt only exists after the penalty period has passed
     * and is calculated based on the penalty rate
     * @param borrower The borrower's address
     * @return The current penalty debt amount for the borrower
     */
    function penaltyDebt(address borrower) public view returns (uint) {
        return _penaltyDebt(borrower, accumulatedInterestFactor());
    }

    /**
     * @notice Returns how long a borrower has been in the penalty period
     * @dev Returns 0 if not in penalty period, otherwise returns seconds since penalty started
     * @param borrower The borrower's address
     * @return The number of seconds in penalty period, or 0 if not in penalty period
     */
    function penaltyTime(address borrower) public view returns (uint) {
        uint penaltyCounterStart = borrowers[borrower].penaltyCounterStart;
        if (penaltyCounterStart > 0) {
            uint penaltyCounterEnd = penaltyCounterStart + params.penaltyPeriod();
            if (penaltyCounterEnd < block.timestamp) {
                return block.timestamp - penaltyCounterEnd;
            }
        }
        return 0;
    }

    /**
     * @notice Returns the accumulated interest factor for the pool
     * @dev Used to calculate the base debt for borrowers
     * @return The accumulated interest factor in WAD (1e18) precision
     */
    function accumulatedInterestFactor() public view returns (uint) {
        if (storedAccInterestFactor == 0) {
            return WAD;
        } else {
            // newFactor = oldFactor * (1 + ratePerSecond)^secondsSinceLastUpdate
            return storedAccInterestFactor.mulDiv(
                WadMath.wadPow(
                    WAD + interestRate(),
                    block.timestamp - lastAccumulatedInterestUpdate
                ),
                WAD,
                Math.Rounding.Ceil
            );
        }
    }

    /**
     * @notice Returns the current interest rate for the pool
     * @dev The maximum interest rate is 1000% annual, represented as a per-second rate in WAD (1e18) precision
     * @return The interest rate per-second in WAD (1e18) precision
     */
    function interestRate() public view returns (uint) {
        uint rate = params.interestRate(_utilizationRate(storedAccInterestFactor));
        if (rate > MAX_INTEREST_RATE) {
            return MAX_INTEREST_RATE;
        }
        return rate;
    }

    /**
     * @notice Internal function to handle debt repayment
     * @dev Handles both base debt and penalty debt repayment
     * @param amount The amount of assets to repay
     * @param borrower The borrower's address
     * @param forgive If true, debt is forgiven without requiring asset transfer
     * @custom:revert ZeroRepayment If amount is 0
     * @custom:revert NoDebt If the borrower has no outstanding debt
     */
    function _repay(uint amount, address borrower, bool forgive) internal nonReentrant() {
        if (amount == 0) {
          revert ZeroRepayment();
        }

        _updateAccumulatedInterestFactor();

        uint baseDebt_ = _baseDebt(borrower, storedAccInterestFactor);
        if (baseDebt_ == 0) {
            revert NoDebt();
        }

        uint baseDebtPayment_;

        uint penaltyDebt_ = _penaltyDebt(borrower, storedAccInterestFactor);
        uint penaltyPayment_ = 0;
        uint newPenaltyCounterStart_ = borrowers[borrower].penaltyCounterStart;
        if (penaltyDebt_ > 0) {
            if (amount > penaltyDebt_) {
                // payment amount is greater than penalty debt.
                // after penalty debt is paid, the remaining amount goes to base debt payment
                baseDebtPayment_ = amount - penaltyDebt_;
                // set penalty payment to full penalty debt amount
                penaltyPayment_ = penaltyDebt_;
                // remove all penalty time so that borrower is at the end of the penalty grace period
                newPenaltyCounterStart_ += penaltyTime(borrower);
            } else {
                // payment amount is less than or equal to penalty debt
                penaltyPayment_ = amount;
                // remove penalty time proportionally to the amount of penalty debt repaid
                newPenaltyCounterStart_ += penaltyTime(borrower).mulDiv(penaltyPayment_, penaltyDebt_);
            }
            emit PenaltyRepayment(borrower, penaltyDebt_, penaltyPayment_);
        } else {
            // no penalty debt, full payment amount is used to pay base debt
            baseDebtPayment_ = amount;
        }
        
        if (baseDebtPayment_ > 0) {
            if (baseDebtPayment_ >= baseDebt_) {
                // full repayment of base debt.
                // clear penalty counter start time.
                newPenaltyCounterStart_ = 0;
                // set base debt payment to base debt amount, in case of overpayment
                baseDebtPayment_ = baseDebt_;
            } else {
                // partial repayment of base debt.
                // decrease time until penalty based on the amount of base debt repaid.
                newPenaltyCounterStart_ += (block.timestamp - newPenaltyCounterStart_).mulDiv(baseDebtPayment_, baseDebt_);
            }

            uint scaledDebt_ = baseDebtPayment_.mulDiv(WAD, storedAccInterestFactor, Math.Rounding.Ceil);
            borrowers[borrower].scaledDebt -= scaledDebt_;
            scaledReceivables -= scaledDebt_;

            emit BaseDebtRepayment(borrower, baseDebt_, baseDebtPayment_);
        }

        // adjust penalty counter start time
        borrowers[borrower].penaltyCounterStart = newPenaltyCounterStart_;

        if (!forgive) {
            IERC20(asset()).safeTransferFrom(msg.sender, address(this), baseDebtPayment_ + penaltyPayment_);
        }
    }

    /**
     * @notice ERC4626 override to handle deposit
     * @dev Updates the accumulated interest factor after deposit, because deposit will decrease
     * the utlization rate which will decrease the pool's interest rate
     * @param caller The caller's address
     * @param receiver The receiver's address
     * @param assets The amount of assets to deposit
     * @param shares The amount of shares to mint
     */
    function _deposit(
        address caller,
        address receiver,
        uint256 assets,
        uint256 shares
    ) internal override nonReentrant() {
        ERC4626._deposit(caller, receiver, assets, shares);

        _updateAccumulatedInterestFactor();
    }

    /**
     * @notice ERC4626 override to handle withdraw
     * @dev Updates the accumulated interest factor after withdraw, because withdraw will increase
     * the utlization rate which will increase the pool's interest rate. If a shareholder owns more
     * shares than the amount of unborrowed assets, the shareholder can only withdraw up to the amount
     * of unborrowed assets, otherwise an InsufficientLiquidity error will be thrown.
     * @param caller The caller's address
     * @param receiver The receiver's address
     * @param owner The owner's address
     * @param assets The amount of assets to withdraw
     * @param shares The amount of shares to burn
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal override nonReentrant() {
        if (assets > IERC20(asset()).balanceOf(address(this))) {
            revert InsufficientLiquidity();
        }
        ERC4626._withdraw(caller, receiver, owner, assets, shares);

        _updateAccumulatedInterestFactor();
    }

    /**
     * @notice Internal function to update the accumulated interest factor
     * @dev Updates the stored accumulated interest factor and the last update timestamp
     */
    function _updateAccumulatedInterestFactor () internal {
        storedAccInterestFactor = accumulatedInterestFactor();
        lastAccumulatedInterestUpdate = block.timestamp;
    }

    /**
     * @notice Internal function to calculate the utilization rate
     * @dev Utilization rate = Total Receivables / Total Assets
     * @param accInterestFactor The accumulated interest factor
     * @return The utilization rate in WAD (1e18) precision
     */
    function _utilizationRate(uint accInterestFactor) internal view returns (uint) {
        uint totalReceivables_ = _totalReceivables(accInterestFactor);
        uint totalAssets_ = totalReceivables_ + IERC20(asset()).balanceOf(address(this));
        return totalReceivables_.mulDiv(WAD, totalAssets_);
    }

    /**
     * @notice Internal function to calculate the total receivables
     * @dev Total receivables = scaled receivables * accumulated interest factor
     * @param accInterestFactor The accumulated interest factor
     * @return The total receivables amount
     */
    function _totalReceivables(uint accInterestFactor) internal view returns (uint) {
        return scaledReceivables.mulDiv(accInterestFactor, WAD);
    }

    /**
     * @notice Internal function to calculate the base debt for a borrower
     * @dev Base debt = scaled debt * accumulated interest factor
     * @param borrower The borrower's address
     * @param accInterestFactor The accumulated interest factor
     * @return The base debt amount for the borrower
     */
    function _baseDebt(address borrower, uint accInterestFactor) internal view returns (uint) {
        return borrowers[borrower].scaledDebt.mulDiv(accInterestFactor, WAD);
    }

    /**
     * @notice Internal function to calculate the penalty debt for a borrower
     * @dev Penalty debt = base debt * penalty time * penalty rate
     * @param borrower The borrower's address
     * @param accInterestFactor The accumulated interest factor
     * @return The penalty debt amount for the borrower
     */
    function _penaltyDebt(address borrower, uint accInterestFactor) internal view returns (uint) {
        uint penaltyTime_ = penaltyTime(borrower);
        if (penaltyTime_ == 0) return 0;

        return (_baseDebt(borrower, accInterestFactor) * penaltyTime_).mulDiv(params.penaltyRate(), WAD);
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library WadMath {

    uint256 internal constant WAD = 1e18;
    uint256 internal constant halfWAD = WAD / 2;

    function wad() internal pure returns (uint256) {
        return WAD;
    }

    function halfWad() internal pure returns (uint256) {
        return halfWAD;
    }

    function wadPow(uint256 x, uint256 n) internal pure returns (uint256 z) {
        z = WAD;

        while (n != 0) {
            uint256 acc = x;

            for (uint8 i = 0; i < 4; ++i) {
                if ((n & (1 << i)) != 0) {
                    z = (z * acc + halfWAD) / WAD;
                }
                acc = (acc * acc + halfWAD) / WAD;
            }

            n >>= 4;

            x = acc;
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

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

interface IInventoryPool01 {
    event Borrowed(address indexed borrower, address indexed recipient, uint amount);
    event PenaltyRepayment(address indexed borrower, uint penaltyDebt, uint penaltyPaymentAmount);
    event BaseDebtRepayment(address indexed borrower, uint baseDebt, uint baseDebtPaymentAmount);
    event ParamsContractUpgraded(IInventoryPoolParams01 indexed paramsContract);

    error Expired();
    error NoDebt();
    error ZeroRepayment();
    error InsufficientLiquidity();
    error WrongChainId(uint chainId);
    error ParamsContractNotChanged();

    function borrow(uint amount, address borrower, address recipient, uint expiry, uint chainId) external;
    function repay(uint amount, address borrower) external;
    function upgradeParamsContract(IInventoryPoolParams01 paramsContract) external;

    function totalAssets() external view returns (uint);
    function totalReceivables() external view returns (uint);
    function utilizationRate() external view returns (uint);
    function baseDebt(address borrower) external view returns (uint);
    function penaltyDebt(address borrower) external view returns (uint);
    function penaltyTime(address borrower) external view returns (uint);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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²56 and mod 2²56 - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²56 + 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²56. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

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

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

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

            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²56 / 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²56. Now that denominator is an odd number, it has an inverse modulo 2²56 such
            // that denominator * inv = 1 mod 2²56. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 24.
            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 28
            inverse *= 2 - denominator * inverse; // inverse mod 2¹6
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 264
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²8
            inverse *= 2 - denominator * inverse; // inverse mod 2²56

            // 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²56. Since the preconditions guarantee that the outcome is
            // less than 2²56, 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;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax = 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) = 1 mod p`. As a consequence, we have `a * a**(p-2) = 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `e_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) = sqrt(a) < 2**e`). We know that `e = 128` because `(2¹²8)² = 2²56` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) = sqrt(a) < 2**e ? (2**(e-1))² = a < (2**e)² ? 2**(2*e-2) = a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) = sqrt(a) < 2**e = 2 * x_n`. This implies e_n = 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to e_n = 2**(e-2).
            // This is going to be our x_0 (and e_0)
            xn = (3 * xn) >> 1; // e_0 := | x_0 - sqrt(a) | = 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n4 + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n4 + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n4 - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              = 0
            // Which proves that for all n = 1, sqrt(a) = x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // e_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | e_n² / (2 * x_n) |
            //         = e_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // e_1 = e_0² / | (2 * x_0) |
            //     = (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     = 2**(2*e-4) / (3 * 2**(e-1))
            //     = 2**(e-3) / 3
            //     = 2**(e-3-log2(3))
            //     = 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) = sqrt(a) = x_n:
            // e_{n+1} = e_n² / | (2 * x_n) |
            //         = (2**(e-k))² / (2 * 2**(e-1))
            //         = 2**(2*e-2*k) / 2**e
            //         = 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // e_1 := | x_1 - sqrt(a) | = 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // e_2 := | x_2 - sqrt(a) | = 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // e_3 := | x_3 - sqrt(a) | = 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // e_4 := | x_4 - sqrt(a) | = 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // e_5 := | x_5 - sqrt(a) | = 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // e_6 := | x_6 - sqrt(a) | = 2**(e-144)  -- general case with k = 72

            // Because e = 128 (as discussed during the first estimation phase), we know have reached a precision
            // e_6 = 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @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;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @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;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 recovered, RecoverError err, bytes32 errArg) {
        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.
            assembly ("memory-safe") {
                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[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        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 recovered, RecoverError err, bytes32 errArg) {
        // 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);
        }
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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

pragma solidity ^0.8.20;

import {IAccessControlEnumerable} from "./IAccessControlEnumerable.sol";
import {AccessControl} from "../AccessControl.sol";
import {EnumerableSet} from "../../utils/structs/EnumerableSet.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 role => EnumerableSet.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual returns (uint256) {
        return _roleMembers[role].length();
    }

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

    /**
     * @dev Overload {AccessControl-_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool granted = super._grantRole(role, account);
        if (granted) {
            _roleMembers[role].add(account);
        }
        return granted;
    }

    /**
     * @dev Overload {AccessControl-_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) {
        bool revoked = super._revokeRole(role, account);
        if (revoked) {
            _roleMembers[role].remove(account);
        }
        return revoked;
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    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 The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @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;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    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 Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

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

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(buffer, add(0x20, offset)))
        }
    }
}

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

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

File 13 of 41 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(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 {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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;
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface ICollateralPool01 {
    event Deposited(address indexed depositor, IERC20 indexed token, uint amount);
    event WithdrawRequested(address indexed depositor, uint indexed nonce, uint startTime, IERC20 indexed token, uint amount);
    event WithdrawCompleted(address indexed depositor, uint indexed nonce, IERC20 indexed token, uint amount);
    event WithdrawPeriodUpdated(uint newWithdrawPeriod);
    event BalanceLiquidated(address indexed depositor, IERC20 indexed token, uint amount, address recipient);
    event WithdrawLiquidated(address indexed depositor, uint indexed nonce, IERC20 indexed token, uint amount, address recipient);

    error InsufficientBalance(uint balance);
    error NothingToWithdraw();
    error WithdrawNotReady(uint withdrawReadyTime);
    error WithdrawAmountZero();
    error InsufficientLiquidity(uint amount);
    error PeriodNotChanged();

    function deposit(IERC20 token, uint amount) external;
    function startWithdraw(IERC20 token, uint amount) external;
    function withdraw(uint nonce) external;
    function liquidateBalance(address depositor, IERC20 token, uint amount, address recipient) external;
    function liquidateWithdraw(uint nonce, address depositor, uint amount, address recipient) external;
    function updateWithdrawPeriod(uint newWithdrawPeriod) external;

    function withdrawPeriod() external view returns (uint);
    function tokenBalance(address depositor, IERC20 token) external view returns (uint);
    function tokenWithdraws(address depositor, uint nonce) external view returns (IERC20 token, uint startTime, uint amount);
    function withdrawNonce(address depositor) external view returns (uint);
}

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

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

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

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

    /**
     * @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 {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @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) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/*=================================================================================================*
 *   Nomial::OwnableParams01.sol                                                                   *
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
 *   ____________________ ______(_)_____ ___  /                                                    *
 *   __  __ \  __ \_  __ `__ \_  /_  __ `/_  /                                                     *
 *   _  / / / /_/ /  / / / / /  / / /_/ /_  /                                                      *
 *   /_/ /_/\____//_/ /_/ /_//_/  \__,_/ /_/                                                       *
 *=================================================================================================*/

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IInventoryPoolParams01} from "./interfaces/IInventoryPoolParams01.sol";

/**
 * @title OwnableParams01
 * @dev A parameter management contract for inventory pools that implements IInventoryPoolParams01
 * and inherits OpenZeppelin's Ownable for access control. This contract provides fixed parameters
 * that can be updated by the owner, including base fee, interest rate, penalty rate, and penalty period.
 * All rates are expressed in WAD (1e18) precision.
 */
contract OwnableParams01 is IInventoryPoolParams01, Ownable {
    /** @dev The base fee charged on new borrows, stored in WAD (1e18) precision */
    uint private _baseFee;

    /** @dev The fixed interest rate per second for loans, stored in WAD (1e18) precision */
    uint private _interestRate;

    /** @dev The penalty interest rate per second charged on overdue loans, stored in WAD (1e18) precision */
    uint private _penaltyRate;

    /** @dev The grace period before penalties apply (in seconds) */
    uint private _penaltyPeriod;

    /** @dev Emitted when the base fee is updated
     * @param oldBaseFee The previous base fee value
     * @param newBaseFee The new base fee value
     */
    event BaseFeeUpdated(uint oldBaseFee, uint newBaseFee);

    /** @dev Emitted when the interest rate is updated
     * @param oldInterestRate The previous interest rate value
     * @param newInterestRate The new interest rate value
     */
    event InterestRateUpdated(uint oldInterestRate, uint newInterestRate);

    /** @dev Emitted when the penalty rate is updated
     * @param oldPenaltyRate The previous penalty rate value
     * @param newPenaltyRate The new penalty rate value
     */
    event PenaltyRateUpdated(uint oldPenaltyRate, uint newPenaltyRate);

    /** @dev Emitted when the penalty period is updated
     * @param oldPenaltyPeriod The previous penalty period value
     * @param newPenaltyPeriod The new penalty period value
     */
    event PenaltyPeriodUpdated(uint oldPenaltyPeriod, uint newPenaltyPeriod);

    /**
     * @notice Initializes the contract with initial parameter values and owner
     * @dev Sets up all parameters and emits events for initial values
     * @param baseFee_ Initial base fee value, in WAD (1e18) precision
     * @param interestRate_ Initial interest rate value, in WAD (1e18) precision
     * @param penaltyRate_ Initial penalty rate value, in WAD (1e18) precision
     * @param penaltyPeriod_ Initial penalty period value, in seconds
     * @param owner Address that will be granted ownership of the contract
     */
    constructor(
        uint baseFee_,
        uint interestRate_,
        uint penaltyRate_,
        uint penaltyPeriod_,
        address owner
    ) Ownable(owner) {
        _baseFee = baseFee_;
        _interestRate = interestRate_;
        _penaltyRate = penaltyRate_;
        _penaltyPeriod = penaltyPeriod_;

        emit BaseFeeUpdated(0, baseFee_);
        emit InterestRateUpdated(0, interestRate_);
        emit PenaltyRateUpdated(0, penaltyRate_);
        emit PenaltyPeriodUpdated(0, penaltyPeriod_);
    }

    /**
     * @notice Returns the current base fee
     * @dev The base fee is charged upfront when a new borrow is created
     * @return The base fee value in WAD (1e18) precision
     */
    function baseFee() external view returns (uint) {
        return _baseFee;
    }

    /**
     * @notice Returns the current interest rate
     * @dev The interest rate accrues debt based on the time a borrower holds a loan
     * @param utilizationRate The utilization rate for the inventory pool (unused in this implementation)
     * @return The interest rate per second in WAD (1e18) precision
     */
    function interestRate(uint utilizationRate) external view returns (uint) {
        return _interestRate;
    }

    /**
     * @notice Returns the current penalty rate
     * @dev The penalty rate is added on top of the regular interest rate when a loan
     * exceeds the penalty period. Penalty rate is persecond in WAD (1e18) precision
     * @return The penalty rate per second in WAD (1e18) precision
     */
    function penaltyRate() external view returns (uint) {
        return _penaltyRate;
    }

    /**
     * @notice Returns the current penalty period
     * @dev The penalty period defines how many seconds a borrower has to repay their loan before
     * additional penalty interest starts accruing
     * @return The penalty period value in seconds
     */
    function penaltyPeriod() external view returns (uint) {
        return _penaltyPeriod;
    }

    /**
     * @notice Updates the base fee to a new value
     * @dev Only callable by the contract owner
     * @param newBaseFee The new base fee value in WAD (1e18) precision
     */
    function updateBaseFee(uint newBaseFee) external onlyOwner {
        emit BaseFeeUpdated(_baseFee, newBaseFee);
        _baseFee = newBaseFee;
    }

    /**
     * @notice Updates the interest rate to a new value
     * @dev Only callable by the contract owner
     * @param newInterestRate The new interest rate value in WAD (1e18) precision
     */
    function updateInterestRate(uint newInterestRate) external onlyOwner {
        emit InterestRateUpdated(_interestRate, newInterestRate);
        _interestRate = newInterestRate;
    }

    /**
     * @notice Updates the penalty rate to a new value
     * @dev Only callable by the contract owner
     * @param newPenaltyRate The new penalty rate value in WAD (1e18) precision
     */
    function updatePenaltyRate(uint newPenaltyRate) external onlyOwner {
        emit PenaltyRateUpdated(_penaltyRate, newPenaltyRate);
        _penaltyRate = newPenaltyRate;
    }

    /**
     * @notice Updates the penalty period to a new value
     * @dev Only callable by the contract owner
     * @param newPenaltyPeriod The new penalty period value in seconds
     */
    function updatePenaltyPeriod(uint newPenaltyPeriod) external onlyOwner {
        emit PenaltyPeriodUpdated(_penaltyPeriod, newPenaltyPeriod);
        _penaltyPeriod = newPenaltyPeriod;
    }
}

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

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.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.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @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].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, 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
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

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

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

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

pragma solidity ^0.8.20;

import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";

/**
 * @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
 * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
 * the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
 * contract and not the "assets" token which is an independent contract.
 *
 * [CAUTION]
 * ====
 * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
 * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
 * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
 * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
 * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
 * verifying the amount received is as expected, using a wrapper that performs these checks such as
 * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
 *
 * Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
 * The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
 * and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
 * itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
 * offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
 * of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
 * With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
 * underlying math can be found xref:erc4626.adoc#inflation-attack[here].
 *
 * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
 * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
 * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
 * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
 * `_convertToShares` and `_convertToAssets` functions.
 *
 * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
 * ====
 */
abstract contract ERC4626 is ERC20, IERC4626 {
    using Math for uint256;

    IERC20 private immutable _asset;
    uint8 private immutable _underlyingDecimals;

    /**
     * @dev Attempted to deposit more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);

    /**
     * @dev Attempted to mint more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);

    /**
     * @dev Attempted to withdraw more assets than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);

    /**
     * @dev Attempted to redeem more shares than the max amount for `receiver`.
     */
    error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);

    /**
     * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
     */
    constructor(IERC20 asset_) {
        (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
        _underlyingDecimals = success ? assetDecimals : 18;
        _asset = asset_;
    }

    /**
     * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
     */
    function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
        (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
            abi.encodeCall(IERC20Metadata.decimals, ())
        );
        if (success && encodedDecimals.length >= 32) {
            uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
            if (returnedDecimals <= type(uint8).max) {
                return (true, uint8(returnedDecimals));
            }
        }
        return (false, 0);
    }

    /**
     * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
     * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
     * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
     *
     * See {IERC20Metadata-decimals}.
     */
    function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
        return _underlyingDecimals + _decimalsOffset();
    }

    /** @dev See {IERC4626-asset}. */
    function asset() public view virtual returns (address) {
        return address(_asset);
    }

    /** @dev See {IERC4626-totalAssets}. */
    function totalAssets() public view virtual returns (uint256) {
        return _asset.balanceOf(address(this));
    }

    /** @dev See {IERC4626-convertToShares}. */
    function convertToShares(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-convertToAssets}. */
    function convertToAssets(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-maxDeposit}. */
    function maxDeposit(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxMint}. */
    function maxMint(address) public view virtual returns (uint256) {
        return type(uint256).max;
    }

    /** @dev See {IERC4626-maxWithdraw}. */
    function maxWithdraw(address owner) public view virtual returns (uint256) {
        return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-maxRedeem}. */
    function maxRedeem(address owner) public view virtual returns (uint256) {
        return balanceOf(owner);
    }

    /** @dev See {IERC4626-previewDeposit}. */
    function previewDeposit(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-previewMint}. */
    function previewMint(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Ceil);
    }

    /** @dev See {IERC4626-previewWithdraw}. */
    function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
        return _convertToShares(assets, Math.Rounding.Ceil);
    }

    /** @dev See {IERC4626-previewRedeem}. */
    function previewRedeem(uint256 shares) public view virtual returns (uint256) {
        return _convertToAssets(shares, Math.Rounding.Floor);
    }

    /** @dev See {IERC4626-deposit}. */
    function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
        uint256 maxAssets = maxDeposit(receiver);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
        }

        uint256 shares = previewDeposit(assets);
        _deposit(_msgSender(), receiver, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-mint}. */
    function mint(uint256 shares, address receiver) public virtual returns (uint256) {
        uint256 maxShares = maxMint(receiver);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
        }

        uint256 assets = previewMint(shares);
        _deposit(_msgSender(), receiver, assets, shares);

        return assets;
    }

    /** @dev See {IERC4626-withdraw}. */
    function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxAssets = maxWithdraw(owner);
        if (assets > maxAssets) {
            revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
        }

        uint256 shares = previewWithdraw(assets);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return shares;
    }

    /** @dev See {IERC4626-redeem}. */
    function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
        uint256 maxShares = maxRedeem(owner);
        if (shares > maxShares) {
            revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
        }

        uint256 assets = previewRedeem(shares);
        _withdraw(_msgSender(), receiver, owner, assets, shares);

        return assets;
    }

    /**
     * @dev Internal conversion function (from assets to shares) with support for rounding direction.
     */
    function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
        return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
    }

    /**
     * @dev Internal conversion function (from shares to assets) with support for rounding direction.
     */
    function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
        return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
    }

    /**
     * @dev Deposit/mint common workflow.
     */
    function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
        // If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
        // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
        // assets are transferred and before the shares are minted, which is a valid state.
        // slither-disable-next-line reentrancy-no-eth
        SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
        _mint(receiver, shares);

        emit Deposit(caller, receiver, assets, shares);
    }

    /**
     * @dev Withdraw/redeem common workflow.
     */
    function _withdraw(
        address caller,
        address receiver,
        address owner,
        uint256 assets,
        uint256 shares
    ) internal virtual {
        if (caller != owner) {
            _spendAllowance(owner, caller, shares);
        }

        // If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
        // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
        // calls the vault, which is assumed not malicious.
        //
        // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
        // shares are burned and after the assets are transferred, which is a valid state.
        _burn(owner, shares);
        SafeERC20.safeTransfer(_asset, receiver, assets);

        emit Withdraw(caller, receiver, owner, assets, shares);
    }

    function _decimalsOffset() internal view virtual returns (uint8) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-20 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);
}

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

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        assembly ("memory-safe") {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC-165 detection.
 */
interface IAccessControlEnumerable is IAccessControl {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-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) {
        assembly ("memory-safe") {
            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 ERC-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 ERC-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 (ERC-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) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

/*=================================================================================================*
 *   Nomial::CollateralPool01.sol                                                                  *
 *~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*
 *   ____________________ ______(_)_____ ___  /                                                    *
 *   __  __ \  __ \_  __ `__ \_  /_  __ `/_  /                                                     *
 *   _  / / / /_/ /  / / / / /  / / /_/ /_  /                                                      *
 *   /_/ /_/\____//_/ /_/ /_//_/  \__,_/ /_/                                                       *
 *=================================================================================================*/

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {ICollateralPool01} from "./interfaces/ICollateralPool01.sol";

/**
 * @title CollateralPool01
 * @dev A contract for managing collateral deposits and withdrawals of multiple ERC20 tokens.
 * Features include:
 * - Deposit of any ERC20 token
 * - Time-locked withdrawals with configurable withdrawal period
 * - Balance and withdrawal liquidation by owner
 * The contract maintains separate balances for each depositor and token,
 * and implements a two-step withdrawal process to allow for time-locked withdrawals.
 */
contract CollateralPool01 is ICollateralPool01, Ownable, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    /**
     * @dev Represents a pending withdrawal request
     * @param token The ERC20 token being withdrawn
     * @param startTime The timestamp when the withdrawal request was initiated
     * @param amount The amount of tokens requested for withdrawal
     */
    struct TokenWithdraw {
        IERC20 token;
        uint startTime;
        uint amount;
    }

    /**
     * @dev Stores a depositor's token balances, withdrawal requests, and withdrawal nonce
     * @param tokenBalance Stores a depositor's token balances
     * @param tokenWithdraws Stores a depositor's withdrawal requests
     * @param withdrawNonce A unique identifier that increments when the depositor makes a new withdrawal request
     */
    struct Depositor {
        mapping(IERC20 => uint) tokenBalance;
        mapping(uint => TokenWithdraw) tokenWithdraws;
        uint withdrawNonce;
    }

    /// @notice The time period (in seconds) that must elapse between requesting and executing a withdrawal
    uint public withdrawPeriod;

    /// @dev Internal mapping to store depositor data
    mapping(address => Depositor) internal depositors;

    /**
     * @notice Initializes the collateral pool with an owner and withdrawal period
     * @param owner The address that can liquidate balances and withdrawals
     * @param initialWithdrawPeriod The time period (in seconds) that must elapse between requesting and executing a withdrawal
     */
    constructor(
        address owner,
        uint initialWithdrawPeriod
    ) Ownable(owner) {
        withdrawPeriod = initialWithdrawPeriod;

        emit WithdrawPeriodUpdated(initialWithdrawPeriod);
    }

    /**
     * @notice Deposits ERC20 tokens into the pool
     * @dev Transfers tokens from the sender to this contract and updates the sender's balance
     * @param token The ERC20 token to deposit
     * @param amount The amount of tokens to deposit
     * @custom:emits Deposited event with depositor address, token, and amount
     */
    function deposit(IERC20 token, uint amount) public nonReentrant() {
        depositors[msg.sender].tokenBalance[token] += amount;
        token.safeTransferFrom(msg.sender, address(this), amount);

        emit Deposited(msg.sender, token, amount);
    }

    /**
     * @notice Initiates a withdrawal request for tokens
     * @dev Starts the withdrawal timer and moves tokens from balance to pending withdrawal
     * @param token The ERC20 token to withdraw
     * @param amount The amount of tokens to withdraw
     * @custom:emits WithdrawRequested event with details of the withdrawal request
     * @custom:revert InsufficientBalance if the depositor's balance is less than the requested amount
     */
    function startWithdraw(IERC20 token, uint amount) public nonReentrant() {
        Depositor storage _depositor = depositors[msg.sender];
        uint _balance = _depositor.tokenBalance[token];
        if(_balance < amount) {
            revert InsufficientBalance(_balance);
        }

        if(amount == 0) {
            revert WithdrawAmountZero();
        }

        _depositor.tokenBalance[token] -= amount;
        _depositor.withdrawNonce += 1;
        uint _withdrawNonce = _depositor.withdrawNonce;
        _depositor.tokenWithdraws[_withdrawNonce] = TokenWithdraw(token, block.timestamp, amount);

        emit WithdrawRequested(msg.sender, _withdrawNonce, block.timestamp, token, amount);
    }

    /**
     * @notice Completes a withdrawal request after the withdrawal period has elapsed
     * @dev Transfers tokens to the withdrawer if the withdrawal period has passed
     * @param nonce The identifier of the withdrawal request to process
     * @custom:emits WithdrawCompleted event upon successful withdrawal
     * @custom:revert NothingToWithdraw if the withdrawal request doesn't exist
     * @custom:revert WithdrawNotReady if the withdrawal period hasn't elapsed
     */
    function withdraw(uint nonce) public nonReentrant() {
        Depositor storage _depositor = depositors[msg.sender];
        TokenWithdraw storage _tokenWithdraw = _depositor.tokenWithdraws[nonce];
        uint amount = _tokenWithdraw.amount;
        IERC20 token = _tokenWithdraw.token;

        if (amount == 0) {
            revert NothingToWithdraw();
        }

        uint withdrawReadyTime = _tokenWithdraw.startTime + withdrawPeriod;
        if (withdrawReadyTime > block.timestamp) {
            revert WithdrawNotReady(withdrawReadyTime);
        }

        delete _depositor.tokenWithdraws[nonce];
        token.safeTransfer(msg.sender, amount);

        emit WithdrawCompleted(msg.sender, nonce, token, amount);
    }

    /**
     * @notice Allows the owner to liquidate a depositor's token balance
     * @dev Transfers tokens from the depositor's balance to a specified recipient
     * @param depositor The address whose balance is being liquidated
     * @param token The ERC20 token to liquidate
     * @param amount The amount of tokens to liquidate
     * @param recipient The address that will receive the liquidated tokens
     * @custom:emits BalanceLiquidated event with liquidation details
     * @custom:revert InsufficientLiquidity if the depositor's balance is less than the liquidation amount
     */
    function liquidateBalance(address depositor, IERC20 token, uint amount, address recipient) public nonReentrant() onlyOwner() {
        Depositor storage _depositor = depositors[depositor];
        uint _balance = _depositor.tokenBalance[token];
        if(_balance < amount) {
            revert InsufficientLiquidity(_balance);
        }

        _depositor.tokenBalance[token] -= amount;
        token.safeTransfer(recipient, amount);

        emit BalanceLiquidated(depositor, token, amount, recipient);
    }

    /**
     * @notice Allows the owner to liquidate a pending withdrawal request
     * @dev Transfers tokens from a withdrawal request to a specified recipient
     * @param nonce The identifier of the withdrawal request to liquidate
     * @param depositor The address whose withdrawal is being liquidated
     * @param amount The amount of tokens to liquidate from the withdrawal
     * @param recipient The address that will receive the liquidated tokens
     * @custom:emits WithdrawLiquidated event with liquidation details
     * @custom:revert InsufficientLiquidity if the withdrawal amount is less than the liquidation amount
     */
    function liquidateWithdraw(uint nonce, address depositor, uint amount, address recipient) public nonReentrant() onlyOwner() {
        Depositor storage _depositor = depositors[depositor];
        TokenWithdraw storage _tokenWithdraw = _depositor.tokenWithdraws[nonce];
        uint _withdrawAmount = _tokenWithdraw.amount;
        if (_withdrawAmount < amount) {
            revert InsufficientLiquidity(_withdrawAmount);
        }

        IERC20 token = _tokenWithdraw.token;
        if (_withdrawAmount == amount) {
            delete _depositor.tokenWithdraws[nonce];
        } else {
            _tokenWithdraw.amount -= amount;
        }
        token.safeTransfer(recipient, amount);

        emit WithdrawLiquidated(depositor, nonce, token, amount, recipient);
    }

    /**
     * @notice Updates the withdrawal period
     * @dev Can only be called by the owner
     * @param newWithdrawPeriod The new withdrawal period in seconds
     * @custom:emits WithdrawPeriodUpdated event with the new period
     */
    function updateWithdrawPeriod(uint newWithdrawPeriod) public onlyOwner() {
        if (withdrawPeriod == newWithdrawPeriod) {
            revert PeriodNotChanged();
        }

        withdrawPeriod = newWithdrawPeriod;

        emit WithdrawPeriodUpdated(newWithdrawPeriod);
    }

    /**
     * @notice Returns the depositor's balance of a token
     * @dev Retrieves the current balance of a token from the depositors mapping
     * @param depositor The depositor's address
     * @param token The ERC20 token address
     * @return The depositor's balance of the token
     */
    function tokenBalance(address depositor, IERC20 token) public view returns (uint) {
        return depositors[depositor].tokenBalance[token];
    }

    /**
     * @notice Returns the details of a specific withdrawal request made by a depositor
     * @dev Retrieves the token, start time, and amount for a given depositor and withdrawal nonce
     * @param depositor The depositor's address
     * @param nonce Unique identifier of the withdrawal request
     * @return token The ERC20 token being withdrawn
     * @return startTime The timestamp when the withdrawal request was initiated
     * @return amount The amount of tokens requested for withdrawal
     */
    function tokenWithdraws(address depositor, uint nonce) public view returns (IERC20 token, uint startTime, uint amount) {
        TokenWithdraw memory _tokenWithdraw = depositors[depositor].tokenWithdraws[nonce];
        return (_tokenWithdraw.token, _tokenWithdraw.startTime, _tokenWithdraw.amount);
    }

    /**
     * @notice Returns the current withdrawal nonce for a depositor
     * @dev This nonce starts at 0 and increments with each new withdrawal request
     * @param depositor The depositor's address
     * @return The current withdrawal nonce for the depositor
     */
    function withdrawNonce(address depositor) public view returns (uint) {
        return depositors[depositor].withdrawNonce;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

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

File 31 of 41 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @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.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

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

    /**
     * @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 revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 34 of 41 : 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
        );
}

File 35 of 41 : IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";

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

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    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 Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            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 silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IInventoryPoolParams01 {
    error InvalidUtilizationRate(uint utilizationRate);

    function baseFee() external view returns (uint);
    function interestRate(uint utilizationRate) external view returns (uint);
    function penaltyRate() external view returns (uint);
    function penaltyPeriod() external view returns (uint);
}

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

pragma solidity ^0.8.20;

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

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import {IInventoryPoolParams01} from "./IInventoryPoolParams01.sol";
import {InventoryPool01} from "../InventoryPool01.sol";
import {OwnableParams01} from "../OwnableParams01.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";

interface IInventoryPoolAccessManager01 is IAccessControl {
    event SignatureThresholdUpdated(uint16 newSignatureThreshold);

    error SignatureUsed(bytes32 sigHash);
    error SignatureThresholdTooLow(uint16 newSignatureThreshold, uint validatorCount);
    error SignatureThresholdTooHigh(uint16 newSignatureThreshold, uint validatorCount);
    error GrantRoleNotAllowed();
    error RevokeRoleNotAllowed();
    error RenounceRoleNotAllowed();
    error InvalidSignatureCount(uint validSignatures, uint requiredSignatures);
    error ValidatorNotUnique(address validator);
    error ValidatorExists(address validator);
    error ValidatorDoesNotExist(address validator);
    error BorrowerExists(address borrower);
    error BorrowerDoesNotExist(address borrower);
    error ZeroValidatorsNotAllowed();

    function VALIDATOR_ROLE() external view returns (bytes32);
    function BORROWER_ROLE() external view returns (bytes32);
    function validatorCount() external view returns (uint);
    function borrowerCount() external view returns (uint);
    function signatureThreshold() external view returns (uint16);
    function usedSigHashes(bytes32) external view returns (bool);
    function domainSeparator() external view returns (bytes32);
    function hashTypedData(bytes32 structHash) external view returns (bytes32);

    function borrow(InventoryPool01 pool, uint amount, address recipient, uint expiry, bytes32 salt, bytes[] calldata signatures) external;
    function forgiveDebt(InventoryPool01 pool, uint amount, address borrower, bytes32 salt, bytes[] calldata signatures) external;
    function updateBaseFee(OwnableParams01 paramsContract, uint newBaseFee, bytes32 salt, bytes[] calldata signatures) external;
    function updateInterestRate(OwnableParams01 paramsContract, uint newInterestRate, bytes32 salt, bytes[] calldata signatures) external;
    function updatePenaltyRate(OwnableParams01 paramsContract, uint newPenaltyRate, bytes32 salt, bytes[] calldata signatures) external;
    function updatePenaltyPeriod(OwnableParams01 paramsContract, uint newPenaltyPeriod, bytes32 salt, bytes[] calldata signatures) external;
    function upgradeParamsContract(InventoryPool01 pool, IInventoryPoolParams01 paramsContract, bytes32 salt, bytes[] calldata signatures) external;
    function overwriteCoreState(InventoryPool01 pool, uint newStoredAccInterestFactor, uint newLastAccumulatedInterestUpdate, uint newScaledReceivables, bytes32 salt, bytes[] calldata signatures) external;
    function transferOwnership(Ownable ownedContract, address newOwner, bytes32 salt, bytes[] calldata signatures) external;
    function addValidator(address validator, uint16 newSignatureThreshold, bytes32 salt, bytes[] calldata signatures) external;
    function removeValidator(address validator, uint16 newSignatureThreshold, bytes32 salt, bytes[] calldata signatures) external;
    function addBorrower(address borrower, bytes32 salt, bytes[] calldata signatures) external;
    function removeBorrower(address borrower, bytes32 salt, bytes[] calldata signatures) external;
    function setSignatureThreshold(uint16 newSignatureThreshold, bytes32 salt, bytes[] calldata signatures) external;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Settings
{
  "evmVersion": "prague",
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "abi"
      ]
    }
  },
  "remappings": [
    "forge-std/=deploy/forge-std/src/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@nomial-contracts-v1/=deploy/nomial-contracts-v1/src/",
    "nomial-contracts-v1/=deploy/nomial-contracts-v1/src/"
  ],
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"address[]","name":"validators","type":"address[]"},{"internalType":"address[]","name":"borrowers","type":"address[]"},{"internalType":"uint16","name":"signatureThreshold_","type":"uint16"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"}],"name":"BorrowerDoesNotExist","type":"error"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"}],"name":"BorrowerExists","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[],"name":"GrantRoleNotAllowed","type":"error"},{"inputs":[],"name":"InvalidShortString","type":"error"},{"inputs":[{"internalType":"uint256","name":"validSignatures","type":"uint256"},{"internalType":"uint256","name":"requiredSignatures","type":"uint256"}],"name":"InvalidSignatureCount","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[],"name":"RenounceRoleNotAllowed","type":"error"},{"inputs":[],"name":"RevokeRoleNotAllowed","type":"error"},{"inputs":[{"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"},{"internalType":"uint256","name":"validatorCount","type":"uint256"}],"name":"SignatureThresholdTooHigh","type":"error"},{"inputs":[{"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"},{"internalType":"uint256","name":"validatorCount","type":"uint256"}],"name":"SignatureThresholdTooLow","type":"error"},{"inputs":[{"internalType":"bytes32","name":"sigHash","type":"bytes32"}],"name":"SignatureUsed","type":"error"},{"inputs":[{"internalType":"string","name":"str","type":"string"}],"name":"StringTooLong","type":"error"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"ValidatorDoesNotExist","type":"error"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"ValidatorExists","type":"error"},{"inputs":[{"internalType":"address","name":"validator","type":"address"}],"name":"ValidatorNotUnique","type":"error"},{"inputs":[],"name":"ZeroValidatorsNotAllowed","type":"error"},{"anonymous":false,"inputs":[],"name":"EIP712DomainChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"}],"name":"SignatureThresholdUpdated","type":"event"},{"inputs":[],"name":"ADD_BORROWER_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ADD_VALIDATOR_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BORROWER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BORROW_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FORGIVE_DEBT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATE_BALANCE_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIQUIDATE_WITHDRAW_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"OVERWRITE_CORE_STATE_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REMOVE_BORROWER_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"REMOVE_VALIDATOR_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"SET_SIGNATURE_THRESHOLD_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TRANSFER_OWNERSHIP_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPDATE_BASE_FEE_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPDATE_INTEREST_RATE_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPDATE_PENALTY_PERIOD_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPDATE_PENALTY_RATE_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPDATE_WITHDRAW_PERIOD_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_PARAMS_CONTRACT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VALIDATOR_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"addBorrower","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"},{"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"addValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract InventoryPool01","name":"pool","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"expiry","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"borrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowerCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"domainSeparator","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"eip712Domain","outputs":[{"internalType":"bytes1","name":"fields","type":"bytes1"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"version","type":"string"},{"internalType":"uint256","name":"chainId","type":"uint256"},{"internalType":"address","name":"verifyingContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"uint256[]","name":"extensions","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract InventoryPool01","name":"pool","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"borrower","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"forgiveDebt","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"getRoleMember","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMemberCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleMembers","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"structHash","type":"bytes32"}],"name":"hashTypedData","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract CollateralPool01","name":"pool","type":"address"},{"internalType":"address","name":"depositor","type":"address"},{"internalType":"contract IERC20","name":"token","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"liquidateBalance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract CollateralPool01","name":"pool","type":"address"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"address","name":"depositor","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"liquidateWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract InventoryPool01","name":"pool","type":"address"},{"internalType":"uint256","name":"newStoredAccInterestFactor","type":"uint256"},{"internalType":"uint256","name":"newLastAccumulatedInterestUpdate","type":"uint256"},{"internalType":"uint256","name":"newScaledReceivables","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"overwriteCoreState","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"removeBorrower","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"validator","type":"address"},{"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"removeValidator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"newSignatureThreshold","type":"uint16"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"setSignatureThreshold","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"signatureThreshold","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract Ownable","name":"ownedContract","type":"address"},{"internalType":"address","name":"newOwner","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract OwnableParams01","name":"paramsContract","type":"address"},{"internalType":"uint256","name":"newBaseFee","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"updateBaseFee","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract OwnableParams01","name":"paramsContract","type":"address"},{"internalType":"uint256","name":"newInterestRate","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"updateInterestRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract OwnableParams01","name":"paramsContract","type":"address"},{"internalType":"uint256","name":"newPenaltyPeriod","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"updatePenaltyPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract OwnableParams01","name":"paramsContract","type":"address"},{"internalType":"uint256","name":"newPenaltyRate","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"updatePenaltyRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract CollateralPool01","name":"pool","type":"address"},{"internalType":"uint256","name":"newWithdrawPeriod","type":"uint256"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"updateWithdrawPeriod","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"contract InventoryPool01","name":"pool","type":"address"},{"internalType":"contract IInventoryPoolParams01","name":"paramsContract","type":"address"},{"internalType":"bytes32","name":"salt","type":"bytes32"},{"internalType":"bytes[]","name":"signatures","type":"bytes[]"}],"name":"upgradeParamsContract","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"usedSigHashes","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"validatorCount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

61016080604052346103e3576134c3803803809161001d82856103e7565b833981016080828203126103e3576100348261041e565b60208301516001600160401b0381116103e35782610053918501610432565b60408401519092906001600160401b0381116103e357606091610077918601610432565b9301519061ffff82168092036103e3576040516100956060826103e7565b6023815260208101907f496e76656e746f7279506f6f6c44656661756c744163636573734d616e61676582526272303160e81b6040820152604051916100dc6040846103e7565b600183526020830191603160f81b83526100f5816104c9565b6101205261010284610664565b61014052519020918260e05251902080610100524660a0526040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261016b60c0826103e7565b5190206080523060c05261017e8161079c565b6103a1575b5061ffff82511615610392575f5b825181101561020f576001600160a01b036101ac82856104a1565b51166101b781610812565b806101dd575b156101cb5750600101610191565b634c97322f60e11b5f5260045260245ffd5b5f5160206134035f395f51905f525f526001602052610209825f5160206134435f395f51905f52610912565b506101bd565b50825f5b81518110156102a4576001600160a01b0361022e82846104a1565b511661023981610892565b8061025f575b1561024d5750600101610213565b6364dca79960e01b5f5260045260245ffd5b5f5160206134235f395f51905f525f52600160205261029e827f37796693c9136991966ecabeb225dddf75f7ae82d42c98571afc1843b5b26acd610912565b5061023f565b5f5160206134035f395f51905f525f52600160208190525f5160206134435f395f51905f525490849082901c81116102eb5763e97165e960e01b5f5260045260245260445ffd5b9080821161037c577fa31c29b707b2e58572a28de7d3e3f17fa5dd9e21a2c0eafe4174b214df4f36156020838061ffff196005541617600555604051908152a1604051612a74908161096f8239608051816121c5015260a05181612282015260c0518161218f015260e051816122140152610100518161223a01526101205181610f9801526101405181610fc20152f35b906374ba4b4560e01b5f5260045260245260445ffd5b63dd9347cf60e01b5f5260045ffd5b5f805260016020526103dc906001600160a01b03167fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49610912565b505f610183565b5f80fd5b601f909101601f19168101906001600160401b0382119082101761040a57604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b03821682036103e357565b9080601f830112156103e3578151916001600160401b03831161040a578260051b906040519361046560208401866103e7565b84526020808501928201019283116103e357602001905b8282106104895750505090565b602080916104968461041e565b81520191019061047c565b80518210156104b55760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b908151602081105f14610543575090601f8151116105035760208151910151602082106104f4571790565b5f198260200360031b1b161790565b604460209160405192839163305a27a960e01b83528160048401528051918291826024860152018484015e5f828201840152601f01601f19168101030190fd5b6001600160401b03811161040a57600254600181811c9116801561065a575b602082101461064657601f8111610613575b50602092601f82116001146105b257928192935f926105a7575b50508160011b915f199060031b1c19161760025560ff90565b015190505f8061058e565b601f1982169360025f52805f20915f5b8681106105fb57508360019596106105e3575b505050811b0160025560ff90565b01515f1960f88460031b161c191690555f80806105d5565b919260206001819286850151815501940192016105c2565b60025f52601f60205f20910160051c810190601f830160051c015b81811061063b5750610574565b5f815560010161062e565b634e487b7160e01b5f52602260045260245ffd5b90607f1690610562565b908151602081105f1461068f575090601f8151116105035760208151910151602082106104f4571790565b6001600160401b03811161040a57600354600181811c91168015610792575b602082101461064657601f811161075f575b50602092601f82116001146106fe57928192935f926106f3575b50508160011b915f199060031b1c19161760035560ff90565b015190505f806106da565b601f1982169360035f52805f20915f5b868110610747575083600195961061072f575b505050811b0160035560ff90565b01515f1960f88460031b161c191690555f8080610721565b9192602060018192868501518155019401920161070e565b60035f52601f60205f20910160051c810190601f830160051c015b81811061078757506106c0565b5f815560010161077a565b90607f16906106ae565b6001600160a01b0381165f9081525f5160206134a35f395f51905f52602052604090205460ff1661080d576001600160a01b03165f8181525f5160206134a35f395f51905f5260205260408120805460ff191660011790553391905f5160206133e35f395f51905f528180a4600190565b505f90565b6001600160a01b0381165f9081525f5160206134635f395f51905f52602052604090205460ff1661080d576001600160a01b03165f8181525f5160206134635f395f51905f5260205260408120805460ff191660011790553391905f5160206134035f395f51905f52905f5160206133e35f395f51905f529080a4600190565b6001600160a01b0381165f9081525f5160206134835f395f51905f52602052604090205460ff1661080d576001600160a01b03165f8181525f5160206134835f395f51905f5260205260408120805460ff191660011790553391905f5160206134235f395f51905f52905f5160206133e35f395f51905f529080a4600190565b6001810190825f528160205260405f2054155f146109675780546801000000000000000081101561040a57600181018083558110156104b5578390825f5260205f20015554915f5260205260405f2055600190565b5050505f9056fe6080806040526004361015610012575f80fd5b5f905f3560e01c9081630196a16a14611c195750806301ffc9a714611ba9578063097b59c314611b6f5780630bec174a14611a4a5780630cd2a4a114611a0f5780630e7b949e146119e75780630f43a677146119b3578063131681ba146118ae57806319c81e96146117e9578063248a9ca3146117bd57806325dd8b88146116b05780632ebfd2ea1461167c5780632f2ff15d1461165257806332aa71c31461162357806336568abe146115f957806351315ee21461151f578063558d2fff146113d4578063605429961461130f57806362c02a3f146112d4578063639b715e146111c65780636575f6aa146111a4578063697f0f9c146110f05780636f09c6b0146110b55780636fe814611461107a57806384b0196e14610f7e5780638d4d2db114610f435780639010d07c14610efd57806391d1485414610eb457806398c8ccb814610e795780639a916af414610e3e5780639d90810014610cfb578063a217fddf14610cdf578063a3246ad314610c2f578063a6e89af614610bf4578063a82f2e2614610bd2578063bbfdaf6b14610b97578063bc23474414610b5c578063c49baebe14610b34578063ca15c87314610b0a578063cb9ee111146109fe578063ccf51afb146109c3578063cd589e6c14610988578063d361baf01461094d578063d445d0e714610888578063d547741f1461085e578063e0438a3d14610799578063e1b0b147146106bf578063eba846f114610684578063f06b713714610593578063f698da2514610570578063f7eb261514610535578063f84553471461043c5763fb85f1cd14610265575f80fd5b346104065760c03660031901126104065761027e611c51565b906024359161028b611cc3565b926064359160a4356001600160401b038111610414576102af903690600401611c67565b95906102b9611e28565b5f5160206129e85f395f51905f52865260208681526040808820335f908152925290205460ff1615610418578596610397916103926040519560208701907fe1f1296627be0060124750977e9616f23b5d73a3c17504735acb15b3ba75eb3d825260018060a01b03169586604089015233606089015288608089015260018060a01b0316968760a08201528960c08201524660e0820152608435610100820152610100815261036a61012082611ddc565b51902061037561218c565b6042916040519161190160f01b8352600283015260228201522090565b611e85565b803b156104145784928360a492604051968795869463054de61b60e31b86526004860152336024860152604485015260648401524660848401525af18015610409576103f1575b505f516020612a285f395f51905f525d80f35b816103fb91611ddc565b61040657805f6103de565b80fd5b6040513d84823e3d90fd5b8480fd5b63e2517d3f60e01b8652336004525f5160206129e85f395f51905f52602452604486fd5b50346104065760803660031901126104065780610457611c51565b6024356064356001600160401b0381116105305761047c6104e9913690600401611c67565b90610485611e28565b61048e336122a8565b6103926040519560208701907f1fad5095fd65097f3b065eb0d4e3236a9703532cdf0ced3fd931e3ff38e9f023825260018060a01b03169687604082015286606082015260443560808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492639e35bf2160e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b5050fd5b505050fd5b503461040657806003193601126104065760206040517fefba6576b27217397aa763a8b62f960f85c09a08794fbf60c2d7d9cb27c8d9158152f35b5034610406578060031936011261040657602061058b61218c565b604051908152f35b50346104065761062261061d6105a836611d66565b906105b896949396959295611e28565b6105c1336122a8565b61039260405160208101907fe0143d71b08cb5463a713c5ae83827af5ae8d02e40eadea38b379b5efce5d775825260018060a01b0387169889604083015261ffff8b16606083015260808201526080815261036a60a082611ddc565b61277e565b8061065c575b1561064a5750610637906120d2565b805f516020612a285f395f51905f525d80f35b634c97322f60e11b8352600452602482fd5b5f5160206129c85f395f51905f528452600160205261067e826040862061296e565b50610628565b503461040657806003193601126104065760206040517f1847c693d194e1a100320ac1e36598ef73b3341774acd1424da6eeab108a48fd8152f35b50346104065761073b6107406106d436611d24565b906106e0959295611e28565b6106e9336122a8565b61039260405160208101907ff0fa648f2f6b39afca5a1dba358729fe1a2519d420d5c941498610fc9a8645d7825260018060a01b0387169889604083015260608201526060815261036a608082611ddc565b6126eb565b80610771575b1561075f5750805f516020612a285f395f51905f525d80f35b6364dca79960e01b8252600452602490fd5b5f5160206129e85f395f51905f5283526001602052610793826040852061296e565b50610746565b5034610406578061039261081b6107af36611cd9565b9294936107be96919296611e28565b6107c7336122a8565b60405160208101917fefba6576b27217397aa763a8b62f960f85c09a08794fbf60c2d7d9cb27c8d915835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492633a95285360e11b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760403660031901126104065760049061087b611c97565b5063ae83e1a360e01b8152fd5b5034610406578061039261090a61089e36611cd9565b9294936108ad96919296611e28565b6108b6336122a8565b60405160208101917f31beef549fa2fb06b369ed48b45a2edeb7617efbc57bacce26f5afdbd005cb64835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492630246820d60e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657806003193601126104065760206040517f63a5eb5ceb726bb49bd96516994883823b842a6156518ce2d0e0136103a758ce8152f35b503461040657806003193601126104065760206040517fe0143d71b08cb5463a713c5ae83827af5ae8d02e40eadea38b379b5efce5d7758152f35b503461040657806003193601126104065760206040517f9c0b53e2c61880f7d4bca4cce82818bb921f0d86f814cd1249439307d4bc29168152f35b50346104065760a03660031901126104065780610a19611c51565b602435610a24611cc3565b916084356001600160401b03811161041457610a47610ac3913690600401611c67565b90610a50611e28565b610a59336122a8565b6103926040519460208601907f9746d0b05fdd12543f6c1ef9696ac18afa4dc0130be3eddd0329e2bf53acda29825260018060a01b03169788604088015287606088015260018060a01b03169586608082015260643560a082015260a0815261036a60c082611ddc565b823b1561053057604484928360405195869485936395f7f34d60e01b8552600485015260248401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760203660031901126104065760406020916004358152600183522054604051908152f35b503461040657806003193601126104065760206040515f5160206129c85f395f51905f528152f35b503461040657806003193601126104065760206040517f7464b56e920567064f091785deccb66a4576616e1029ab267552e6509ee757228152f35b503461040657806003193601126104065760206040517ff0fa648f2f6b39afca5a1dba358729fe1a2519d420d5c941498610fc9a8645d78152f35b5034610406578060031936011261040657602061ffff60055416604051908152f35b503461040657806003193601126104065760206040517f675cf17ef722191a274d830b69382dac42e70f4f7218ca222a32aa3ae906c6c48152f35b5034610406576020366003190112610406576004358152600160205260408120604051908160208254918281520190819285526020852090855b818110610cc95750505082610c7f910383611ddc565b604051928392602084019060208552518091526040840192915b818110610ca7575050500390f35b82516001600160a01b0316845285945060209384019390920191600101610c99565b8254845260209093019260019283019201610c69565b5034610406578060031936011261040657602090604051908152f35b50346104065760e03660031901126104065780610d16611c51565b60243590610d22611cc3565b9160643592610d2f611cad565b9160c4356001600160401b038111610e3a57610d52610de4913690600401611c67565b90610d5b611e28565b610d64336122a8565b6103926040519760208901907f939642605c445f20f056667e4fef08a430d5d7a11f2015abf09af49c09a0b331825260018060a01b0316968760408b01528660608b015260018060a01b0316978860808b01528a60a08b015260018060a01b0316988960c082015260a43560e082015260e0815261036a61010082611ddc565b813b15610e36578560849281956040519788968795636fa7c1d760e01b875260048701526024860152604485015260648401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b8580fd5b8680fd5b503461040657806003193601126104065760206040517f9746d0b05fdd12543f6c1ef9696ac18afa4dc0130be3eddd0329e2bf53acda298152f35b503461040657806003193601126104065760206040517fe1f1296627be0060124750977e9616f23b5d73a3c17504735acb15b3ba75eb3d8152f35b5034610406576040366003190112610406576040610ed0611c97565b91600435815280602052209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b503461040657604036600319011261040657610f2a60209160043581526001835260406024359120612501565b905460405160039290921b1c6001600160a01b03168152f35b503461040657806003193601126104065760206040517f95c8a14d53e1bab3e3fe7f0c3e904f7d307f154ddeae3f4b87c59df3306fbfab8152f35b503461040657806003193601126104065761101e90610fbc7f0000000000000000000000000000000000000000000000000000000000000000612308565b90610fe67f0000000000000000000000000000000000000000000000000000000000000000612431565b90602061102c60405193610ffa8386611ddc565b8385525f368137604051968796600f60f81b885260e08589015260e0880190611db8565b908682036040880152611db8565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061106357505050500390f35b835185528695509381019392810192600101611054565b503461040657806003193601126104065760206040517f95c38268b5649f06a6f6d39a8832927e89ed9cc1303985b22baed3db3e1bdfc78152f35b503461040657806003193601126104065760206040517f939642605c445f20f056667e4fef08a430d5d7a11f2015abf09af49c09a0b3318152f35b50346104065760603660031901126104065760043561ffff8116908181036111a057604435916001600160401b03831161119c576103926111979161113c610637953690600401611c67565b929091611147611e28565b611150336122a8565b60405160208101917f63a5eb5ceb726bb49bd96516994883823b842a6156518ce2d0e0136103a758ce8352604082015260243560608201526060815261036a608082611ddc565b6120d2565b8380fd5b8280fd5b503461040657602036600319011261040657602061058b60043561037561218c565b5034610406576111d536611d66565b906111e294929394611e28565b6111eb336122a8565b5f5160206129c85f395f51905f528652600160205260016040872054146112c55761127692916112719161039260405160208101907f675cf17ef722191a274d830b69382dac42e70f4f7218ca222a32aa3ae906c6c4825260018060a01b0387169889604083015261ffff8b16606083015260808201526080815261036a60a082611ddc565b61265a565b8061129d575b1561128b5750610637906120d2565b63d979040560e01b8352600452602482fd5b5f5160206129c85f395f51905f52845260016020526112bf8260408620612893565b5061127c565b63dd9347cf60e01b8652600486fd5b503461040657806003193601126104065760206040517f31beef549fa2fb06b369ed48b45a2edeb7617efbc57bacce26f5afdbd005cb648152f35b5034610406578061039261139161132536611cd9565b92949361133496919296611e28565b61133d336122a8565b60405160208101917fec92e66243efd4e1228fbba4d38debae48ef58c5522cd863db9f7f4d4c40e088835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263b463058360e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760e036600319011261040657806113ef611c51565b6113f7611c97565b906044356001600160a01b038116908190036105305760643592611419611cad565b60c4356001600160401b038111610e3a5761143b6114cd913690600401611c67565b90611444611e28565b61144d336122a8565b6103926040519760208901907f95c38268b5649f06a6f6d39a8832927e89ed9cc1303985b22baed3db3e1bdfc7825260018060a01b0316968760408b015260018060a01b0316958660608b01528860808b01528a60a08b015260018060a01b0316988960c082015260a43560e082015260e0815261036a61010082611ddc565b813b15610e365785608492819560405197889687956342aa022360e01b875260048701526024860152604485015260648401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065761159b6115a061153436611d24565b90611540959295611e28565b611549336122a8565b61039260405160208101907f998a4c94dc3882fa6384c73e65bd8f33311b4c0e4916a0cedca40a15de35f2e5825260018060a01b0387169889604083015260608201526060815261036a608082611ddc565b6125c4565b806115d1575b156115bf5750805f516020612a285f395f51905f525d80f35b63153a592b60e01b8252600452602490fd5b5f5160206129e85f395f51905f52835260016020526115f38260408520612893565b506115a6565b503461040657604036600319011261040657600490611616611c97565b506314ec366d60e21b8152fd5b50346104065760203660031901126104065760ff60406020926004358152600484522054166040519015158152f35b50346104065760403660031901126104065760049061166f611c97565b50630790904d60e41b8152fd5b50346104065780600319360112610406576040815f5160206129e85f395f51905f5260209352600183522054604051908152f35b50346104065760c036600319011261040657806116cb611c51565b6024356044356064359260a4356001600160401b038111610e36576116f7611770913690600401611c67565b90611700611e28565b611709336122a8565b6103926040519460208601907f95c8a14d53e1bab3e3fe7f0c3e904f7d307f154ddeae3f4b87c59df3306fbfab825260018060a01b0316958660408201528860608201528760808201528960a082015260843560c082015260c0815261036a60e082611ddc565b803b15610414578492836064926040519687958694634ef58bf560e11b86526004860152602485015260448401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657602036600319011261040657600160406020926004358152808452200154604051908152f35b5034610406578061039261186b6117ff36611cd9565b92949361180e96919296611e28565b611817336122a8565b60405160208101917f9c0b53e2c61880f7d4bca4cce82818bb921f0d86f814cd1249439307d4bc2916835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263473480c360e11b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657608036600319011261040657806004356001600160a01b038116908190036119b0576118de611c97565b6064356001600160401b0381116105305761190061196d913690600401611c67565b90611909611e28565b611912336122a8565b6103926040519460208601907f1847c693d194e1a100320ac1e36598ef73b3341774acd1424da6eeab108a48fd825287604088015260018060a01b03169586606082015260443560808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263f2fde38b60e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50fd5b50346104065780600319360112610406576040815f5160206129c85f395f51905f5260209352600183522054604051908152f35b503461040657806003193601126104065760206040515f5160206129e85f395f51905f528152f35b503461040657806003193601126104065760206040517fec92e66243efd4e1228fbba4d38debae48ef58c5522cd863db9f7f4d4c40e0888152f35b5034611b6b576080366003190112611b6b57611a64611c51565b6024356001600160a01b03811690819003611b6b576064356001600160401b038111611b6b57611a9b611b08913690600401611c67565b90611aa4611e28565b611aad336122a8565b6103926040519560208701907f7464b56e920567064f091785deccb66a4576616e1029ab267552e6509ee75722825260018060a01b03169687604082015286606082015260443560808201526080815261036a60a082611ddc565b813b15611b6b575f9160248392604051948593849263bd69025360e01b845260048401525af18015611b6057611b4d575b50805f516020612a285f395f51905f525d80f35b611b5991505f90611ddc565b5f5f611b39565b6040513d5f823e3d90fd5b5f80fd5b34611b6b575f366003190112611b6b5760206040517f1fad5095fd65097f3b065eb0d4e3236a9703532cdf0ced3fd931e3ff38e9f0238152f35b34611b6b576020366003190112611b6b5760043563ffffffff60e01b8116809103611b6b57602090635a05180f60e01b8114908115611bee575b506040519015158152f35b637965db0b60e01b811491508115611c08575b5082611be3565b6301ffc9a760e01b14905082611c01565b34611b6b575f366003190112611b6b57807f998a4c94dc3882fa6384c73e65bd8f33311b4c0e4916a0cedca40a15de35f2e560209252f35b600435906001600160a01b0382168203611b6b57565b9181601f84011215611b6b578235916001600160401b038311611b6b576020808501948460051b010111611b6b57565b602435906001600160a01b0382168203611b6b57565b608435906001600160a01b0382168203611b6b57565b604435906001600160a01b0382168203611b6b57565b906080600319830112611b6b576004356001600160a01b0381168103611b6b57916024359160443591606435906001600160401b038211611b6b57611d2091600401611c67565b9091565b6060600319820112611b6b576004356001600160a01b0381168103611b6b579160243591604435906001600160401b038211611b6b57611d2091600401611c67565b906080600319830112611b6b576004356001600160a01b0381168103611b6b579160243561ffff81168103611b6b579160443591606435906001600160401b038211611b6b57611d2091600401611c67565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b90601f801991011681019081106001600160401b03821117611dfd57604052565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b038111611dfd5760051b60200190565b5f516020612a285f395f51905f525c611e4e5760015f516020612a285f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b8051821015611e715760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b929092805f52600460205260ff60405f2054166120c0575f818152600460205260408120805460ff1916600117905593611ebe84611e11565b92611ecc6040519485611ddc565b848452601f19611edb86611e11565b013660208601375f955b85871015612041578660051b830135601e1984360301811215611b6b5783018035906001600160401b038211611b6b5760208101908236038213611b6b5760405190611f3b601f8501601f191660200183611ddc565b8382526020843692010111611b6b575f602084611f6d95611f6495838601378301015286612516565b90929192612550565b611f778887611e5d565b9060018060a01b0316809152845f52600660205260405f20815f5260205260ff60405f20541661202f575f8181525f516020612a085f395f51905f52602052604090205460ff161561200c57845f52600660205260405f20905f5260205260405f20600160ff198254161790555f198114611ff85760019687019601611ee5565b634e487b7160e01b5f52601160045260245ffd5b63e2517d3f60e01b5f526004525f5160206129c85f395f51905f5260245260445ffd5b63387370e760e01b5f5260045260245ffd5b92945094505061ffff60055416908181106120ab5750505f5b81518110156120a6575f838152600660205260409020600191906001600160a01b036120868386611e5d565b5116838060a01b03165f5260205260405f2060ff1981541690550161205a565b505050565b636b01174760e11b5f5260045260245260445ffd5b63a4b9136d60e01b5f5260045260245ffd5b5f5160206129c85f395f51905f525f52600160208190527f54fa744d02e0cd6feb2b438b7701c241f85ef8aa84993c058c9ed46b60f00edc549261ffff909216919083901c8211612133575063e97165e960e01b5f5260045260245260445ffd5b91808211612176575060207fa31c29b707b2e58572a28de7d3e3f17fa5dd9e21a2c0eafe4174b214df4f3615918061ffff196005541617600555604051908152a1565b906374ba4b4560e01b5f5260045260245260445ffd5b307f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316148061227f575b156121e7577f000000000000000000000000000000000000000000000000000000000000000090565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f000000000000000000000000000000000000000000000000000000000000000060408201527f000000000000000000000000000000000000000000000000000000000000000060608201524660808201523060a082015260a0815261227960c082611ddc565b51902090565b507f000000000000000000000000000000000000000000000000000000000000000046146121be565b6001600160a01b0381165f9081527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604090205460ff16156122ea5750565b63e2517d3f60e01b5f5260018060a01b03166004525f60245260445ffd5b60ff811461234e5760ff811690601f821161233f576040519161232c604084611ddc565b6020808452838101919036833783525290565b632cd44ac360e21b5f5260045ffd5b506040515f6002548060011c9160018216918215612427575b6020841083146124135783855284929081156123f45750600114612395575b61239292500382611ddc565b90565b5060025f90815290917f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5b8183106123d857505090602061239292820101612386565b60209193508060019154838588010152019101909183926123c0565b6020925061239294915060ff191682840152151560051b820101612386565b634e487b7160e01b5f52602260045260245ffd5b92607f1692612367565b60ff81146124555760ff811690601f821161233f576040519161232c604084611ddc565b506040515f6003548060011c91600182169182156124f7575b6020841083146124135783855284929081156123f457506001146124985761239292500382611ddc565b5060035f90815290917fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8183106124db57505090602061239292820101612386565b60209193508060019154838588010152019101909183926124c3565b92607f169261246e565b8054821015611e71575f5260205f2001905f90565b81519190604183036125465761253f9250602082015190606060408401519301515f1a90612811565b9192909190565b50505f9160029190565b60048110156125b05780612562575050565b600181036125795763f645eedf60e01b5f5260045ffd5b60028103612594575063fce698f760e01b5f5260045260245ffd5b60031461259e5750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b0381165f9081525f516020612a485f395f51905f52602052604090205460ff1615612655576001600160a01b03165f8181525f516020612a485f395f51905f5260205260408120805460ff191690553391905f5160206129e85f395f51905f52907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b505f90565b6001600160a01b0381165f9081525f516020612a085f395f51905f52602052604090205460ff1615612655576001600160a01b03165f8181525f516020612a085f395f51905f5260205260408120805460ff191690553391905f5160206129c85f395f51905f52907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b6001600160a01b0381165f9081525f516020612a485f395f51905f52602052604090205460ff16612655576001600160a01b03165f8181525f516020612a485f395f51905f5260205260408120805460ff191660011790553391905f5160206129e85f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b6001600160a01b0381165f9081525f516020612a085f395f51905f52602052604090205460ff16612655576001600160a01b03165f8181525f516020612a085f395f51905f5260205260408120805460ff191660011790553391905f5160206129c85f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411612888579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15611b60575f516001600160a01b0381161561287e57905f905f90565b505f906001905f90565b5050505f9160039190565b906001820191815f528260205260405f20548015155f14612966575f198101818111611ff85782545f19810191908211611ff85781810361291b575b50505080548015612907575f1901906128e88282612501565b8154905f199060031b1b19169055555f526020525f6040812055600190565b634e487b7160e01b5f52603160045260245ffd5b61295161292b61293b9386612501565b90549060031b1c92839286612501565b819391549060031b91821b915f19901b19161790565b90555f528360205260405f20555f80806128cf565b505050505f90565b6001810190825f528160205260405f2054155f146129c057805468010000000000000000811015611dfd576129ad61293b826001879401855584612501565b905554915f5260205260405f2055600190565b5050505f9056fe21702c8af46127c7fa207f89d0b0a8441bb32959a0ac7df790e9ab1a25c989262344277e405079ec07749d374ba0b5862a4e45a6a05ac889dbb4a991c6f9354d5111aeae4aa79889928e72f88b5872109754de9d419ea9a4e3df5fba21d4d46f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0046893eb66b8615e8839ca23d55ac8782893b5b2b09384720c144d0140eae75bfa164736f6c634300081c000a2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d21702c8af46127c7fa207f89d0b0a8441bb32959a0ac7df790e9ab1a25c989262344277e405079ec07749d374ba0b5862a4e45a6a05ac889dbb4a991c6f9354d54fa744d02e0cd6feb2b438b7701c241f85ef8aa84993c058c9ed46b60f00edc5111aeae4aa79889928e72f88b5872109754de9d419ea9a4e3df5fba21d4d46f46893eb66b8615e8839ca23d55ac8782893b5b2b09384720c144d0140eae75bfad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb50000000000000000000000007aafd20521cf8ed0f227a255bd7f8c139c9019d70000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003000000000000000000000000e43806448931345a6ab228f1e370c54cd2c34c930000000000000000000000006f765bfd178f4c01fb44e978993c203969dda6d8000000000000000000000000b3fe99287675a0bba71c1d179eca45fe0d4ce94800000000000000000000000000000000000000000000000000000000000000030000000000000000000000008e1d6a141e09720d6bcb9d082c86a7fb652f0a3d000000000000000000000000aa76b01b0189c5d4e00703167c3c616b21c320fe000000000000000000000000210fec8dd1cc51728ccef1ad20ca5867e46c05c9

Deployed Bytecode

0x6080806040526004361015610012575f80fd5b5f905f3560e01c9081630196a16a14611c195750806301ffc9a714611ba9578063097b59c314611b6f5780630bec174a14611a4a5780630cd2a4a114611a0f5780630e7b949e146119e75780630f43a677146119b3578063131681ba146118ae57806319c81e96146117e9578063248a9ca3146117bd57806325dd8b88146116b05780632ebfd2ea1461167c5780632f2ff15d1461165257806332aa71c31461162357806336568abe146115f957806351315ee21461151f578063558d2fff146113d4578063605429961461130f57806362c02a3f146112d4578063639b715e146111c65780636575f6aa146111a4578063697f0f9c146110f05780636f09c6b0146110b55780636fe814611461107a57806384b0196e14610f7e5780638d4d2db114610f435780639010d07c14610efd57806391d1485414610eb457806398c8ccb814610e795780639a916af414610e3e5780639d90810014610cfb578063a217fddf14610cdf578063a3246ad314610c2f578063a6e89af614610bf4578063a82f2e2614610bd2578063bbfdaf6b14610b97578063bc23474414610b5c578063c49baebe14610b34578063ca15c87314610b0a578063cb9ee111146109fe578063ccf51afb146109c3578063cd589e6c14610988578063d361baf01461094d578063d445d0e714610888578063d547741f1461085e578063e0438a3d14610799578063e1b0b147146106bf578063eba846f114610684578063f06b713714610593578063f698da2514610570578063f7eb261514610535578063f84553471461043c5763fb85f1cd14610265575f80fd5b346104065760c03660031901126104065761027e611c51565b906024359161028b611cc3565b926064359160a4356001600160401b038111610414576102af903690600401611c67565b95906102b9611e28565b5f5160206129e85f395f51905f52865260208681526040808820335f908152925290205460ff1615610418578596610397916103926040519560208701907fe1f1296627be0060124750977e9616f23b5d73a3c17504735acb15b3ba75eb3d825260018060a01b03169586604089015233606089015288608089015260018060a01b0316968760a08201528960c08201524660e0820152608435610100820152610100815261036a61012082611ddc565b51902061037561218c565b6042916040519161190160f01b8352600283015260228201522090565b611e85565b803b156104145784928360a492604051968795869463054de61b60e31b86526004860152336024860152604485015260648401524660848401525af18015610409576103f1575b505f516020612a285f395f51905f525d80f35b816103fb91611ddc565b61040657805f6103de565b80fd5b6040513d84823e3d90fd5b8480fd5b63e2517d3f60e01b8652336004525f5160206129e85f395f51905f52602452604486fd5b50346104065760803660031901126104065780610457611c51565b6024356064356001600160401b0381116105305761047c6104e9913690600401611c67565b90610485611e28565b61048e336122a8565b6103926040519560208701907f1fad5095fd65097f3b065eb0d4e3236a9703532cdf0ced3fd931e3ff38e9f023825260018060a01b03169687604082015286606082015260443560808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492639e35bf2160e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b5050fd5b505050fd5b503461040657806003193601126104065760206040517fefba6576b27217397aa763a8b62f960f85c09a08794fbf60c2d7d9cb27c8d9158152f35b5034610406578060031936011261040657602061058b61218c565b604051908152f35b50346104065761062261061d6105a836611d66565b906105b896949396959295611e28565b6105c1336122a8565b61039260405160208101907fe0143d71b08cb5463a713c5ae83827af5ae8d02e40eadea38b379b5efce5d775825260018060a01b0387169889604083015261ffff8b16606083015260808201526080815261036a60a082611ddc565b61277e565b8061065c575b1561064a5750610637906120d2565b805f516020612a285f395f51905f525d80f35b634c97322f60e11b8352600452602482fd5b5f5160206129c85f395f51905f528452600160205261067e826040862061296e565b50610628565b503461040657806003193601126104065760206040517f1847c693d194e1a100320ac1e36598ef73b3341774acd1424da6eeab108a48fd8152f35b50346104065761073b6107406106d436611d24565b906106e0959295611e28565b6106e9336122a8565b61039260405160208101907ff0fa648f2f6b39afca5a1dba358729fe1a2519d420d5c941498610fc9a8645d7825260018060a01b0387169889604083015260608201526060815261036a608082611ddc565b6126eb565b80610771575b1561075f5750805f516020612a285f395f51905f525d80f35b6364dca79960e01b8252600452602490fd5b5f5160206129e85f395f51905f5283526001602052610793826040852061296e565b50610746565b5034610406578061039261081b6107af36611cd9565b9294936107be96919296611e28565b6107c7336122a8565b60405160208101917fefba6576b27217397aa763a8b62f960f85c09a08794fbf60c2d7d9cb27c8d915835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492633a95285360e11b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760403660031901126104065760049061087b611c97565b5063ae83e1a360e01b8152fd5b5034610406578061039261090a61089e36611cd9565b9294936108ad96919296611e28565b6108b6336122a8565b60405160208101917f31beef549fa2fb06b369ed48b45a2edeb7617efbc57bacce26f5afdbd005cb64835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c578291602483926040519485938492630246820d60e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657806003193601126104065760206040517f63a5eb5ceb726bb49bd96516994883823b842a6156518ce2d0e0136103a758ce8152f35b503461040657806003193601126104065760206040517fe0143d71b08cb5463a713c5ae83827af5ae8d02e40eadea38b379b5efce5d7758152f35b503461040657806003193601126104065760206040517f9c0b53e2c61880f7d4bca4cce82818bb921f0d86f814cd1249439307d4bc29168152f35b50346104065760a03660031901126104065780610a19611c51565b602435610a24611cc3565b916084356001600160401b03811161041457610a47610ac3913690600401611c67565b90610a50611e28565b610a59336122a8565b6103926040519460208601907f9746d0b05fdd12543f6c1ef9696ac18afa4dc0130be3eddd0329e2bf53acda29825260018060a01b03169788604088015287606088015260018060a01b03169586608082015260643560a082015260a0815261036a60c082611ddc565b823b1561053057604484928360405195869485936395f7f34d60e01b8552600485015260248401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760203660031901126104065760406020916004358152600183522054604051908152f35b503461040657806003193601126104065760206040515f5160206129c85f395f51905f528152f35b503461040657806003193601126104065760206040517f7464b56e920567064f091785deccb66a4576616e1029ab267552e6509ee757228152f35b503461040657806003193601126104065760206040517ff0fa648f2f6b39afca5a1dba358729fe1a2519d420d5c941498610fc9a8645d78152f35b5034610406578060031936011261040657602061ffff60055416604051908152f35b503461040657806003193601126104065760206040517f675cf17ef722191a274d830b69382dac42e70f4f7218ca222a32aa3ae906c6c48152f35b5034610406576020366003190112610406576004358152600160205260408120604051908160208254918281520190819285526020852090855b818110610cc95750505082610c7f910383611ddc565b604051928392602084019060208552518091526040840192915b818110610ca7575050500390f35b82516001600160a01b0316845285945060209384019390920191600101610c99565b8254845260209093019260019283019201610c69565b5034610406578060031936011261040657602090604051908152f35b50346104065760e03660031901126104065780610d16611c51565b60243590610d22611cc3565b9160643592610d2f611cad565b9160c4356001600160401b038111610e3a57610d52610de4913690600401611c67565b90610d5b611e28565b610d64336122a8565b6103926040519760208901907f939642605c445f20f056667e4fef08a430d5d7a11f2015abf09af49c09a0b331825260018060a01b0316968760408b01528660608b015260018060a01b0316978860808b01528a60a08b015260018060a01b0316988960c082015260a43560e082015260e0815261036a61010082611ddc565b813b15610e36578560849281956040519788968795636fa7c1d760e01b875260048701526024860152604485015260648401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b8580fd5b8680fd5b503461040657806003193601126104065760206040517f9746d0b05fdd12543f6c1ef9696ac18afa4dc0130be3eddd0329e2bf53acda298152f35b503461040657806003193601126104065760206040517fe1f1296627be0060124750977e9616f23b5d73a3c17504735acb15b3ba75eb3d8152f35b5034610406576040366003190112610406576040610ed0611c97565b91600435815280602052209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b503461040657604036600319011261040657610f2a60209160043581526001835260406024359120612501565b905460405160039290921b1c6001600160a01b03168152f35b503461040657806003193601126104065760206040517f95c8a14d53e1bab3e3fe7f0c3e904f7d307f154ddeae3f4b87c59df3306fbfab8152f35b503461040657806003193601126104065761101e90610fbc7f00000000000000000000000000000000000000000000000000000000000000ff612308565b90610fe67f3100000000000000000000000000000000000000000000000000000000000001612431565b90602061102c60405193610ffa8386611ddc565b8385525f368137604051968796600f60f81b885260e08589015260e0880190611db8565b908682036040880152611db8565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b82811061106357505050500390f35b835185528695509381019392810192600101611054565b503461040657806003193601126104065760206040517f95c38268b5649f06a6f6d39a8832927e89ed9cc1303985b22baed3db3e1bdfc78152f35b503461040657806003193601126104065760206040517f939642605c445f20f056667e4fef08a430d5d7a11f2015abf09af49c09a0b3318152f35b50346104065760603660031901126104065760043561ffff8116908181036111a057604435916001600160401b03831161119c576103926111979161113c610637953690600401611c67565b929091611147611e28565b611150336122a8565b60405160208101917f63a5eb5ceb726bb49bd96516994883823b842a6156518ce2d0e0136103a758ce8352604082015260243560608201526060815261036a608082611ddc565b6120d2565b8380fd5b8280fd5b503461040657602036600319011261040657602061058b60043561037561218c565b5034610406576111d536611d66565b906111e294929394611e28565b6111eb336122a8565b5f5160206129c85f395f51905f528652600160205260016040872054146112c55761127692916112719161039260405160208101907f675cf17ef722191a274d830b69382dac42e70f4f7218ca222a32aa3ae906c6c4825260018060a01b0387169889604083015261ffff8b16606083015260808201526080815261036a60a082611ddc565b61265a565b8061129d575b1561128b5750610637906120d2565b63d979040560e01b8352600452602482fd5b5f5160206129c85f395f51905f52845260016020526112bf8260408620612893565b5061127c565b63dd9347cf60e01b8652600486fd5b503461040657806003193601126104065760206040517f31beef549fa2fb06b369ed48b45a2edeb7617efbc57bacce26f5afdbd005cb648152f35b5034610406578061039261139161132536611cd9565b92949361133496919296611e28565b61133d336122a8565b60405160208101917fec92e66243efd4e1228fbba4d38debae48ef58c5522cd863db9f7f4d4c40e088835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263b463058360e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065760e036600319011261040657806113ef611c51565b6113f7611c97565b906044356001600160a01b038116908190036105305760643592611419611cad565b60c4356001600160401b038111610e3a5761143b6114cd913690600401611c67565b90611444611e28565b61144d336122a8565b6103926040519760208901907f95c38268b5649f06a6f6d39a8832927e89ed9cc1303985b22baed3db3e1bdfc7825260018060a01b0316968760408b015260018060a01b0316958660608b01528860808b01528a60a08b015260018060a01b0316988960c082015260a43560e082015260e0815261036a61010082611ddc565b813b15610e365785608492819560405197889687956342aa022360e01b875260048701526024860152604485015260648401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50346104065761159b6115a061153436611d24565b90611540959295611e28565b611549336122a8565b61039260405160208101907f998a4c94dc3882fa6384c73e65bd8f33311b4c0e4916a0cedca40a15de35f2e5825260018060a01b0387169889604083015260608201526060815261036a608082611ddc565b6125c4565b806115d1575b156115bf5750805f516020612a285f395f51905f525d80f35b63153a592b60e01b8252600452602490fd5b5f5160206129e85f395f51905f52835260016020526115f38260408520612893565b506115a6565b503461040657604036600319011261040657600490611616611c97565b506314ec366d60e21b8152fd5b50346104065760203660031901126104065760ff60406020926004358152600484522054166040519015158152f35b50346104065760403660031901126104065760049061166f611c97565b50630790904d60e41b8152fd5b50346104065780600319360112610406576040815f5160206129e85f395f51905f5260209352600183522054604051908152f35b50346104065760c036600319011261040657806116cb611c51565b6024356044356064359260a4356001600160401b038111610e36576116f7611770913690600401611c67565b90611700611e28565b611709336122a8565b6103926040519460208601907f95c8a14d53e1bab3e3fe7f0c3e904f7d307f154ddeae3f4b87c59df3306fbfab825260018060a01b0316958660408201528860608201528760808201528960a082015260843560c082015260c0815261036a60e082611ddc565b803b15610414578492836064926040519687958694634ef58bf560e11b86526004860152602485015260448401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657602036600319011261040657600160406020926004358152808452200154604051908152f35b5034610406578061039261186b6117ff36611cd9565b92949361180e96919296611e28565b611817336122a8565b60405160208101917f9c0b53e2c61880f7d4bca4cce82818bb921f0d86f814cd1249439307d4bc2916835260018060a01b03169788604083015287606083015260808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263473480c360e11b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b503461040657608036600319011261040657806004356001600160a01b038116908190036119b0576118de611c97565b6064356001600160401b0381116105305761190061196d913690600401611c67565b90611909611e28565b611912336122a8565b6103926040519460208601907f1847c693d194e1a100320ac1e36598ef73b3341774acd1424da6eeab108a48fd825287604088015260018060a01b03169586606082015260443560808201526080815261036a60a082611ddc565b813b1561052c57829160248392604051948593849263f2fde38b60e01b845260048401525af18015610409576103f157505f516020612a285f395f51905f525d80f35b50fd5b50346104065780600319360112610406576040815f5160206129c85f395f51905f5260209352600183522054604051908152f35b503461040657806003193601126104065760206040515f5160206129e85f395f51905f528152f35b503461040657806003193601126104065760206040517fec92e66243efd4e1228fbba4d38debae48ef58c5522cd863db9f7f4d4c40e0888152f35b5034611b6b576080366003190112611b6b57611a64611c51565b6024356001600160a01b03811690819003611b6b576064356001600160401b038111611b6b57611a9b611b08913690600401611c67565b90611aa4611e28565b611aad336122a8565b6103926040519560208701907f7464b56e920567064f091785deccb66a4576616e1029ab267552e6509ee75722825260018060a01b03169687604082015286606082015260443560808201526080815261036a60a082611ddc565b813b15611b6b575f9160248392604051948593849263bd69025360e01b845260048401525af18015611b6057611b4d575b50805f516020612a285f395f51905f525d80f35b611b5991505f90611ddc565b5f5f611b39565b6040513d5f823e3d90fd5b5f80fd5b34611b6b575f366003190112611b6b5760206040517f1fad5095fd65097f3b065eb0d4e3236a9703532cdf0ced3fd931e3ff38e9f0238152f35b34611b6b576020366003190112611b6b5760043563ffffffff60e01b8116809103611b6b57602090635a05180f60e01b8114908115611bee575b506040519015158152f35b637965db0b60e01b811491508115611c08575b5082611be3565b6301ffc9a760e01b14905082611c01565b34611b6b575f366003190112611b6b57807f998a4c94dc3882fa6384c73e65bd8f33311b4c0e4916a0cedca40a15de35f2e560209252f35b600435906001600160a01b0382168203611b6b57565b9181601f84011215611b6b578235916001600160401b038311611b6b576020808501948460051b010111611b6b57565b602435906001600160a01b0382168203611b6b57565b608435906001600160a01b0382168203611b6b57565b604435906001600160a01b0382168203611b6b57565b906080600319830112611b6b576004356001600160a01b0381168103611b6b57916024359160443591606435906001600160401b038211611b6b57611d2091600401611c67565b9091565b6060600319820112611b6b576004356001600160a01b0381168103611b6b579160243591604435906001600160401b038211611b6b57611d2091600401611c67565b906080600319830112611b6b576004356001600160a01b0381168103611b6b579160243561ffff81168103611b6b579160443591606435906001600160401b038211611b6b57611d2091600401611c67565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b90601f801991011681019081106001600160401b03821117611dfd57604052565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b038111611dfd5760051b60200190565b5f516020612a285f395f51905f525c611e4e5760015f516020612a285f395f51905f525d565b633ee5aeb560e01b5f5260045ffd5b8051821015611e715760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b929092805f52600460205260ff60405f2054166120c0575f818152600460205260408120805460ff1916600117905593611ebe84611e11565b92611ecc6040519485611ddc565b848452601f19611edb86611e11565b013660208601375f955b85871015612041578660051b830135601e1984360301811215611b6b5783018035906001600160401b038211611b6b5760208101908236038213611b6b5760405190611f3b601f8501601f191660200183611ddc565b8382526020843692010111611b6b575f602084611f6d95611f6495838601378301015286612516565b90929192612550565b611f778887611e5d565b9060018060a01b0316809152845f52600660205260405f20815f5260205260ff60405f20541661202f575f8181525f516020612a085f395f51905f52602052604090205460ff161561200c57845f52600660205260405f20905f5260205260405f20600160ff198254161790555f198114611ff85760019687019601611ee5565b634e487b7160e01b5f52601160045260245ffd5b63e2517d3f60e01b5f526004525f5160206129c85f395f51905f5260245260445ffd5b63387370e760e01b5f5260045260245ffd5b92945094505061ffff60055416908181106120ab5750505f5b81518110156120a6575f838152600660205260409020600191906001600160a01b036120868386611e5d565b5116838060a01b03165f5260205260405f2060ff1981541690550161205a565b505050565b636b01174760e11b5f5260045260245260445ffd5b63a4b9136d60e01b5f5260045260245ffd5b5f5160206129c85f395f51905f525f52600160208190527f54fa744d02e0cd6feb2b438b7701c241f85ef8aa84993c058c9ed46b60f00edc549261ffff909216919083901c8211612133575063e97165e960e01b5f5260045260245260445ffd5b91808211612176575060207fa31c29b707b2e58572a28de7d3e3f17fa5dd9e21a2c0eafe4174b214df4f3615918061ffff196005541617600555604051908152a1565b906374ba4b4560e01b5f5260045260245260445ffd5b307f000000000000000000000000baba24610681fdf6a8fcb921c3074b0dd6dc57ae6001600160a01b0316148061227f575b156121e7577f990c59795c5d15ce44ec84ec00e117b9bd2fdc12b11efb73d06d9e1d220cd09290565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f3b122ae40bffe633fa056e367a4e7f23381a9435115086056a3c644bc53c591c60408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a0815261227960c082611ddc565b51902090565b507f00000000000000000000000000000000000000000000000000000000000b67d246146121be565b6001600160a01b0381165f9081527fad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5602052604090205460ff16156122ea5750565b63e2517d3f60e01b5f5260018060a01b03166004525f60245260445ffd5b60ff811461234e5760ff811690601f821161233f576040519161232c604084611ddc565b6020808452838101919036833783525290565b632cd44ac360e21b5f5260045ffd5b506040515f6002548060011c9160018216918215612427575b6020841083146124135783855284929081156123f45750600114612395575b61239292500382611ddc565b90565b5060025f90815290917f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5b8183106123d857505090602061239292820101612386565b60209193508060019154838588010152019101909183926123c0565b6020925061239294915060ff191682840152151560051b820101612386565b634e487b7160e01b5f52602260045260245ffd5b92607f1692612367565b60ff81146124555760ff811690601f821161233f576040519161232c604084611ddc565b506040515f6003548060011c91600182169182156124f7575b6020841083146124135783855284929081156123f457506001146124985761239292500382611ddc565b5060035f90815290917fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b5b8183106124db57505090602061239292820101612386565b60209193508060019154838588010152019101909183926124c3565b92607f169261246e565b8054821015611e71575f5260205f2001905f90565b81519190604183036125465761253f9250602082015190606060408401519301515f1a90612811565b9192909190565b50505f9160029190565b60048110156125b05780612562575050565b600181036125795763f645eedf60e01b5f5260045ffd5b60028103612594575063fce698f760e01b5f5260045260245ffd5b60031461259e5750565b6335e2f38360e21b5f5260045260245ffd5b634e487b7160e01b5f52602160045260245ffd5b6001600160a01b0381165f9081525f516020612a485f395f51905f52602052604090205460ff1615612655576001600160a01b03165f8181525f516020612a485f395f51905f5260205260408120805460ff191690553391905f5160206129e85f395f51905f52907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b505f90565b6001600160a01b0381165f9081525f516020612a085f395f51905f52602052604090205460ff1615612655576001600160a01b03165f8181525f516020612a085f395f51905f5260205260408120805460ff191690553391905f5160206129c85f395f51905f52907ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9080a4600190565b6001600160a01b0381165f9081525f516020612a485f395f51905f52602052604090205460ff16612655576001600160a01b03165f8181525f516020612a485f395f51905f5260205260408120805460ff191660011790553391905f5160206129e85f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b6001600160a01b0381165f9081525f516020612a085f395f51905f52602052604090205460ff16612655576001600160a01b03165f8181525f516020612a085f395f51905f5260205260408120805460ff191660011790553391905f5160206129c85f395f51905f52907f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9080a4600190565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411612888579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15611b60575f516001600160a01b0381161561287e57905f905f90565b505f906001905f90565b5050505f9160039190565b906001820191815f528260205260405f20548015155f14612966575f198101818111611ff85782545f19810191908211611ff85781810361291b575b50505080548015612907575f1901906128e88282612501565b8154905f199060031b1b19169055555f526020525f6040812055600190565b634e487b7160e01b5f52603160045260245ffd5b61295161292b61293b9386612501565b90549060031b1c92839286612501565b819391549060031b91821b915f19901b19161790565b90555f528360205260405f20555f80806128cf565b505050505f90565b6001810190825f528160205260405f2054155f146129c057805468010000000000000000811015611dfd576129ad61293b826001879401855584612501565b905554915f5260205260405f2055600190565b5050505f9056fe21702c8af46127c7fa207f89d0b0a8441bb32959a0ac7df790e9ab1a25c989262344277e405079ec07749d374ba0b5862a4e45a6a05ac889dbb4a991c6f9354d5111aeae4aa79889928e72f88b5872109754de9d419ea9a4e3df5fba21d4d46f9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f0046893eb66b8615e8839ca23d55ac8782893b5b2b09384720c144d0140eae75bfa164736f6c634300081c000a

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

0000000000000000000000007aafd20521cf8ed0f227a255bd7f8c139c9019d70000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003000000000000000000000000e43806448931345a6ab228f1e370c54cd2c34c930000000000000000000000006f765bfd178f4c01fb44e978993c203969dda6d8000000000000000000000000b3fe99287675a0bba71c1d179eca45fe0d4ce94800000000000000000000000000000000000000000000000000000000000000030000000000000000000000008e1d6a141e09720d6bcb9d082c86a7fb652f0a3d000000000000000000000000aa76b01b0189c5d4e00703167c3c616b21c320fe000000000000000000000000210fec8dd1cc51728ccef1ad20ca5867e46c05c9

-----Decoded View---------------
Arg [0] : admin (address): 0x7aAfD20521CF8ED0F227A255bd7F8c139c9019D7
Arg [1] : validators (address[]): 0xe43806448931345a6Ab228F1e370c54cD2C34C93,0x6f765BFD178F4C01fb44e978993c203969Dda6d8,0xb3Fe99287675A0BbA71C1D179eca45fe0D4CE948
Arg [2] : borrowers (address[]): 0x8E1d6A141e09720d6BCb9D082c86A7FB652F0A3d,0xaA76b01b0189c5d4E00703167C3C616b21C320fE,0x210FeC8dD1CC51728CceF1Ad20cA5867e46C05C9
Arg [3] : signatureThreshold_ (uint16): 2

-----Encoded View---------------
12 Constructor Arguments found :
Arg [0] : 0000000000000000000000007aafd20521cf8ed0f227a255bd7f8c139c9019d7
Arg [1] : 0000000000000000000000000000000000000000000000000000000000000080
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000100
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000003
Arg [5] : 000000000000000000000000e43806448931345a6ab228f1e370c54cd2c34c93
Arg [6] : 0000000000000000000000006f765bfd178f4c01fb44e978993c203969dda6d8
Arg [7] : 000000000000000000000000b3fe99287675a0bba71c1d179eca45fe0d4ce948
Arg [8] : 0000000000000000000000000000000000000000000000000000000000000003
Arg [9] : 0000000000000000000000008e1d6a141e09720d6bcb9d082c86a7fb652f0a3d
Arg [10] : 000000000000000000000000aa76b01b0189c5d4e00703167c3c616b21c320fe
Arg [11] : 000000000000000000000000210fec8dd1cc51728ccef1ad20ca5867e46c05c9


Deployed Bytecode Sourcemap

2275:25887:7:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;:::i;:::-;;;;;;;:::i;:::-;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;:::i;:::-;1181:103:27;;;;:::i;:::-;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;735:10:25;-1:-1:-1;2275:25887:7;;;;;;;;;;3519:23:9;3515:108;;2275:25887:7;;7520:10;2275:25887;5020:66:33;2275:25887:7;;7389:91;2275:25887;7389:91;;2275:25887;2607:127;2275:25887;;;;;;;;;;;;;;735:10:25;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;7460:13;2275:25887;;;;;;;;;;;7389:91;;;;;;:::i;:::-;2275:25887;7379:102;;5053:20:33;;:::i;:::-;3445:249:34;3326:374;3445:249;;;-1:-1:-1;;;3445:249:34;;;;;;;;;;;3326:374;;5020:66:33;7520:10:7;:::i;:::-;7542:63;;;;;2275:25887;;;;;;;;;;;;;;;7542:63;;2275:25887;7542:63;;2275:25887;735:10:25;2275:25887:7;;;;;;;;;;;;7460:13;2275:25887;;;;7542:63;;;;;;;;2275:25887;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;7542:63;;;;;:::i;:::-;2275:25887;;7542:63;;;;2275:25887;;;7542:63;2275:25887;;;;;;;;;7542:63;2275:25887;;;3515:108:9;-1:-1:-1;;;3565:47:9;;735:10:25;2275:25887:7;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;3565:47:9;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;17491:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;17377:74;2275:25887;17377:74;;2275:25887;5063:86;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;17377:74;;;;;;:::i;17491:10::-;17513:44;;;;;2275:25887;;;;;;;;;;;;;;;17513:44;;2275:25887;17513:44;;2275:25887;17513:44;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;17513:44;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;3578:92;2275:25887;;;;;;;;;;;;;;;;;23781:20;;:::i;:::-;2275:25887;;;;;;;;;;;2865:31:12;19746:10:7;2275:25887;;;:::i;:::-;1181:103:27;;;;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;19632:74;;;;2926:83;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;19632:74;;;;;;:::i;19746:10::-;2865:31:12;:::i;:::-;2906:69;;;2275:25887:7;26633:38;26630:101;;19831:21;;;;:::i;:::-;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;26630:101;-1:-1:-1;;;26694:26:7;;2275:25887;;;26694:26;;2906:69:12;-1:-1:-1;;;;;;;;;;;2275:25887:7;;2933:12:12;19632:74:7;2275:25887;8382:50:40;2275:25887:7;;;;8382:50:40;:::i;:::-;;2906:69:12;;2275:25887:7;;;;;;;;;;;;;;;;4412:83;2275:25887;;;;;;;;21561:10;2865:31:12;2275:25887:7;;;:::i;:::-;1181:103:27;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;21472:49;;;2275:25887;3207:55;2275:25887;;;;;;;;;;;;;;;;;;;;21472:49;;;;;;:::i;21561:10::-;2865:31:12;:::i;:::-;2906:69;;;2275:25887:7;27582:36;27579:97;;3550:68:31;;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;27579:97;-1:-1:-1;;;27641:24:7;;2275:25887;;;;27641:24;2906:69:12;-1:-1:-1;;;;;;;;;;;2275:25887:7;;2933:12:12;21472:49:7;2275:25887;8382:50:40;2275:25887:7;;;;8382:50:40;:::i;:::-;;2906:69:12;;2275:25887:7;;;;;;5020:66:33;10210:10:7;2275:25887;;;:::i;:::-;1181:103:27;;;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;2275:25887:7;;10090:80;;;2275:25887;3578:92;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;10090:80;;;;;;:::i;10210:10::-;10232:50;;;;;2275:25887;;10232:50;2275:25887;;;;;;;;;;;;10232:50;;2275:25887;10232:50;;2275:25887;10232:50;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;:::i;:::-;-1:-1:-1;;;;18734:22:7;;;2275:25887;;;;;;5020:66:33;12008:10:7;2275:25887;;;:::i;:::-;1181:103:27;;;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;2275:25887:7;;11886:82;;;2275:25887;3884:94;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;11886:82;;;;;;:::i;12008:10::-;12030:52;;;;;2275:25887;;12030:52;2275:25887;;;;;;;;;;;;12030:52;;2275:25887;12030:52;;2275:25887;12030:52;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;;;;;;;;;;4560:77;2275:25887;;;;;;;;;;;;;;;;;;;2926:83;2275:25887;;;;;;;;;;;;;;;;;;;3434:82;2275:25887;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;;;:::i;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;8471:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;8368:63;2275:25887;8368:63;;2275:25887;2788:83;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;8368:63;;;;;;:::i;8471:10::-;8493:34;;;;;2275:25887;;;;;;;;;;;;;;8493:34;;2275:25887;8493:34;;2275:25887;;;;;8493:34;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;;;;;;;;;;4043:84;2275:25887;;;;;;;;;;;;;;;;;;;3207:55;2275:25887;;;;;;;;;;;;;;;;;;5255:32;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;3067:86;2275:25887;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;1390:66:28;;;2275:25887:7;1390:66:28;;2275:25887:7;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;-1:-1:-1;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;;;;:::i;:::-;;;;;;;:::i;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;16571:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;16443:88;2275:25887;16443:88;;2275:25887;4877:122;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;16443:88;;;;;;:::i;16571:10::-;16593:59;;;;;2275:25887;;;;;;;;;;;;;;;16593:59;;2275:25887;16593:59;;2275:25887;;;;;;;;;;;;;16593:59;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;16593:59;2275:25887;;;;;;;;;;;;;;;;;;;;;;;2788:83;2275:25887;;;;;;;;;;;;;;;;;;;2607:127;2275:25887;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;;;;;;;;2954:29:9;2275:25887:7;;;;;;-1:-1:-1;2275:25887:7;;;;;;-1:-1:-1;2275:25887:7;;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;5016:18:40;2275:25887:7;;;;;;;;;;;;;;5016:18:40;:::i;:::-;2275:25887:7;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;;;;;;4189:163;2275:25887;;;;;;;;;;;;;;;;;6099:5:33;:41;:5;:41;:::i;:::-;6554:8;:47;:8;:47;:::i;:::-;2275:25887:7;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;:::i;:::-;5590:13:33;;2275:25887:7;;;;5625:4:33;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;4696:121;2275:25887;;;;;;;;;;;;;;;;;;;4877:122;2275:25887;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;5020:66:33;23056:10:7;2275:25887;;23101:21;2275:25887;;;;;;:::i;:::-;1181:103:27;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;2275:25887:7;;;22943:73;;2275:25887;4560:77;2275:25887;;;;;;;;;;;;;22943:73;;;;;;:::i;23056:10::-;23101:21;:::i;2275:25887::-;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;5020:66:33;2275:25887:7;;5053:20:33;;:::i;2275:25887:7:-;;;;;;;;:::i;:::-;1181:103:27;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;-1:-1:-1;;;;;;;;;;;2275:25887:7;;1933:12:12;2275:25887:7;;1933:12:12;2275:25887:7;;;;20531:21;20527:85;;3226:32:12;2275:25887:7;;20783:10;2275:25887;5020:66:33;2275:25887:7;;;20666:77;;;3067:86;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;20666:77;;;;;;:::i;20783:10::-;3226:32:12;:::i;:::-;3268:72;;;2275:25887:7;27115:39;27112:108;;20869:21;;;;:::i;27112:108::-;-1:-1:-1;;;27177:32:7;;2275:25887;;;27177:32;;3268:72:12;-1:-1:-1;;;;;;;;;;;2275:25887:7;;1933:12:12;2275:25887:7;;8703:53:40;2275:25887:7;;;;8703:53:40;:::i;:::-;;3268:72:12;;20527:85:7;-1:-1:-1;;;20575:26:7;;2275:25887;20575:26;;2275:25887;;;;;;;;;;;;;;;;3884:94;2275:25887;;;;;;;;;5020:66:33;11103:10:7;2275:25887;;;:::i;:::-;1181:103:27;;;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;2275:25887:7;;10985:78;;;2275:25887;3731:90;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;10985:78;;;;;;:::i;11103:10::-;11125:48;;;;;2275:25887;;11125:48;2275:25887;;;;;;;;;;;;11125:48;;2275:25887;11125:48;;2275:25887;11125:48;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;:::i;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;:::i;:::-;;;-1:-1:-1;;;;;2275:25887:7;;;;;15340:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;15213:87;2275:25887;15213:87;;2275:25887;4696:121;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;15213:87;;;;;;:::i;15340:10::-;15362:58;;;;;2275:25887;;;;;;;;;;;;;;;15362:58;;2275:25887;15362:58;;2275:25887;;;;;;;;;;;;;15362:58;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;22286:10;3226:32:12;2275:25887:7;;;:::i;:::-;1181:103:27;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;22194:52;;;2275:25887;3319:58;2275:25887;;;;;;;;;;;;;;;;;;;;22194:52;;;;;;:::i;22286:10::-;3226:32:12;:::i;:::-;3268:72;;;2275:25887:7;28053:37;28050:104;;3550:68:31;;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;28050:104;-1:-1:-1;;;28113:30:7;;2275:25887;;;;28113:30;3268:72:12;-1:-1:-1;;;;;;;;;;;2275:25887:7;;3295:12:12;22194:52:7;2275:25887;8703:53:40;2275:25887:7;;;;8703:53:40;:::i;:::-;;3268:72:12;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;:::i;:::-;-1:-1:-1;;;;18894:24:7;;;2275:25887;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;:::i;:::-;-1:-1:-1;;;;18577:21:7;;;2275:25887;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;1933:12:12;2275:25887:7;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;:::i;:::-;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;14135:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;13958:137;2275:25887;13958:137;;2275:25887;4189:163;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;13958:137;;;2275:25887;13958:137;;:::i;14135:10::-;14157:107;;;;;2275:25887;;;;;;;;;;;;;;;14157:107;;2275:25887;14157:107;;2275:25887;;;;;;;;;14157:107;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;3901:22:9;2275:25887:7;;;;;;;;;;;;;5020:66:33;9320:10:7;2275:25887;;;:::i;:::-;1181:103:27;;;;;;;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;2275:25887:7;;9210:70;;;2275:25887;3434:82;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;9210:70;;;;;;:::i;9320:10::-;9342:40;;;;;2275:25887;;9342:40;2275:25887;;;;;;;;;;;;9342:40;;2275:25887;9342:40;;2275:25887;9342:40;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;:::i;:::-;;;-1:-1:-1;;;;;2275:25887:7;;;;;18379:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;18269:70;2275:25887;18269:70;;2275:25887;4412:83;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;18269:70;;;;;;:::i;18379:10::-;18401:41;;;;;2275:25887;;;;;;;;;;;;;;;18401:41;;2275:25887;18401:41;;2275:25887;18401:41;;;;;;;;3550:68:31;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;1933:12:12;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;;;;;;;;;;3731:90;2275:25887;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;:::i;:::-;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;12899:10;2275:25887;;;;;;:::i;:::-;1181:103:27;;;:::i;:::-;3282:12:9;735:10:25;3282:12:9;:::i;:::-;5020:66:33;2275:25887:7;;12787:72;2275:25887;12787:72;;2275:25887;4043:84;2275:25887;;;;;;;;;;;;;;;;;;;;;;;;;;12787:72;;;;;;:::i;12899:10::-;12921:42;;;;;2275:25887;;;;;;;;;;;;;;;12921:42;;2275:25887;12921:42;;2275:25887;12921:42;;;;;;;;2275:25887;3550:68:31;;-1:-1:-1;;;;;;;;;;;3550:68:31;2275:25887:7;;12921:42;;;;2275:25887;12921:42;;:::i;:::-;2275:25887;12921:42;;;;2275:25887;;;;;;;;;12921:42;2275:25887;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;5063:86;2275:25887;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;;;;;;;;;;;-1:-1:-1;;;837:57:12;;;:97;;;;2275:25887:7;;;;;;;;;;837:97:12;-1:-1:-1;;;2673:47:9;;;-1:-1:-1;2673:87:9;;;;837:97:12;;;;;2673:87:9;-1:-1:-1;;;862:40:35;;-1:-1:-1;2673:87:9;;;2275:25887:7;;;;;;-1:-1:-1;;2275:25887:7;;;;;3319:58;2275:25887;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;:::o;:::-;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;;;:::o;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;:::o;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;:::o;:::-;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;:::o;:::-;;;-1:-1:-1;;2275:25887:7;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;:::i;:::-;;;:::o;:::-;;-1:-1:-1;;2275:25887:7;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;:::i;:::-;;;-1:-1:-1;;2275:25887:7;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;-1:-1:-1;2275:25887:7;;;;;;;;-1:-1:-1;;2275:25887:7;;;;:::o;:::-;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;:::o;:::-;;;;-1:-1:-1;2275:25887:7;;;;;-1:-1:-1;2275:25887:7;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;:::o;1290:346:27:-;-1:-1:-1;;;;;;;;;;;3321:69:31;1413:93:27;;1624:4;-1:-1:-1;;;;;;;;;;;3550:68:31;1290:346:27:o;1413:93::-;1465:30;;;-1:-1:-1;1465:30:27;;-1:-1:-1;1465:30:27;2275:25887:7;;;;;;;;;;;;;;;:::o;:::-;;;;;;;;;;;;24487:989;;;;2275:25887;-1:-1:-1;2275:25887:7;24584:13;2275:25887;;;;-1:-1:-1;2275:25887:7;;;24580:80;;-1:-1:-1;2275:25887:7;;;24584:13;2275:25887;;;;;;;-1:-1:-1;;2275:25887:7;24693:4;2275:25887;;;-1:-1:-1;2275:25887:7;;;:::i;:::-;;;;;;;;:::i;:::-;;;;-1:-1:-1;;2275:25887:7;;;:::i;:::-;;;;;;;-1:-1:-1;24812:400:7;24852:3;24829:21;;;;;;2275:25887;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;:::i;:::-;;;;;;;;;;;;;-1:-1:-1;2275:25887:7;;3927:8:32;2275:25887:7;3871:27:32;2275:25887:7;;;;;;;;;3871:27:32;;:::i;:::-;3927:8;;;;;:::i;:::-;24938:19:7;;;;:::i;:::-;2275:25887;;;;;;;;;;;-1:-1:-1;2275:25887:7;24976:12;2275:25887;;;-1:-1:-1;2275:25887:7;;-1:-1:-1;2275:25887:7;;;;;-1:-1:-1;2275:25887:7;;;24972:100;;-1:-1:-1;2275:25887:7;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;3519:23:9;3515:108;;2275:25887:7;-1:-1:-1;2275:25887:7;24976:12;2275:25887;;;-1:-1:-1;2275:25887:7;25135:28;-1:-1:-1;2275:25887:7;;;;-1:-1:-1;2275:25887:7;24693:4;2275:25887;;;;;;;;;;;;;;24693:4;2275:25887;;;;;24817:10;;2275:25887;;;;-1:-1:-1;2275:25887:7;;24584:13;2275:25887;;-1:-1:-1;2275:25887:7;3515:108:9;3565:47;;;-1:-1:-1;3565:47:9;24584:13:7;2275:25887;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;-1:-1:-1;3565:47:9;24972:100:7;25031:26;;;-1:-1:-1;25031:26:7;24584:13;2275:25887;;-1:-1:-1;25031:26:7;24829:21;;;;;;;2275:25887;;;;25226:36;;;;25222:132;;25369:10;;-1:-1:-1;25401:3:7;2275:25887;;25381:18;;;;;-1:-1:-1;2275:25887:7;;;24976:12;2275:25887;;;;;24693:4;;2275:25887;-1:-1:-1;;;;;25448:10:7;2275:25887;25448:10;;:::i;:::-;2275:25887;;;;;;;;-1:-1:-1;2275:25887:7;;;;-1:-1:-1;2275:25887:7;;;;;;;;;25369:10;;25381:18;;;;24487:989::o;25222:132::-;25285:58;;;-1:-1:-1;25285:58:7;24584:13;2275:25887;;;;-1:-1:-1;25285:58:7;24580:80;24628:21;;;-1:-1:-1;24628:21:7;24584:13;2275:25887;;-1:-1:-1;24628:21:7;25724:546;-1:-1:-1;;;;;;;;;;;;2275:25887:7;1933:12:12;2275:25887:7;;;;;;;;;;;;25724:546;2275:25887;;;25858:44;;2275:25887;;25925:64;;;;-1:-1:-1;25925:64:7;;2275:25887;;;;-1:-1:-1;25925:64:7;25854:294;26010:39;;;;26006:142;;25854:294;2275:25887;26215:48;25854:294;2275:25887;;;26157:42;2275:25887;;;26157:42;2275:25887;;;;;;26215:48;25724:546::o;26006:142::-;26072:65;;;;-1:-1:-1;26072:65:7;;2275:25887;;;;-1:-1:-1;26072:65:7;3845:262:33;3929:4;3938:11;-1:-1:-1;;;;;2275:25887:7;3921:28:33;;:63;;3845:262;3917:184;;;4007:22;4000:29;:::o;3917:184::-;2275:25887:7;;4204:80:33;;;2275:25887:7;2079:95:33;2275:25887:7;;4226:11:33;2275:25887:7;2079:95:33;;2275:25887:7;4239:14:33;2079:95;;;2275:25887:7;4255:13:33;2079:95;;;2275:25887:7;3929:4:33;2079:95;;;2275:25887:7;2079:95:33;4204:80;;;;;;:::i;:::-;2275:25887:7;4194:91:33;;4060:30;:::o;3921:63::-;3970:14;;3953:13;:31;3921:63;;3432:197:9;-1:-1:-1;;;;;2275:25887:7;;;;;;;;;;;;;;;3519:23:9;3515:108;;3432:197;:::o;3515:108::-;3565:47;;;2275:25887:7;3565:47:9;2275:25887:7;;;;;;3565:47:9;2275:25887:7;;;;;;3565:47:9;3358:267:28;1390:66;3481:46;;1390:66;;;2625:40;;2679:11;2688:2;2679:11;;2675:69;;2275:25887:7;;;;;;;:::i;:::-;2311:2:28;2275:25887:7;;;;;;;;;;;2324:106:28;;;3543:22;:::o;2675:69::-;2713:20;;;-1:-1:-1;2713:20:28;;-1:-1:-1;2713:20:28;3477:142;2275:25887:7;;;-1:-1:-1;6126:13:33;1390:66:28;;;;;;;;;;;;;3477:142;1390:66;;;;;;;2275:25887:7;;;;;;1390:66:28;;;;;;;;;;;;;;;;:::i;:::-;3596:12;:::o;1390:66::-;-1:-1:-1;6126:13:33;-1:-1:-1;1390:66:28;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2275:25887:7;;1390:66:28;2275:25887:7;;;;;1390:66:28;2275:25887:7;;;1390:66:28;;;;;;;;;;;2275:25887:7;;;-1:-1:-1;1390:66:28;;;;;-1:-1:-1;1390:66:28;;;;;;;;3358:267;1390:66;3481:46;;1390:66;;;2625:40;;2679:11;2688:2;2679:11;;2675:69;;2275:25887:7;;;;;;;:::i;3477:142:28:-;2275:25887:7;;;-1:-1:-1;6584:16:33;1390:66:28;;;;;;;;;;;;;3477:142;1390:66;;;;;;;2275:25887:7;;;;;;1390:66:28;;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1;6584:16:33;-1:-1:-1;1390:66:28;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2275:25887:7;;;;;;;;-1:-1:-1;1390:66:28;;-1:-1:-1;1390:66:28;2275:25887:7;;-1:-1:-1;2275:25887:7;:::o;2129:778:32:-;2275:25887:7;;;2129:778:32;2319:2;2299:22;;2319:2;;2751:25;2535:196;;;;;;;;;;;;;;;-1:-1:-1;2535:196:32;2751:25;;:::i;:::-;2744:32;;;;;:::o;2295:606::-;2807:83;;2823:1;2807:83;2827:35;2807:83;;:::o;7278:532::-;2275:25887:7;;;;;;7364:29:32;;;7409:7;;:::o;7360:444::-;2275:25887:7;7460:38:32;;2275:25887:7;;7521:23:32;;;7373:20;7521:23;2275:25887:7;7373:20:32;7521:23;7456:348;7574:35;7565:44;;7574:35;;7632:46;;;;7373:20;7632:46;2275:25887:7;;;7373:20:32;7632:46;7561:243;7708:30;7699:39;7695:109;;7561:243;7278:532::o;7695:109::-;7761:32;;;7373:20;7761:32;2275:25887:7;;;7373:20:32;7761:32;2275:25887:7;;;;7373:20:32;2275:25887:7;;;;;7373:20:32;2275:25887:7;6730:317:9;-1:-1:-1;;;;;2275:25887:7;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;735:10:25;;2275:25887:7;-1:-1:-1;;;;;;;;;;;2532:26:7;6922:40:9;;2275:25887:7;6922:40:9;2275:25887:7;6976:11:9;:::o;6824:217::-;7018:12;2275:25887:7;7018:12:9;:::o;6730:317::-;-1:-1:-1;;;;;2275:25887:7;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;735:10:25;;2275:25887:7;-1:-1:-1;;;;;;;;;;;2459:27:7;6922:40:9;;2275:25887:7;6922:40:9;2275:25887:7;6976:11:9;:::o;6179:316::-;-1:-1:-1;;;;;2275:25887:7;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;;;735:10:25;;2275:25887:7;-1:-1:-1;;;;;;;;;;;2532:26:7;6370:40:9;;2275:25887:7;6370:40:9;6347:4;6424:11;:::o;6179:316::-;-1:-1:-1;;;;;2275:25887:7;;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;;;;-1:-1:-1;;;;;2275:25887:7;;;;;-1:-1:-1;;;;;;;;;;;2275:25887:7;;;;;;;-1:-1:-1;;2275:25887:7;;;;;735:10:25;;2275:25887:7;-1:-1:-1;;;;;;;;;;;2459:27:7;6370:40:9;;2275:25887:7;6370:40:9;6347:4;6424:11;:::o;5203:1549:32:-;;;6281:66;6268:79;;6264:164;;2275:25887:7;;;;;;-1:-1:-1;2275:25887:7;;;;;;;;;;;;;;;;;;;6539:24:32;;;;;;;;;-1:-1:-1;6539:24:32;-1:-1:-1;;;;;2275:25887:7;;6577:20:32;6573:113;;6696:49;-1:-1:-1;6696:49:32;-1:-1:-1;5203:1549:32;:::o;6573:113::-;6613:62;-1:-1:-1;6613:62:32;6539:24;6613:62;-1:-1:-1;6613:62:32;:::o;6264:164::-;6363:54;;;6379:1;6363:54;6383:30;6363:54;;:::o;2815:1368:40:-;;3010:14;;;2275:25887:7;;;;;;;;;;;3046:13:40;;;3042:1135;3046:13;;;-1:-1:-1;;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;;;3521:23:40;;;3517:378;;3042:1135;2275:25887:7;;;;;;;;;-1:-1:-1;;2275:25887:7;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;3010:14:40;4112:11;:::o;2275:25887:7:-;;;;;;;;;;;;3517:378:40;2275:25887:7;3584:22:40;3705:23;3584:22;;;:::i;:::-;2275:25887:7;;;;;;3705:23:40;;;;;:::i;:::-;2275:25887:7;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;3517:378:40;;;;;3042:1135;4154:12;;;;2275:25887:7;4154:12:40;:::o;2241:406::-;4360:14;;;2275:25887:7;;;;;;;;;;;4360:26:40;2320:321;2275:25887:7;;;;;;;;;;;;;;4360:14:40;2275:25887:7;;;;;;;:::i;:::-;;;;;;;;;;;;;4360:14:40;2576:11;:::o;2320:321::-;2618:12;;;2275:25887:7;2618:12:40;:::o

Swarm Source

none://164736f6c634300081c000a

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ Download: CSV Export  ]

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.