ICOSale

Description:

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

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

{{
  "language": "Solidity",
  "sources": {
    "src/ICOSale.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { Nonces } from "@openzeppelin/contracts/utils/Nonces.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

import { Utils } from "src/lib/Utils.sol";
import { Errors } from "src/lib/Errors.sol";
import { Constants } from "src/lib/Constants.sol";
import { IICOSale } from "src/interfaces/IICOSale.sol";
import { IOracleAdapter } from "src/interfaces/IOracleAdapter.sol";

/// @title The ICOSale Smart Contract
/// @notice This contract manages the ICO sale process, including rounds, purchases, referrals, and refunds
/// @dev The contract uses OpenZeppelin libraries for security and standard functionalities
contract ICOSale is IICOSale, EIP712, Ownable, ReentrancyGuard, Nonces {
    using SafeERC20 for IERC20;

    /// @notice The enum defining the referral types used for categorizing referrals
    /// @param NoReferral Represents no referral used
    /// @param Influencer Represents referrals made by influencers
    /// @param Media Represents referrals made by media partners
    enum RefType {
        NoReferral,
        Influencer,
        Media
    }

    /// @notice The treasury address where funds will be sent
    address public immutable TREASURY_WALLET;

    /// @notice The oracle adapter for fetching price feeds
    IOracleAdapter public immutable ORACLE_ADAPTER;

    /// @notice The maximum number of tokens available for sale
    uint256 public immutable MAX_TOTAL_ALLOCATION_TOKENS;

    /// @notice The minimum USD amount per transaction available for purchase
    uint256 public minUsdPerTx;

    /// @notice The total USD amount raised across all rounds (normalized to 18 decimals)
    uint256 public totalUsdRaised;

    /// @notice The total number of tokens allocated across all buyers and rounds
    /// @dev This value cannot exceed MAX_TOTAL_ALLOCATION_TOKENS
    uint256 public totalAllocatedTokens;

    /// @notice The current round ID
    uint256 public currentRoundId;

    /// @notice The boolean indicating if the sale has been finalized
    /// @dev Once finalized, no more deposits are allowed
    bool public saleFinalized;

    /// @notice The mapping keeps details of each sale round
    /// @dev The general sale parameters are defined in the Round struct, schema: roundId => Round
    mapping(uint256 => Round) public rounds;

    /// @notice The mapping tracks the approved assets for payment
    /// @dev The key is the token address, and the value indicates if it's approved (true) or not (false)
    mapping(address => bool) public isApprovedAsset;

    /// @notice The mapping tracks the total USD amount raised per wallet (normalized to 18 decimals)
    mapping(address => uint256) public walletUsdRaised;

    /// @notice The mapping tracks the allocation per user across all rounds
    /// @dev The schema is: user address => total allocated tokens
    mapping(address => uint256) public totalBuyerAllocation;

    /// @notice The mapping tracks the round-specific allocation per user
    /// @dev The schema is: round ID => user address => allocated tokens in that round
    mapping(uint256 => mapping(address => uint256)) public roundBuyerAllocation;

    /// @notice The mapping tracks refundable amounts per user and asset
    /// @dev The schema is: user address => token address => refundable amount
    mapping(address => mapping(address => uint256)) public refundable;

    /// @notice The mapping tracks referral bonus basis points by referral type
    /// @dev The key is the referral type (e.g., 0 for no referral, 1 for influencer, etc.), and the value is the bonus in basis points
    mapping(uint8 => uint16) public referralBonusBpsByType;

    /// @notice The mapping tracks total USD raised per referral code (normalized to 18 decimals)
    /// @dev The key is the string of the referral code
    mapping(string => uint256) public refTotalUsd;

    /// @notice The mapping tracks total bonus tokens awarded per referral code
    /// @dev The key is the string of the referral code
    mapping(string => uint256) public refTotalBonusTokens;

    /// @notice Fallback function to receive Ether
    receive() external payable { }

    /// @dev The constructor initializes the contract with essential parameters
    /// @param _owner The owner of the contract
    /// @param _oracle The address of the oracle adapter for price feeds
    /// @param _treasury The address where funds will be sent
    /// @param _maxTotalAllocationTokens The maximum number of tokens available for sale
    constructor(address _owner, address _oracle, address _treasury, uint256 _maxTotalAllocationTokens)
        Ownable(_owner)
        EIP712("ICOSale", "1")
    {
        require(_treasury != address(0) && _oracle != address(0), Errors.ZeroAddress());
        require(_maxTotalAllocationTokens != 0, Errors.ZeroAmount());

        TREASURY_WALLET = _treasury;
        ORACLE_ADAPTER = IOracleAdapter(_oracle);
        MAX_TOTAL_ALLOCATION_TOKENS = _maxTotalAllocationTokens;

        isApprovedAsset[Constants.WETH] = true;
        isApprovedAsset[Constants.USDC] = true;
        isApprovedAsset[Constants.USDT] = true;

        emit SaleInitialized(_owner, _oracle, _treasury, _maxTotalAllocationTokens);
    }

    /// @inheritdoc IICOSale
    function rescueFunds(address _token, uint256 _amount) external nonReentrant onlyOwner {
        require(_amount != 0, Errors.ZeroAmount());

        if (_token != address(0)) {
            IERC20(_token).safeTransfer(TREASURY_WALLET, _amount);
        } else {
            require(_amount <= address(this).balance, Errors.InsufficientBalance());
            Address.sendValue(payable(TREASURY_WALLET), _amount);
        }

        emit FundsRescued(_token, TREASURY_WALLET, _amount, _msgSender());
    }

    /// @inheritdoc IICOSale
    function setMinUsdPerTx(uint256 _minUsdPerTx) external onlyOwner {
        require(_minUsdPerTx != 0, Errors.ZeroAmount());
        minUsdPerTx = _minUsdPerTx;
        emit MinUsdPerTxUpdated(_minUsdPerTx, _msgSender());
    }

    /// @inheritdoc IICOSale
    function setApprovedAsset(address _asset, bool _approved) external onlyOwner {
        require(_asset != address(0), Errors.ZeroAddress());
        require(isApprovedAsset[_asset] != _approved, Errors.IndicatorAlreadySet());
        isApprovedAsset[_asset] = _approved;
        emit PayAssetApprovalSet(_asset, _approved, _msgSender());
    }

    /// @inheritdoc IICOSale
    function setReferralTypeBps(uint8 _refType, uint16 _refPercentage) external onlyOwner {
        require(_refType == uint8(RefType.Influencer) || _refType == uint8(RefType.Media), Errors.InvalidReferralType());
        require(_refPercentage <= Constants.MAX_REFERRAL_PERCENTAGE, Errors.InvalidReferralPercentage());
        referralBonusBpsByType[_refType] = _refPercentage;
        emit ReferralTypePercentageUpdated(_refType, _refPercentage, _msgSender());
    }

    /// @inheritdoc IICOSale
    function finalizeSale() external onlyOwner {
        require(!saleFinalized, Errors.SaleAlreadyFinalized());
        require(currentRoundId + 1 == Constants.MAX_ROUNDS, Errors.OngoingSaleRounds());
        saleFinalized = true;
        if (rounds[currentRoundId].active) rounds[currentRoundId].active = false;
        emit SaleFinalized(totalUsdRaised, _msgSender());
    }

    /// @inheritdoc IICOSale
    function setNewRound(uint256 _startTime, uint256 _endTime, uint256 _tokenPrice, uint256 _capTotal)
        external
        onlyOwner
    {
        require(!saleFinalized, Errors.SaleAlreadyFinalized());
        require(
            _startTime != 0 && _startTime >= block.timestamp && _endTime != 0 && _startTime < _endTime,
            Errors.InvalidTimeframe()
        );
        require(_tokenPrice != 0 && _capTotal != 0, Errors.ZeroAmount());

        if (rounds[currentRoundId].active) rounds[currentRoundId].active = false;

        uint256 newId = (rounds[0].startTime == 0 && currentRoundId == 0) ? 0 : currentRoundId + 1;
        require(newId < Constants.MAX_ROUNDS, Errors.CapReached());
        currentRoundId = newId;

        rounds[currentRoundId] = Round({
            startTime: _startTime,
            endTime: _endTime,
            tokenPrice: _tokenPrice,
            capTotal: _capTotal,
            soldTokens: 0,
            active: true
        });

        emit NewRoundSet(newId, _startTime, _endTime, _tokenPrice, _capTotal);
    }

    /// @inheritdoc IICOSale
    function buyETH(PurchaseDetails calldata _ref, bytes calldata _sig, string calldata _refCodeString)
        external
        payable
        nonReentrant
    {
        require(!saleFinalized, Errors.SaleAlreadyFinalized());
        require(msg.value != 0 && msg.value == _ref.amount, Errors.ZeroAmount());
        require(_ref.refCode == keccak256(bytes(_refCodeString)), Errors.InvalidReferralCode());
        require(_ref.asset == Constants.WETH || _ref.asset == address(0), Errors.NotAcceptedAsset());

        if (_ref.refType != uint8(RefType.NoReferral)) {
            require(
                _ref.refCode != keccak256(bytes(""))
                    && (_ref.refType == uint8(RefType.Influencer) || _ref.refType == uint8(RefType.Media)),
                Errors.InvalidReferralType()
            );
        } else {
            require(_ref.refCode == keccak256(bytes("")), Errors.InvalidReferralCode());
        }

        _verifyReferralSignature(_ref, _sig);

        Address.sendValue(payable(TREASURY_WALLET), msg.value);
        refundable[_msgSender()][address(0)] += msg.value;

        _buyChecksAndEffects(_ref.asset, _ref.amount, _msgSender(), _refCodeString, _ref.refType);
    }

    /// @inheritdoc IICOSale
    function buyToken(PurchaseDetails calldata _ref, bytes calldata _sig, string calldata _refCodeString)
        external
        nonReentrant
    {
        require(!saleFinalized, Errors.SaleAlreadyFinalized());
        require(_ref.amount != 0, Errors.ZeroAmount());
        require(_ref.refCode == keccak256(bytes(_refCodeString)), Errors.InvalidReferralCode());
        require(_ref.asset != address(0) && isApprovedAsset[_ref.asset], Errors.NotAcceptedAsset());

        if (_ref.refType != uint8(RefType.NoReferral)) {
            require(
                _ref.refCode != keccak256(bytes(""))
                    && (_ref.refType == uint8(RefType.Influencer) || _ref.refType == uint8(RefType.Media)),
                Errors.InvalidReferralType()
            );
        } else {
            require(_ref.refCode == keccak256(bytes("")), Errors.InvalidReferralCode());
        }

        _verifyReferralSignature(_ref, _sig);

        IERC20(_ref.asset).safeTransferFrom(_msgSender(), TREASURY_WALLET, _ref.amount);
        refundable[_msgSender()][_ref.asset] += _ref.amount;

        _buyChecksAndEffects(_ref.asset, _ref.amount, _msgSender(), _refCodeString, _ref.refType);
    }

    /// @dev Internal function to handle purchase checks and state updates
    /// @param _payAsset The address of the asset used for payment
    /// @param _payAmount The amount of the asset used for payment
    /// @param _buyer The address of the buyer
    /// @param _refCode The referral code used (if any)
    /// @param _refType The type of referral (if any)
    function _buyChecksAndEffects(
        address _payAsset,
        uint256 _payAmount,
        address _buyer,
        string calldata _refCode,
        uint8 _refType
    ) internal {
        Round storage r = rounds[currentRoundId];
        require(r.active, Errors.InactiveRound());
        require(block.timestamp >= r.startTime && block.timestamp <= r.endTime, Errors.InvalidTimeframe());

        if (_payAsset == address(0)) _payAsset = Constants.WETH;

        uint256 normalizedAmount = Utils._normalizeTo18Decimals(_payAsset, _payAmount);
        uint256 priceAsset = ORACLE_ADAPTER.getPriceInUSD(_payAsset);
        uint256 usdValue = normalizedAmount * priceAsset / 1 ether;

        require(usdValue >= minUsdPerTx, Errors.UnderMin());
        require(totalUsdRaised + usdValue <= Constants.HARD_CAP_USD, Errors.HardCapExceeded());
        require(walletUsdRaised[_buyer] + usdValue <= Constants.MAX_USD_PER_WALLET, Errors.WalletCapExceeded());

        uint256 base = usdValue * 1 ether / r.tokenPrice;
        uint256 refBonus =
            (bytes(_refCode).length != 0) ? base * referralBonusBpsByType[_refType] / Constants.BASIS_FEE_DIVISOR : 0;
        uint256 toBuyer = base + refBonus;

        require(toBuyer <= (r.capTotal - r.soldTokens), Errors.CapReached());
        require(toBuyer <= (MAX_TOTAL_ALLOCATION_TOKENS - totalAllocatedTokens), Errors.CapReached());

        totalUsdRaised += usdValue;
        walletUsdRaised[_buyer] += usdValue;

        r.soldTokens += toBuyer;
        roundBuyerAllocation[currentRoundId][_buyer] += toBuyer;
        totalBuyerAllocation[_buyer] += toBuyer;
        totalAllocatedTokens += toBuyer;

        if (bytes(_refCode).length != 0) {
            refTotalUsd[_refCode] += usdValue;
            refTotalBonusTokens[_refCode] += refBonus;
        }

        emit Purchased(
            currentRoundId, _buyer, _refCode, _refType, _payAsset, normalizedAmount, usdValue, base, refBonus, toBuyer
        );
    }

    /// @dev Internal function to verify the referral signature and update the nonce
    /// @param _ref The referral details structure
    /// @param _signature The EIP-712 signature to verify
    function _verifyReferralSignature(PurchaseDetails calldata _ref, bytes calldata _signature) internal {
        require(_ref.buyer == _msgSender(), Errors.NotBuyer());
        require(_ref.roundId == currentRoundId, Errors.InactiveRound());
        require(_ref.nonce == nonces(_ref.buyer), Errors.NonceMismatch());
        require(_ref.deadline >= block.timestamp, Errors.ExpiredSignature());

        bytes32 digest = _hashTypedDataV4(
            keccak256(
                abi.encode(
                    Constants._REFERRAL_TYPEHASH,
                    _ref.refCode,
                    _ref.refType,
                    _ref.buyer,
                    _ref.asset,
                    _ref.amount,
                    _ref.roundId,
                    _ref.nonce,
                    _ref.deadline
                )
            )
        );
        address recoveredAddress = ECDSA.recover(digest, _signature);

        require(recoveredAddress == owner(), Errors.InvalidSignature());
        _useNonce(_ref.buyer);
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/utils/Nonces.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
pragma solidity ^0.8.20;

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

    mapping(address account => uint256) private _nonces;

    /**
     * @dev Returns the next unused nonce for an address.
     */
    function nonces(address owner) public view virtual returns (uint256) {
        return _nonces[owner];
    }

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

    /**
     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
     */
    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
        uint256 current = _useNonce(owner);
        if (nonce != current) {
            revert InvalidAccountNonce(owner, current);
        }
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/utils/Address.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Address.sol)

pragma solidity ^0.8.20;

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

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

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

        (bool success, bytes memory returndata) = recipient.call{value: amount}("");
        if (!success) {
            _revert(returndata);
        }
    }

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

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

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

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

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

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                revert(add(returndata, 0x20), mload(returndata))
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/access/Ownable.sol": {
      "content": "// 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);
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/utils/cryptography/ECDSA.sol": {
      "content": "// 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);
        }
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/utils/cryptography/EIP712.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.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;
    // slither-disable-next-line constable-states
    string private _nameFallback;
    // slither-disable-next-line constable-states
    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);
    }

    /// @inheritdoc IERC5267
    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);
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/utils/ReentrancyGuard.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @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 EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * 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;

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

    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
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // 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;
    }
}
"
    },
    "dependencies/@openzeppelin-contracts-5.4.0/token/ERC20/utils/SafeERC20.sol": {
      "content": "// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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);
    }
}
"
    },
    "src/lib/Utils.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { Constants } from "src/lib/Constants.sol";

