Abstract Testnet

Contract Diff Checker

Contract Name:
INOFactory

Contract Source Code:

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

import {AccessControlEnumerable} from "openzeppelin-contracts/access/AccessControlEnumerable.sol";
import {Clones} from "openzeppelin-contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "openzeppelin-contracts/security/ReentrancyGuard.sol";

import {IINOFactory} from "./IINOFactory.sol";
import {IINOFactoryInternal} from "./IINOFactoryInternal.sol";
import {IHost} from "../lzApp/interfaces/IHost.sol";
import {IRestrictedWritable} from "../common/writable/restricted/IRestrictedWritable.sol";
import {IINORestricted} from "../ino/writable/restricted/IINORestricted.sol";

import {INOPhase} from "../ino/INOStruct.sol";

import {LzStorage} from "../lzApp/LzStorage.sol";

import {INOStorage} from "../ino/INOStorage.sol";
import {SaleStorage} from "../common/SaleStorage.sol";

/**
 * @title INOFactory
 * @notice Deploy {INO} in single transaction through {createINO}.
 */
contract INOFactory is
    IINOFactory, // 1 inherited component
    IINOFactoryInternal, // 1 inherited component
    AccessControlEnumerable, // 7 inherited component
    ReentrancyGuard // 1 inherited component
{
    /// @inheritdoc IINOFactory
    uint256 public override maxLoop = 100;

    INODetail[] internal _inoDetails;
    mapping(string => address) internal _inoNames;

    /// @inheritdoc IINOFactory
    address public override defaultINO;

    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
    }

    /// @inheritdoc IINOFactory
    function createINO(
        string calldata inoName,
        INOStorage.SetUp calldata inoSetUp,
        SaleStorage.SetUp memory saleSetUp,
        string[] calldata phaseIds,
        INOPhase[] calldata phases
    )
        external
        override
        nonReentrant
        onlyRole(DEFAULT_ADMIN_ROLE)
        returns (address ino)
    {
        (ino) = _createINO(inoName, inoSetUp, saleSetUp, phaseIds, phases);

        emit INOCreated(inoName, ino);
    }

    /// @inheritdoc IINOFactory
    function updateDefaultINO(
        address newDefaultINO
    ) external override onlyRole(DEFAULT_ADMIN_ROLE) {
        if (newDefaultINO == address(0))
            revert INOFactory_DefaultINO_ZeroAddr();

        emit DefaultINOUpdated(defaultINO, newDefaultINO);
        defaultINO = newDefaultINO;
    }

    /// @inheritdoc IINOFactory
    function setMaxLoop(
        uint256 newMaxLoop
    ) external override onlyRole(DEFAULT_ADMIN_ROLE) {
        maxLoop = newMaxLoop;
    }

    /// @inheritdoc IINOFactory
    function getInosDetails(
        uint256 from,
        uint256 to
    )
        external
        view
        override
        returns (
            INODetail[] memory inos,
            uint256 lastEvaludatedIndex,
            uint256 totalItems
        )
    {
        if (from > to) revert INOFactory_IndexesReversed();

        unchecked {
            if ((to - from) > maxLoop) to = from + maxLoop;
            if (to > _inoDetails.length) to = _inoDetails.length;

            inos = new INODetail[](to - from);
            for (uint256 i = from; i < to; ++i) {
                inos[i - from] = _inoDetails[i];
            }
            // loop end when i == to, but last call is _inoDetails[to - 1]
            lastEvaludatedIndex = --to;
        }

        totalItems = _inoDetails.length;
    }

    ///  @dev `saleSetUp` must be `memory` type as it is updated inside the function.
    function _createINO(
        string calldata inoName,
        INOStorage.SetUp calldata inoSetUp,
        SaleStorage.SetUp memory saleSetUp,
        string[] calldata phaseIds,
        INOPhase[] calldata phases
    ) internal returns (address ino) {
        if (address(_inoNames[inoName]) != address(0)) {
            revert INOFactory_INONameExists(inoName);
        }
        if (defaultINO == address(0)) {
            revert INOFactory_DefaultINO_NotSet();
        }

        bytes32 salt = keccak256(abi.encodePacked(_msgSender(), inoName));

        ino = Clones.cloneDeterministic(defaultINO, salt);

        _inoNames[inoName] = ino;
        _inoDetails.push(INODetail(inoName, ino, inoSetUp, saleSetUp));

        IINORestricted(ino).initialize(
            saleSetUp,
            _msgSender(),
            inoSetUp,
            phaseIds,
            phases
        );
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../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 => 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 override 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 override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

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

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

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

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

import {INOStorage} from "../ino/INOStorage.sol";
import {SaleStorage} from "../common/SaleStorage.sol";

import {INOPhase} from "../ino/INOStruct.sol";

/**
 * @title IINOFactory
 * @notice Defines external and public functions for {INOFactory}.
 */
interface IINOFactory {
    /**
     * @notice Clone (minimal proxy - gas saving) and configure an {INO} with its {INOVesting} in a single
     *         transaction.
     * @dev `saleSetUp` must be `memory` type as it is updated in {_createINO}.
     *
     * @param inoName Name of the INO to create and configure.
     * @param inoSetUp Struct to initialize {INO} contract.
     * @param saleSetUp Struct to initialize {INO} contract with shared sale variables from
     *        {SaleWritableInternal}.
     * @param phaseIds Default phases/phase name to create at INO initialization.
     * @param phases Default phases/phase object to create at INO initialization.
     *
     * @return ino New cloned and configured {INO} contract.
     */
    function createINO(
        string calldata inoName,
        INOStorage.SetUp calldata inoSetUp,
        SaleStorage.SetUp memory saleSetUp,
        string[] calldata phaseIds,
        INOPhase[] calldata phases
    ) external returns (address ino);

    /**
     * @notice Update default {INO} to use in {createINO}.
     * @dev If not one of these or both not set, {createINO} will fail with:
     *      - {INOFactory_DefaultINO_NotSet} error.
     *
     * @param newDefaultINO Default {INO} to use for next {createINO} call.
     */
    function updateDefaultINO(address newDefaultINO) external;

    /// @notice Set the maxium amount of loops to be used in {getInosDetails}.
    function setMaxLoop(uint256 newMaxLoop) external;

    /**
     * @notice Get details of many {INO} by batch to index items on frontend.
     *
     * @param from Index to start reading from {_inoDetails}.
     * @param to Index to finish reading from {_inoDetails}.
     *
     * @return inos Details of {INO} requested, from `from` to `to`.
     * @return lastEvaludatedIndex Last index evaluated within the loop - should be `from`.
     * @return totalItems Total amount of {INODetail} fetched.
     */
    function getInosDetails(
        uint256 from,
        uint256 to
    )
        external
        view
        returns (
            IINOFactoryInternal.INODetail[] memory inos,
            uint256 lastEvaludatedIndex,
            uint256 totalItems
        );

    ///////////////// PUBLIC /////////////////
    /// @return return Default {INO}.
    function defaultINO() external returns (address);

    /// @return Maximum amount of loops to use per {getInosDetails} call.
    function maxLoop() external returns (uint256);
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

import {INOStorage} from "../ino/INOStorage.sol";
import {SaleStorage} from "../common/SaleStorage.sol";

/**
 * @title IINOFactoryInternal
 * @notice Internal interface of {INOFactory} which defines structures, events and errors.
 */
interface IINOFactoryInternal {
    /**
     * @notice Struct representing an INO cloned and created by {_createINO} function.
     *
     * @param name Name of the INO.
     * @param ino Address of the {INO} contract cloned.
     * @param inoSetUp Struct to set up newly deployed {INO}.
     * @param saleSetUp Struct to set up newly deployed {INO} with common sale variables.
     */
    struct INODetail {
        string name;
        address ino;
        INOStorage.SetUp inoSetUp;
        SaleStorage.SetUp saleSetUp;
    }

    /**
     * @notice Emitted only in {updateDefaultINO}.
     *
     * @param defaultINO Address of the old default {INO} contract.
     * @param newDefaultINO Address of the new default {INO} contract.
     */
    event DefaultINOUpdated(
        address indexed defaultINO,
        address indexed newDefaultINO
    );
    /**
     * @notice Emitted only in {createINO}.
     *
     * @param inoName Name of the INO.
     * @param ino Address of the {INO} contract cloned and initialized.
     */
    event INOCreated(string indexed inoName, address indexed ino);

    /// @notice Thrown when {defaultINO} is not set.
    error INOFactory_DefaultINO_NotSet();
    /// @notice Thrown when trying to set {defaultINO} as `address(0)` in {updateDefaultINO}.
    error INOFactory_DefaultINO_ZeroAddr();
    /// @notice Thrown when an INO with `name` has already been created.
    error INOFactory_INONameExists(string name);
    /// @notice Thrown when `from` is > `to` in {getInosDetails}.
    error INOFactory_IndexesReversed();
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

/**
 * @title IHost
 * @notice Defines external and public functions for {LzVestingHostChain}.
 */
interface IHost {
    /**
     * @notice Initialize {LzVestingHostChain} contract.
     * @dev Use `reinitializer(2)` as we initialize contract in 2 times:
     * 1. Common parts shared between crosschain and not crosschain IGOVesting
     *    with `initializeCrowdfunding`
     * 2. Crosschain configuration with `init`
     *
     * We could have refactor this into a single function though this would
     * prevent us from using a common method in IGOFactory to deploy IGOs and
     * IGOVesting not matter if crosschain compatible or not.
     *
     * @param lzEndpoint_ Address of the {ILayerZeroEndpoint}, see the official doc:
     * https://layerzero.gitbook.io/docs/technical-reference/mainnet/supported-chain-ids
     * @param hostChain_ Current chain id of where the {IGO} and {LzVestingHostChain} are deployed, using
     *        nomenclature LayerZero.
     * @param targetChain_ Chain id where {LzClaimRefundTargetChain} is deployed, using LayerZero nomenclature.
     */
    function init(
        address lzEndpoint_,
        uint16 hostChain_,
        uint16 targetChain_
    ) external;

    /**
     * @notice Estimate fees for a crosschain transaction by requesting LayerZero endpoint.
     *
     * @param _dstChainId Chain id where the call will be made to, using  LayerZero nomenclature.
     * @param _payload Payload to send to the destination chain - abi.encode(...).
     * @param _useZro Whether to use ZERO token for fees or native (ETH, BNB, ARB, etc...).
     * @param _adapterParams Params to send to the destination chain adapter - abi.encode(...).
     */
    function estimateFee(
        uint16 _dstChainId,
        bytes calldata _payload,
        bool _useZro,
        bytes calldata _adapterParams
    ) external view returns (uint nativeFee, uint zroFee);

    /**
     * @notice Host chain where call are made from, using LayerZero nomenclature.
     */
    function getHostChain() external view returns (uint16);

    /**
     * @notice Target chain where call are made to, using LayerZero nomenclature.
     */
    function getTargetChain() external view returns (uint16);

    ///////////////// PUBLIC /////////////////
    /**
     * @notice Update vesting from crosschain call of {LzClaimRefundTargetChain} contract.
     * @dev Send a call back to target chain to release the right amount of tokens to `_wallet`. Only
     *      LayerZero endpoint can call this function.
     * @custom:audit The only reason this function is made public is to receive native tokens from
     *               LayerZero endpoint. This is a requirement for crosschain ping-pong calls.
     *
     * @param _wallet Address of the wallet which requested to claim their due on target chain from
     *        {LzClaimRefundTargetChain.claim}.
     */
    function hostClaimUpdate(address _wallet) external payable;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

import {IGOStorage} from "../../../igo/IGOStorage.sol";
import {SaleStorage} from "../../SaleStorage.sol";

// import struct
import {Phase} from "../../SaleStruct.sol";

/**
 * @title IRestrictedWritable
 * @notice Only the owner of the contract can call these methods.
 */
interface IRestrictedWritable {
    //////////////////////////// SHARED Sale DATA ////////////////////////////
    /**
     * @notice Close the sale for good.
     * @dev Can be closed at any point in time AND NOT reversible.
     */
    function closeSale() external;

    function openSale() external;

    function pauseSale() external;

    function resumeSale() external;

    /// @dev Retrieve any ERC20 sent to the contract by mistake.
    function recoverLostERC20(address token, address to) external;

    function closePhases(string[] calldata phaseIds) external;

    // TODO: UX choice to make here, do we need both phase single field update and phase batch update?
    //////////////////////////// PHASE SINGLE UPDATE ////////////////////////////
    /**
     * @custom:audit phase can be opened even if it does not exists but as only the owner can update this
     * method we make the asumption that the owner will always be aware of this to save gast costs and it
     * can be paused at any time to update its data so it does not pose a security risk.
     */
    function openPhase(string calldata phaseId) external;

    function pausePhase(string calldata phaseId) external;

    function resumePhase(string calldata phaseId) external;

    function updatePhaseEndDate(
        string calldata phaseId,
        uint128 endAt
    ) external;

    /**
     * @notice Update `maxPhaseCap` which is the maximum amount of tokens that can be sold in a phase
     *         and the merkle root of a phase to update a single or multiple wallet allocation,
     *         refund fee, etc.
     * @dev `maxPhaseCap` is expressed in {SaleStorage.SetUp.paymentToken}.
     *
     * @param phaseId Identifier of the phase.
     * @param merkleRoot New merkle root to be saved for this phase.
     */
    function updatePhaseMaxCapAndMerkleRoot(
        string calldata phaseId,
        uint256 maxPhaseCap,
        bytes32 merkleRoot
    ) external;

    /**
     * @notice Update the merkle root of a phase to update a single or multiple wallet allocation,
     *         refund fee, payment token etc.
     *
     * @param phaseId Identifier of the phase.
     * @param merkleRoot New merkle root to be saved for this phase.
     */
    function updatePhaseMerkleRoot(
        string calldata phaseId,
        bytes32 merkleRoot
    ) external;

    function updatePhaseStartDate(
        string calldata phaseId,
        uint128 startAt
    ) external;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

// import struct
import {Phase} from "../../../common/SaleStruct.sol";
import {INOPhase} from "../../INOStruct.sol";

// storage
import {INOStorage} from "../../INOStorage.sol";
import {SaleStorage} from "../../../common/SaleStorage.sol";

/**
 * @title IINORestricted
 * @notice Only the owner of the contract can call these methods.
 */
interface IINORestricted {
    /**
     * @notice Some projects will only do the sale through INO and will handle the NFT minting themselves.
     *         Others will do the mint and sale through INO. This function is used to deploy the NFT
     *         collection for the second case.
     * @dev Use {reinitializer(2)} as {initialize} is called first.
     *
     * @param nftToClone The address of the NFT to use as an NFT base.
     * @param data Data of the NFT collection to be deployed.
     */
    function deployNftToSell(
        address nftToClone,
        INOStorage.NFTCollectionData calldata data
    ) external returns (address collection);

    /**
     * @notice Use a single token for the whole INO (never changed once set here).
     *
     * @param saleSetUp Data of the sale to be deployed - common logic shared between IGOs and INOs.
     * @param owner Owner of the INO.
     * @param inoSetUp Data of the INO to be deployed.
     * @param phaseIds Default list of phase identifiers - can be empty array `new string[](0)`
     * @param phases Default list of phases - can be empty array `new INOPhase[](0)`
     */
    function initialize(
        SaleStorage.SetUp calldata saleSetUp,
        address owner,
        INOStorage.SetUp calldata inoSetUp,
        string[] calldata phaseIds,
        INOPhase[] calldata phases
    ) external;

    /**
     * @dev Update or create a phase with all its data.
     *
     * @param phaseId_ Identifier of phase to set or update.
     * @param phase_ Struct {INOPhase} containing INO phase's data to be saved.
     */
    function updateSetPhase(
        string calldata phaseId_,
        INOPhase calldata phase_
    ) external;

    /**
     * @dev Update or create multiple phases with all their data.
     *
     * @param phaseIdentifiers_ Array of identifiers of `phases`.
     * @param phases_ Array of struct {INOPhase} containing phases' data to be saved.
     */
    function updateSetPhases(
        string[] calldata phaseIdentifiers_,
        INOPhase[] calldata phases_
    ) external;

    function updatePhaseMaxMintAndMerkleRoot(
        string calldata phaseId,
        uint256 phaseMaxMint,
        bytes32 merkleRoot
    ) external;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

import {Phase} from "../common/SaleStruct.sol";

/**
 * @notice Struct representing a free allocation and user based for a specific phase of a sale.
 *         Whitelisted addresses will mint NFTs for free.
 *
 * @param phaseId Phase identifier of the current sale.
 * @param toMint Amount of NFT to be minted.
 * @param account Wallet address of the buyer.
 */
struct FreeAllocation {
    string phaseId;
    uint256 toMint;
    address account;
}

/**
 * @notice Struct representing the details of a public phase of a sale.
 *
 * @param phaseId Phase identifier of the current sale.
 * @param unitPrice Price of each NFT in this phase.
 * @param maxAllocationPerWallet Maximum amount of tokens that can be spent by a wallet in this phase,
 *          expressed in {SaleStorage.SetUp.paymentToken}.
 */
struct PublicPhaseDetails {
    string phaseId;
    uint256 unitPrice;
    uint256 maxAllocationPerWallet;
}

/**
 * @notice Struct representing a phase of an INO sale.
 *
 * @param base Phase struct from {SaleStruct} shared with IGO sales.
 * @param phaseMaxMint Maximum amount of NFTs that can be minted in this phase.
 */
struct INOPhase {
    Phase base;
    uint256 phaseMaxMint;
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

/**
 * @title LzStorage
 * @notice Mapps the storage layout of LayerZero dependend contracts:
 *         - {LzClaimRefundTargetChain};
 *         - {LzVestingHostChain} contract;
 * @dev Diamond proxy (ERC-2535) storage style.
 */
library LzStorage {
    /**
     * @notice Struct reprensenting data required by all LayerZero calls.
     *
     * @param hostChain Chain id of where the {LzVestingHostChain} is deployed, using LayerZero's
     *        nomenclature.
     * @param targetChain Chain id of where the {LzClaimRefundTargetChain} is deployed, using
     *        LayerZero's nomenclature.
     * @param vestedToken Address of the token to release to the user in {LzClaimRefundTargetChain}.
     */
    struct LzStruct {
        uint16 hostChain;
        uint16 targetChain;
        address vestedToken;
    }

    /// @notice Storage position of {LzStorage} in contracts using it.
    bytes32 public constant LZ_STORAGE = keccak256("lz.storage");

    /**
     * @notice Custom selector to clone and configure {LzClaimRefundTargetChain}.
     * @dev `_crosschainCloneClaim` does not exists, though it helps to identify the
     *      methods to call in {ClaimFactory._nonblockingLzReceive}.
     */
    bytes4 public constant CROSSCHAIN_CLONE_CLAIM_SELECTOR =
        bytes4(
            keccak256(
                "_crosschainCloneClaim(string,address,address,uint16,uint16,address)"
            )
        );
    /**
     * @notice Custom selector to save cloned {LzClaimRefundTargetChain} in {IGOFactory} through
     *         crosschain call from {ClaimFactory.saveCrosschainClaimInHostFactory}.
     */
    bytes4 public constant LINK_CLAIM_TO_IGO__CALLBACK =
        bytes4(keccak256("LINK_CLAIM_TO_IGO__CALLBACK"));

    /// @dev Custom selector to update vesting schedule on host from crosschain call.
    bytes4 public constant LZ_HOSTCLAIM_SELECTOR =
        bytes4(keccak256("hostClaimUpdate(address)"));
    /// @dev Custom selector to release token to user on target chain from crosschain call.
    bytes4 public constant LZ_RELEASE_TOKEN_SELECTOR =
        bytes4(keccak256("_releaseTokenToUser(address,uint256)"));

    /// @dev Custom selector to refun tokens to user on host chain from crosschain call.
    bytes4 public constant LZ_REFUND_SELECTOR =
        bytes4(keccak256("_refundLz(string,address)"));

    /// @return lzStruct Whole storage of {LzClaimRefundTargetChain} and {LzVestingHostChain} contracts.
    function layout() internal pure returns (LzStruct storage lzStruct) {
        bytes32 position = LZ_STORAGE;
        assembly {
            lzStruct.slot := position
        }
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

/**
 * @title INOStorage
 * @notice Mapps the storage layout of the {INO} contract.
 * @dev Diamond proxy (ERC-2535) storage style.
 */
library INOStorage {
    /**
     * @notice Struct reprensenting the main setup of the INO.
     *
     * @param paymentReceiver The address which will receive the funds from the INO.
     * @param projectWallet The address of the project issuing NFTs - transfer ownership once sale closed.
     */
    struct SetUp {
        address paymentReceiver;
        address projectWallet;
    }

    /**
     * @notice Struct reprensenting the data of the NFT collection to be deployed through INO.
     *
     * @param name The name of the NFTs to be minted during the INO.
     * @param symbol The symbol of the NFTs to be minted during the INO.
     * @param uri The base URI of the NFTs to be minted during the INO - only used for reveal on minint,
     *        otherwise the uri will be an empty string (blackbox and reveal date cases).
     * @param maxCap The maximum number of NFTs to be minted during and after (if not sold out) the INO.
     * @param startTokenId The first token id to be minted during the INO.
     */
    struct NFTCollectionData {
        string name;
        string symbol;
        string uri;
        uint256 maxCap;
        uint256 startTokenId;
    }

    /**
     * @notice Struct reprensenting the whole storage layout of the INO contract.
     *
     * @param setUp Struct reprensenting the main setup of the INO - modified by owner interactions only.
     * @param nftData Struct reprensenting the data of the NFT collection to be deployed through INO
     *                - modified by owner interactions only.
     * @param collection The address of the NFT collection to be deployed and minted through INO - modified
     *                   by owner interactions only.
     * @param phaseMaxMint Maximum number of NFTs to be minted in a specific phase - modified by owner
     *                     interactions only.
     * @param mintedInPhase Number of NFTs minted in a specific phase - modified by INO contract
     *                      interaction.
     * @param totalMinted Total number of NFTs minted in the whole INO - modified by INO contract
     *                    interaction.
     */
    struct INOStruct {
        // modified by owner interactions only
        SetUp setUp;
        NFTCollectionData nftData;
        address collection;
        mapping(string => uint256) phaseMaxMint;
        // modified by INO contract interaction
        mapping(string => uint256) mintedInPhase;
        uint256 totalMinted;
    }

    /// @notice Storage position of {INOStruct} in {INO} contract.
    bytes32 public constant INO_STORAGE = keccak256("ino.storage");

    /**
     * @return inoStruct Whole storage of {INO} contract.
     */
    function layout() internal pure returns (INOStruct storage inoStruct) {
        bytes32 position = INO_STORAGE;
        assembly {
            inoStruct.slot := position
        }
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

// import struct
import {Status, Phase} from "./SaleStruct.sol";

/**
 * @author https://github.com/Theo6890
 * @title SaleStorage
 * @notice Mapps the storage layout of the {Sale} contract.
 * @dev Diamond proxy (ERC-2535) storage style.
 */
library SaleStorage {
    /**
     * @notice Struct reprensenting the main setup of the Sale.
     *
     * @param paymentToken Address of the default token used to reserve allocation through the Sale.
     *                     If `address(0)`, it means native token of the chain (ETH, BNB, etc...).
     * @param permit2 Official address of the {Permit2} library deployed by Uniswap.
     */
    struct SetUp {
        address paymentToken;
        address permit2;
    }

    /**
     * @notice Struct reprensenting the setup of each phase of the Sale.
     * @dev Status of the phase is the only value that can be updated by Sale contract itself due to user's
     *      interactions with the contract.
     *
     * @param ids List of all phases identifiers.
     * @param data Mapping of data of each phases.
     */
    struct Phases {
        string[] ids;
        mapping(string => Phase) data;
    }

    /**
     * @notice Struct reprensenting data of the Sale which are always updated by user's interactions with
     *         the Sale contract.
     *
     * @param status Enum representing the current status of the Sale.
     * @param summedMaxPhaseCap Sum of maximum cap of each phase expressed in {SetUp.paymentToken}.
     * @param totalRaised Total amount of paymentToken raised for this Sale,
     *                    expressed in {SetUp.paymentToken}.
     * @param raisedInPhase Amount of paymentToken raised for each phase, expressed in {SetUp.paymentToken}.
     * @param allocationReservedByIn Amount of paymentToken paid by phase by each user,
     *                               expressed in {SetUp.paymentToken}.
     */
    struct Ledger {
        Status status;
        uint256 summedMaxPhaseCap;
        uint256 totalRaised;
        mapping(string => uint256) raisedInPhase;
        mapping(address => mapping(string => uint256)) allocationReservedByIn;
        mapping(address => mapping(string => uint256)) freeAllocationMintedBy;
    }

    /**
     * @notice Struct reprensenting the whole storage layout of the Sale contract.
     *
     * @param setUp reprensenting the main setup of the Sale.
     * @param phases reprensenting the setup of each phase of the Sale.
     * @param ledger reprensenting data of the Sale which are always updated by user's interactions with
     *        the Sale contract.
     */
    struct SaleStruct {
        SetUp setUp;
        Phases phases;
        Ledger ledger;
    }

    /// @notice Storage position of {SaleStruct} in {Sale} contract.
    bytes32 public constant Sale_STORAGE = keccak256("common.storage");

    /**
     * @return igoStruct Whole storage of {Sale} contract.
     */
    function layout() internal pure returns (SaleStruct storage igoStruct) {
        bytes32 position = Sale_STORAGE;
        assembly {
            igoStruct.slot := position
        }
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 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 v4.8.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../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 => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    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 override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @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 override 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 override 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 override 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 `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @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 Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

            return true;
        } else {
            return false;
        }
    }

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

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

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

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

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

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

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

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

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

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

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

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

        return result;
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

/**
 * @author https://github.com/Theo6890
 * @title IGOStorage
 * @notice Mapps the storage layout of the {IGO} contract.
 * @dev Diamond proxy (ERC-2535) storage style.
 */
library IGOStorage {
    /**
     * @notice Struct reprensenting the main setup of the IGO.
     *
     * @param vestingContract Address of the {IGOVesting} contract.
     * @param refundFeeDecimals Number of decimals used for {IIGOWritableInternal.Allocation.refundFee}.
     */
    struct SetUp {
        address vestingContract;
        uint256 refundFeeDecimals;
    }

    /**
     * @notice Struct reprensenting the whole storage layout of the IGO contract.
     *
     * @param setUp Struct reprensenting the main setup of the IGO.
     */
    struct IGOStruct {
        SetUp setUp;
    }

    /// @notice Storage position of {IGOStruct} in {IGO} contract.
    bytes32 public constant IGO_STORAGE = keccak256("igo.storage");

    /**
     * @return igoStruct Whole storage of {IGO} contract.
     */
    function layout() internal pure returns (IGOStruct storage igoStruct) {
        bytes32 position = IGO_STORAGE;
        assembly {
            igoStruct.slot := position
        }
    }
}

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;

/**
 * @notice Shared enum representing the different status of a phase or the whole IGO.
 *
 * @custom:value NOT_STARTED IGO/Phase created but not started; allocations/buyAndMint are allowed.
 * @custom:value OPENED IGO/Phase started according to start date; allocations/buyAndMint are allowed.
 * @custom:value COMPLETED IGO/Phase everything has been sold or time has been elapsed;
 *               allocations/buyAndMint can't be reserved anymore.
 * @custom:value PAUSED IGO/Phase has been paused by the owner; allocations/buyAndMint can't be
 *               reserved until further notice.
 */
enum Status {
    NOT_STARTED,
    OPENED,
    COMPLETED,
    PAUSED
}

/**
 * @notice Struct representing an allocation of a wallet for a specific phase of a sale.
 *
 * @param phaseId Phase identifier of the in the current sale, e.g. "vpr-social-task",
 *        "sale-public-phase-1", "ino-public" etc...
 * @param maxAllocation Maximum amount to spend in {SaleStorage.SetUp.paymentToken}.
 * @param saleTokenPerPaymentToken Price per token/nft of the project behind the Sale, expressed in
 *        {SaleStorage.SetUp.paymentToken}.
 */
struct Allocation {
    string phaseId;
    uint256 maxAllocation;
    uint256 saleTokenPerPaymentToken;
}

/**
 * @notice Struct representing a buy permission signed by `msg.sender` for
 *         {SaleWritable.reserveAllocation} function to use with {Permit2} library.
 *
 * @dev Compulsory to interact with {Permit2.permitTransferFrom} in
 *      {SaleWritableInternal._reserveAllocation}.
 *
 * @param signature {Permit2} signature to transfer tokens from the buyer to {SaleVesting}.
 * @param deadline Seadline on the permit signature.
 * @param nonce Unique value for every token owner's signature to prevent signature replays.
 */
struct BuyPermission {
    bytes signature;
    uint256 deadline;
    uint256 nonce;
}

/**
 * @notice Shared struct representing the data of a phase.
 *
 * @param status Enum representing the current status of the phase.
 * @param rootHash Merkle root hash or hash of a metadata configuration:
          contains keccas256 hash of 3 encoded values:
            1. address(this)
            2. chainid
            3. any of: UserAllocationFee | FreeAllocation | PublicPhaseDetails
 * @param startAt Timestamp at which the phase will be opened to reserve allocation.
 * @param endAt Timestamp at which the phase will not accept allocation reservation anymore.
 * @param maxPhaseCap Maximum amount of {SaleStorage.SetUp.paymentToken} for this phase.
 */
struct Phase {
    Status status;
    bytes32 rootHash;
    uint128 startAt;
    uint128 endAt;
    uint256 maxPhaseCap;
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @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.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

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

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

pragma solidity ^0.8.0;

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

Please enter a contract address above to load the contract details and source code.

Context size (optional):