/// @notice The Utils library provides utility functions for normalizing amounts to different decimal places
/// @dev It includes functions to normalize amounts to 18 decimals and to convert from 18 decimals to 6 decimals
library Utils {
    /// @dev Returns the normalized amount to 18 decimals
    /// @param asset The address of the asset (token)
    /// @param amount The amount to normalize
    /// @return normalizedAmount The normalized amount in 18 decimals
    function _normalizeTo18Decimals(address asset, uint256 amount) internal view returns (uint256 normalizedAmount) {
        if (asset == Constants.WETH) return amount;
        uint8 fromDecimals = IERC20Metadata(asset).decimals();
        normalizedAmount = _convertDecimals(amount, fromDecimals, 18);
    }

    /// @dev Converts an `amount` from one decimal‐precision to another
    /// @param amount The raw amount in `fromDecimals` precision
    /// @param fromDecimals The number of decimals in `amount`
    /// @param toDecimals The target number of decimals
    /// @return converted The same input value, expressed in `toDecimals` precision
    function _convertDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals)
        private
        pure
        returns (uint256 converted)
    {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            unchecked {
                return amount * (10 ** (toDecimals - fromDecimals));
            }
        } else {
            unchecked {
                return amount / (10 ** (fromDecimals - toDecimals));
            }
        }
    }
}
"
    },
    "src/lib/Errors.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title Errors Library
/// @notice This library contains custom error definitions for the core SCs
library Errors {
    /// @dev The custom error for zero address inputs
    error ZeroAddress();
    /// @dev The custom error for input zero amount re purchase params
    error ZeroAmount();
    /// @dev The custom error for minimum amount violations
    error UnderMin();
    /// @dev The custom error for maximum amount violations - e.g. cap reached
    error CapReached();
    /// @dev The custom error for maximum amount violations - e.g. max allocation exceeded
    error HardCapExceeded();
    /// @dev The custom error for maximum wallet cap violations - e.g. max allocation per wallet exceeded
    error WalletCapExceeded();
    /// @dev The custom error for insufficient balance cases
    error InsufficientBalance();
    /// @dev The custom error for different lengths of arrays when they are expected to be the same
    error LengthMismatch();
    /// @dev The custom error for cases when the boolean indicator already set to expected value
    error IndicatorAlreadySet();
    /// @dev The custom error for early manual price updates
    error EarlyManualUpdate();
    /// @dev The custom error for stale manual price updates
    error StaleManualPrice();
    /// @dev The custom error for stale price feed updates
    error StalePriceFeed();
    /// @dev The custom error for incorrect timeframe inputs
    error InvalidTimeframe();
    /// @dev The custom error for invalid buyer bonus inputs
    error InvalidBuyerBonus();
    /// @dev The custom error for cases when the current round is active
    error ActiveRoundExists();
    /// @dev The custom error for cases when the current round is not active
    error InactiveRound();
    /// @dev The custom error for cases when the provided asset is not accepted for payment
    error NotAcceptedAsset();
    /// @dev The custom error for cases when the sale has not already been finalized
    error SaleNotFinished();
    /// @dev The custom error for cases when the sale has already been finalized
    error SaleAlreadyFinalized();
    /// @dev The custom error for cases when there are ongoing sale rounds
    error OngoingSaleRounds();
    /// @dev The custom error for cases when the provided referral type is invalid
    error InvalidReferralType();
    /// @dev The custom error for cases when the provided referral code is invalid
    error InvalidReferralCode();
    /// @dev The custom error for cases when the provided referral percentage is invalid
    error InvalidReferralPercentage();
    /// @dev The custom error for cases when the signature's deadline has expired
    error ExpiredSignature();
    /// @dev The custom error for cases when the signature is invalid
    error InvalidSignature();
    /// @dev The custom error for cases when the nonce does not match the expected value
    error NonceMismatch();
    /// @dev The custom error for cases when the buyer address does not match the caller's address
    error NotBuyer();
}
"
    },
    "src/lib/Constants.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title Constants library
/// @notice This library contains constants for the core SCs
library Constants {
    /// @dev The maximum number of rounds allowed in the ICO sale
    uint256 public constant MAX_ROUNDS = 10;

    /// @notice The constant defining the hard cap in USD (normalized to 18 decimals)
    uint256 public constant HARD_CAP_USD = 5_565_000 * 1 ether;

    /// @notice The constant defining the maximum USD amount per wallet (normalized to 18 decimals)
    uint256 public constant MAX_USD_PER_WALLET = 50_000 * 1 ether;

    /// @dev The maximum referral percentage (10%)
    uint256 internal constant MAX_REFERRAL_PERCENTAGE = 1_000;
    /// @dev The divisor (10_000 - 100%) to calculate the percentage
    uint16 internal constant BASIS_FEE_DIVISOR = 10_000;

    /// @dev The typehash for the PurchaseDetails structure used in EIP-712 signatures
    bytes32 internal constant _REFERRAL_TYPEHASH = keccak256(
        "PurchaseDetails(bytes32 refCode,uint8 refType,address buyer,address asset,uint256 amount,uint256 roundId,uint256 nonce,uint256 deadline)"
    );

    /// @dev The address of the USDC token on Ethereum mainnet
    address internal constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
    /// @dev The address of the USDT token on Ethereum mainnet
    address internal constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
    /// @dev The address of the WETH token on Ethereum mainnet
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
"
    },
    "src/interfaces/IICOSale.sol": {
      "content": "// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.29;

/// @title The ICOSale Interface
/// @notice This interface defines the structures, events and function's prototypes for the ICOSale contract
interface IICOSale {
    /// @notice The structure defines the parameters for each sale round
    /// @param startTime The start time of the sale round (timestamp)
    /// @param endTime The end time of the sale round (timestamp)
    /// @param tokenPrice The price of the token in USD, normalized to 18 decimals
    /// @param capTotal The total cap of tokens available for sale in this round
    /// @param soldTokens The number of tokens sold in this round
    /// @param active The boolean indicating if the round is active
    struct Round {
        uint256 startTime;
        uint256 endTime;
        uint256 tokenPrice;
        uint256 capTotal;
        uint256 soldTokens;
        bool active;
    }

    /// @notice The structure defines the purchase details including referral information
    /// @param refCode The referral code used for the purchase (if any)
    /// @param refType The type of referral (e.g., 0 for influencer, 1 for media, etc.)
    /// @param buyer The address of the buyer making the purchase
    /// @param asset The address of the asset (token) used for payment
    /// @param amount The amount of the asset used for payment
    /// @param roundId The ID of the sale round
    /// @param nonce The unique nonce to prevent replay attacks
    /// @param deadline The timestamp by which the referral must be used
    struct PurchaseDetails {
        bytes32 refCode;
        uint8 refType;
        address buyer;
        address asset;
        uint256 amount;
        uint256 roundId;
        uint256 nonce;
        uint256 deadline;
    }

    /// @dev The event is triggered whenever the sale is initialized while SC creation
    /// @param owner The owner of the contract
    /// @param oracle The address of the oracle adapter for price feeds
    /// @param treasury The address where funds will be sent
    /// @param maxTotalAllocationTokens The maximum number of tokens available for sale
    event SaleInitialized(
        address indexed owner, address indexed oracle, address indexed treasury, uint256 maxTotalAllocationTokens
    );

    /// @dev The event is triggered whenever alien funds (leftovers) are rescued from the SC
    /// @param token The address of the token being rescued, use address(0) for ETH
    /// @param recipient The address receiving the rescued funds - usually the treasury
    /// @param amount The amount of tokens rescued
    /// @param admin The address of the admin who performed the rescue
    event FundsRescued(address indexed token, address indexed recipient, uint256 amount, address indexed admin);

    /// @dev The event is triggered whenever a new minimum USD per transaction is set
    /// @param newMinUsdPerTx The new minimum USD amount per transaction
    /// @param adm

Tags:
ERC20, ERC165, Multisig, Upgradeable, Multi-Signature, Factory, Oracle|addr:0xb687f2f2a77799e560d3568f51b4ad9218e5390b|verified:true|block:23685103|tx:0xe82316681a477a2951738af1bfd9823b3fe5413c9d6424ac773b97d3aeb207e6|first_check:1761766182

Submitted on: 2025-10-29 20:29:44

Comments

Log in to comment.

No comments yet.