Skip to content
Verified contractExactMIT

Presale

Address0x87af0b601df7edee09255d99a16b37f327a10fdc
Balance

0 ETH

 

Transactions

35

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,146,282
Creation transaction
0x9d67ebb6c6…343c41cdb3

project/src/Presale.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

import {AggregatorV3Interface} from "./interfaces/AggregatorV3Interface.sol";
import {IReferralRegistry} from "./interfaces/IReferralRegistry.sol";

/**
 * Staged token presale. Buyers pay in ETH, USDT or USDC and receive the sale
 * token immediately from this contract's pre-funded balance. Payment is
 * forwarded to the treasury in the same transaction — this contract never
 * holds funds between transactions.
 *
 * Units, because mixing them is the classic presale bug:
 *
 *   USD          8 decimals   ($0.015 -> 1_500_000)  matches Chainlink ETH/USD
 *   ETH         18 decimals
 *   USDT/USDC    6 decimals
 *   sale token  read from the token itself, expected 18
 *
 * Every conversion goes through _paymentToUsd / _usdToTokens. These mirror
 * src/lib/presale-math.ts in the web app exactly, including floor division —
 * a test fuzzes both against each other. If you change one, change both, or
 * the UI will quote a number the chain does not honour.
 */
contract Presale is Ownable2Step, Pausable, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint256 private constant USD_BASE = 1e8;
    uint256 private constant BPS = 10_000;
    /// Chainlink ETH/USD reports 8 decimals on every network this deploys to.
    uint8 private constant FEED_DECIMALS = 8;
    /// The furthest ahead the opening can be set — also what keeps startsAt
    /// inside uint64.
    uint256 public constant MAX_START_DELAY = 365 days;

    struct Stage {
        uint256 priceUsd8; // USD per whole token, 8 decimals
        uint256 allocation; // sale-token base units offered in this stage
        uint256 sold; // sale-token base units already sold in this stage
        uint64 endsAt; // unix seconds; 0 = no deadline
    }

    struct AcceptedToken {
        bool accepted;
        uint8 decimals;
    }

    IERC20 public immutable saleToken;
    uint256 private immutable tokenBase; // 10 ** saleToken.decimals()

    address public treasury;
    AggregatorV3Interface public ethUsdFeed;
    /// Reject a feed answer older than this many seconds (C3.3).
    uint256 public feedStaleAfter = 1 hours;

    /// Unix seconds when buying opens: deploy time + the constructor's delay.
    /// The owner can move it while the sale has not opened yet, never after.
    /// Until then both buy paths revert with SaleNotStarted, so the presale
    /// can be configured and funded on mainnet without anyone buying early.
    uint64 public startsAt;

    Stage[] private stages;
    /// 0-based index into `stages`. The public getters expose 1-based numbers,
    /// which is what the UI and the plan use.
    uint256 private stageIdx;

    mapping(address => AcceptedToken) public acceptedTokens;

    uint256 public minBuyUsd8; // per purchase
    uint256 public maxBuyUsd8; // cumulative per wallet; 0 = unlimited

    IReferralRegistry public referralRegistry; // address(0) = referrals off
    /// Hard ceiling on what a referral registry can claim from one purchase.
    uint256 public maxCommissionBps = 2_000; // 20%

    uint256 public totalSold;
    uint256 public totalRaisedUsd8;
    uint256 public participants;
    mapping(address => uint256) public purchasedUsd8;

    event Purchased(
        address indexed buyer,
        uint256 indexed stage,
        address indexed asset,
        uint256 paid,
        uint256 usd8,
        uint256 tokens,
        uint256 referralId
    );
    event CommissionPaid(uint256 indexed referralId, address indexed referrer, uint256 tokens);
    event StageAdvanced(uint256 indexed from, uint256 indexed to, string reason);
    event StageConfigured(uint256 indexed stage, uint256 priceUsd8, uint256 allocation, uint64 endsAt);
    event TreasuryChanged(address indexed treasury);
    event FeedChanged(address indexed feed, uint256 staleAfter);
    event LimitsChanged(uint256 minBuyUsd8, uint256 maxBuyUsd8);
    event AcceptedTokenSet(address indexed token, bool accepted, uint8 decimals);
    event ReferralRegistryChanged(address indexed registry, uint256 maxCommissionBps);
    event Recovered(address indexed token, address indexed to, uint256 amount);
    event StartTimeChanged(uint64 startsAt);

    error ZeroAddress();
    error SaleNotStarted(uint64 startsAt);
    error SaleAlreadyStarted(uint64 startsAt);
    error InvalidStartTime(uint256 startsAt);
    error SaleNotConfigured();
    error NothingToBuy();
    error BelowMinimum(uint256 usd8, uint256 minUsd8);
    error AboveWalletCap(uint256 totalUsd8, uint256 maxUsd8);
    error StageSoldOut(uint256 stage, uint256 remaining);
    error SaleFinished();
    error Underfunded(uint256 needed, uint256 available);
    error TokenNotAccepted(address token);
    error StaleFeed(uint256 updatedAt, uint256 staleAfter);
    error BadFeedAnswer(int256 answer);
    error UnexpectedFeedDecimals(uint8 decimals);
    error TreasuryTransferFailed();
    error PastStage(uint256 stage);
    error AllocationBelowSold(uint256 allocation, uint256 sold);
    error ReservedBalance(uint256 requested, uint256 free);

    /// @param startDelay seconds from deployment until buying opens. 0 opens
    /// it at once (local chain, tests); mainnet deploys with 24 hours.
    constructor(address saleToken_, address treasury_, address feed_, address owner_, uint256 startDelay)
        Ownable(owner_)
    {
        if (saleToken_ == address(0) || treasury_ == address(0) || feed_ == address(0)) revert ZeroAddress();
        if (startDelay > MAX_START_DELAY) revert InvalidStartTime(block.timestamp + startDelay);

        saleToken = IERC20(saleToken_);
        tokenBase = 10 ** IERC20Metadata(saleToken_).decimals();
        treasury = treasury_;
        _setFeed(feed_, feedStaleAfter);
        startsAt = uint64(block.timestamp + startDelay);

        emit TreasuryChanged(treasury_);
        emit StartTimeChanged(startsAt);
    }

    /// Buying is closed until startsAt, whatever else is configured. Checked
    /// before anything else, so an early buyer is told the sale has not
    /// opened rather than some secondary reason (a stale feed, say).
    modifier whenStarted() {
        if (block.timestamp < startsAt) revert SaleNotStarted(startsAt);
        _;
    }

    // ── Buying ───────────────────────────────────────────────────────────────

    /// @param referralId registry id of the referrer, or 0 for none.
    function buyWithETH(uint256 referralId) external payable whenStarted nonReentrant whenNotPaused {
        if (msg.value == 0) revert NothingToBuy();

        uint256 usd8 = _paymentToUsd(msg.value, 18, true);
        uint256 tokens = _settle(msg.sender, address(0), msg.value, usd8, referralId);

        // Forward before delivering tokens; both still land in this tx (C3.6).
        (bool ok,) = treasury.call{value: msg.value}("");
        if (!ok) revert TreasuryTransferFailed();

        _deliver(msg.sender, tokens);
    }

    /// Buy with USDT or USDC. Requires an allowance to this contract first —
    /// see approvalPlan() in the web app for the USDT two-step case.
    function buyWithToken(address token, uint256 amount, uint256 referralId)
        external
        whenStarted
        nonReentrant
        whenNotPaused
    {
        AcceptedToken memory cfg = acceptedTokens[token];
        if (!cfg.accepted) revert TokenNotAccepted(token);
        if (amount == 0) revert NothingToBuy();

        uint256 usd8 = _paymentToUsd(amount, cfg.decimals, false);
        uint256 tokens = _settle(msg.sender, token, amount, usd8, referralId);

        // Straight from buyer to treasury — the payment never rests here.
        // SafeERC20 because USDT returns no bool.
        IERC20(token).safeTransferFrom(msg.sender, treasury, amount);

        _deliver(msg.sender, tokens);
    }

    /// Shared accounting for both buy paths. Runs every check and writes every
    /// state change; the caller then moves the funds and the tokens.
    function _settle(address buyer, address asset, uint256 paid, uint256 usd8, uint256 referralId)
        private
        returns (uint256 tokens)
    {
        if (stages.length == 0) revert SaleNotConfigured();

        _syncStage();
        uint256 idx = stageIdx;
        Stage storage stage = stages[idx];

        if (usd8 < minBuyUsd8) revert BelowMinimum(usd8, minBuyUsd8);

        uint256 walletTotal = purchasedUsd8[buyer] + usd8;
        if (maxBuyUsd8 != 0 && walletTotal > maxBuyUsd8) revert AboveWalletCap(walletTotal, maxBuyUsd8);

        tokens = _usdToTokens(usd8, stage.priceUsd8);
        if (tokens == 0) revert NothingToBuy();

        // Single-stage fill, on purpose: the UI quotes at one price
        // (usdToTokens in presale-math.ts). Spanning a boundary would deliver
        // fewer tokens than quoted, so it reverts and the UI caps the input
        // using remainingInStage() instead.
        uint256 remaining = stage.allocation - stage.sold;
        if (tokens > remaining) revert StageSoldOut(idx + 1, remaining);

        uint256 commission = _commissionTokens(referralId, buyer, usd8, tokens, stage.priceUsd8);

        uint256 needed = tokens + commission;
        uint256 available = saleToken.balanceOf(address(this));
        if (available < needed) revert Underfunded(needed, available);

        stage.sold += tokens;
        totalSold += tokens;
        totalRaisedUsd8 += usd8;
        if (purchasedUsd8[buyer] == 0) participants++;
        purchasedUsd8[buyer] = walletTotal;

        emit Purchased(buyer, idx + 1, asset, paid, usd8, tokens, referralId);

        if (commission > 0) _payCommission(referralId, buyer, usd8, commission);

        // Roll over immediately so the next buyer sees the new price.
        if (stage.sold == stage.allocation) _advance("sold out");
    }

    function _deliver(address buyer, uint256 tokens) private {
        saleToken.safeTransfer(buyer, tokens);
    }

    // ── Referrals ────────────────────────────────────────────────────────────

    function _commissionTokens(
        uint256 referralId,
        address buyer,
        uint256 usd8,
        uint256 tokens,
        uint256 priceUsd8
    ) private view returns (uint256) {
        IReferralRegistry registry = referralRegistry;
        if (address(registry) == address(0) || referralId == 0) return 0;

        uint256 commissionUsd8 = registry.commissionUsd8(referralId, buyer, usd8);
        if (commissionUsd8 == 0) return 0;

        uint256 commission = _usdToTokens(commissionUsd8, priceUsd8);

        // The registry is a separate contract; never let it name its own
        // number without a ceiling this contract controls.
        uint256 cap = (tokens * maxCommissionBps) / BPS;
        return commission > cap ? cap : commission;
    }

    function _payCommission(uint256 referralId, address buyer, uint256 usd8, uint256 commission) private {
        IReferralRegistry registry = referralRegistry;
        saleToken.safeTransfer(address(registry), commission);
        address referrer = registry.recordPurchase(referralId, buyer, usd8, commission);
        emit CommissionPaid(referralId, referrer, commission);
    }

    // ── Pricing maths — mirrors src/lib/presale-math.ts ───────────────────────

    /// Payment amount -> USD at 8 decimals. Floor division, like the UI.
    function _paymentToUsd(uint256 amount, uint8 assetDecimals, bool isNative)
        private
        view
        returns (uint256)
    {
        uint256 assetBase = 10 ** assetDecimals;
        return isNative ? (amount * ethUsd8()) / assetBase : (amount * USD_BASE) / assetBase;
    }

    /// USD (8dp) -> sale-token base units at the given stage price.
    function _usdToTokens(uint256 usd8, uint256 priceUsd8) private view returns (uint256) {
        if (usd8 == 0 || priceUsd8 == 0) return 0;
        return (usd8 * tokenBase) / priceUsd8;
    }

    /// Live ETH/USD price, 8 decimals. Reverts rather than returning a stale
    /// or negative answer — a bad price here mints tokens at the wrong rate.
    function ethUsd8() public view returns (uint256) {
        (uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) =
            ethUsdFeed.latestRoundData();

        if (answer <= 0) revert BadFeedAnswer(answer);
        if (updatedAt == 0 || answeredInRound < roundId) revert StaleFeed(updatedAt, feedStaleAfter);
        if (block.timestamp - updatedAt > feedStaleAfter) revert StaleFeed(updatedAt, feedStaleAfter);

        return uint256(answer);
    }

    // ── Stages ───────────────────────────────────────────────────────────────

    /// Advance past any stage that has sold out or run past its deadline.
    function _syncStage() private {
        uint256 len = stages.length;
        while (stageIdx < len - 1) {
            Stage storage s = stages[stageIdx];
            if (s.sold >= s.allocation) {
                _advance("sold out");
            } else if (s.endsAt != 0 && block.timestamp >= s.endsAt) {
                _advance("deadline");
            } else {
                break;
            }
        }
        Stage storage last = stages[stageIdx];
        if (last.sold >= last.allocation) revert SaleFinished();
        if (last.endsAt != 0 && block.timestamp >= last.endsAt) revert SaleFinished();
    }

    function _advance(string memory reason) private {
        if (stageIdx + 1 >= stages.length) return;
        uint256 from = stageIdx;
        stageIdx = from + 1;
        emit StageAdvanced(from + 1, stageIdx + 1, reason);
    }

    /// Admin-triggered rollover (C3.2). Unsold tokens stay unsold — the next
    /// stage sells its own allocation at its own price.
    function advanceStage() external onlyOwner {
        if (stageIdx + 1 >= stages.length) revert SaleFinished();
        _advance("admin");
    }

    // ── Views the UI reads ───────────────────────────────────────────────────

    /// 1-based, matching Stage.index in src/config/presale.ts.
    function currentStage() external view returns (uint256) {
        return stageIdx + 1;
    }

    function stageCount() external view returns (uint256) {
        return stages.length;
    }

    /// @param stage 1-based.
    function stageAt(uint256 stage) external view returns (Stage memory) {
        return stages[stage - 1];
    }

    function remainingInStage() external view returns (uint256) {
        Stage storage s = stages[stageIdx];
        return s.allocation - s.sold;
    }

    /// What `amount` of `asset` buys right now. asset == address(0) means ETH.
    /// This is the number the UI shows before the user signs.
    function quote(address asset, uint256 amount) external view returns (uint256 tokens, uint256 usd8) {
        if (asset == address(0)) {
            usd8 = _paymentToUsd(amount, 18, true);
        } else {
            AcceptedToken memory cfg = acceptedTokens[asset];
            if (!cfg.accepted) revert TokenNotAccepted(asset);
            usd8 = _paymentToUsd(amount, cfg.decimals, false);
        }
        tokens = _usdToTokens(usd8, stages[stageIdx].priceUsd8);
    }

    /// Sale tokens this contract can still sell without breaking a promise.
    function unsoldAllocation() public view returns (uint256 total) {
        uint256 len = stages.length;
        for (uint256 i = stageIdx; i < len; i++) {
            total += stages[i].allocation - stages[i].sold;
        }
    }

    // ── Admin ────────────────────────────────────────────────────────────────

    /// Move the opening — to an announced launch time, or later if the handover
    /// runs long. Only while the sale has not opened, and only to a moment
    /// still ahead: once anyone could have bought, the start is history.
    function setStartsAt(uint64 newStartsAt) external onlyOwner {
        if (block.timestamp >= startsAt) revert SaleAlreadyStarted(startsAt);
        if (newStartsAt <= block.timestamp || newStartsAt > block.timestamp + MAX_START_DELAY) {
            revert InvalidStartTime(newStartsAt);
        }
        startsAt = newStartsAt;
        emit StartTimeChanged(newStartsAt);
    }

    /// Append a stage. Stages are sold in the order they are added.
    function addStage(uint256 priceUsd8, uint256 allocation, uint64 endsAt) external onlyOwner {
        if (priceUsd8 == 0 || allocation == 0) revert NothingToBuy();
        stages.push(Stage({priceUsd8: priceUsd8, allocation: allocation, sold: 0, endsAt: endsAt}));
        emit StageConfigured(stages.length, priceUsd8, allocation, endsAt);
    }

    /// @param stage 1-based. Only the current stage or a later one, and never
    /// below what that stage has already sold.
    function configureStage(uint256 stage, uint256 priceUsd8, uint256 allocation, uint64 endsAt)
        external
        onlyOwner
    {
        uint256 i = stage - 1;
        if (i < stageIdx) revert PastStage(stage);
        if (priceUsd8 == 0) revert NothingToBuy();

        Stage storage s = stages[i];
        if (allocation < s.sold) revert AllocationBelowSold(allocation, s.sold);

        s.priceUsd8 = priceUsd8;
        s.allocation = allocation;
        s.endsAt = endsAt;
        emit StageConfigured(stage, priceUsd8, allocation, endsAt);
    }

    function setTreasury(address treasury_) external onlyOwner {
        if (treasury_ == address(0)) revert ZeroAddress();
        treasury = treasury_;
        emit TreasuryChanged(treasury_);
    }

    function setFeed(address feed_, uint256 staleAfter) external onlyOwner {
        _setFeed(feed_, staleAfter);
    }

    function _setFeed(address feed_, uint256 staleAfter) private {
        if (feed_ == address(0)) revert ZeroAddress();
        if (staleAfter == 0) revert NothingToBuy();

        // All USD in this contract is 8dp. A feed with different decimals would
        // silently misprice every ETH buy, so refuse it at config time.
        uint8 dec = AggregatorV3Interface(feed_).decimals();
        if (dec != FEED_DECIMALS) revert UnexpectedFeedDecimals(dec);

        ethUsdFeed = AggregatorV3Interface(feed_);
        feedStaleAfter = staleAfter;
        emit FeedChanged(feed_, staleAfter);
    }

    function setAcceptedToken(address token, bool accepted) external onlyOwner {
        if (token == address(0)) revert ZeroAddress();
        uint8 dec = IERC20Metadata(token).decimals();
        acceptedTokens[token] = AcceptedToken({accepted: accepted, decimals: dec});
        emit AcceptedTokenSet(token, accepted, dec);
    }

    function setLimits(uint256 minUsd8, uint256 maxUsd8) external onlyOwner {
        if (maxUsd8 != 0 && maxUsd8 < minUsd8) revert AboveWalletCap(minUsd8, maxUsd8);
        minBuyUsd8 = minUsd8;
        maxBuyUsd8 = maxUsd8;
        emit LimitsChanged(minUsd8, maxUsd8);
    }

    function setReferralRegistry(address registry, uint256 maxBps) external onlyOwner {
        if (maxBps > BPS) revert AboveWalletCap(maxBps, BPS);
        referralRegistry = IReferralRegistry(registry);
        maxCommissionBps = maxBps;
        emit ReferralRegistryChanged(registry, maxBps);
    }

    function pause() external onlyOwner {
        _pause();
    }

    function unpause() external onlyOwner {
        _unpause();
    }

    // ── Recovery (C3.11) ─────────────────────────────────────────────────────

    /// Rescue tokens sent here by mistake. The sale token is protected: only
    /// the surplus above what is still owed to future buyers can leave.
    function recoverERC20(address token, address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();

        if (token == address(saleToken)) {
            uint256 balance = saleToken.balanceOf(address(this));
            uint256 reserved = unsoldAllocation();
            uint256 free = balance > reserved ? balance - reserved : 0;
            if (amount > free) revert ReservedBalance(amount, free);
        }

        IERC20(token).safeTransfer(to, amount);
        emit Recovered(token, to, amount);
    }

    /// ETH is forwarded during a buy, so a balance here means someone forced
    /// it in (selfdestruct) or a treasury transfer was retried.
    function recoverETH(address to) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        uint256 amount = address(this).balance;
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TreasuryTransferFailed();
        emit Recovered(address(0), to, amount);
    }
}

npm/@openzeppelin/[email protected]/access/Ownable.sol

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

npm/@openzeppelin/[email protected]/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

npm/@openzeppelin/[email protected]/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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

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

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

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

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

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

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

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

npm/@openzeppelin/[email protected]/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

npm/@openzeppelin/[email protected]/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

npm/@openzeppelin/[email protected]/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

npm/@openzeppelin/[email protected]/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

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

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

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

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

npm/@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 _safeTransfer(token, to, value, false);
    }

    /**
     * @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 _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @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 {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 relies 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 relies 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}.
     * Oppositely, 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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

npm/@openzeppelin/[email protected]/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

npm/@openzeppelin/[email protected]/utils/Pausable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

npm/@openzeppelin/[email protected]/utils/ReentrancyGuard.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If 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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

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

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

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

npm/@openzeppelin/[email protected]/utils/StorageSlot.sol

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

pragma solidity ^0.8.20;

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

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

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

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

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

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

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

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

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

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

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

npm/@openzeppelin/[email protected]/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

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

project/src/interfaces/AggregatorV3Interface.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

// The four members of the Chainlink feed this project actually uses. Declared
// here rather than taking a dependency on the whole Chainlink contracts package
// for one interface.
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function version() external view returns (uint256);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

project/src/interfaces/IReferralRegistry.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

/**
 * The slice of the C5 referral contract the presale needs. Kept as an
 * interface so the presale can ship and be deployed before C5 exists — the
 * registry address starts at address(0), which disables referrals entirely.
 */
interface IReferralRegistry {
    /**
     * Credit a referrer for a purchase. Called by the presale inside the buy
     * transaction, after the buyer's tokens have been sent.
     *
     * @param referralId  numeric id from the registry; 0 means "no referrer"
     * @param buyer       who made the purchase
     * @param volumeUsd8  purchase size in USD, 8 decimals
     * @param commission  tokens already transferred to the registry for this
     * @return referrer   the credited address, or address(0) if the id was invalid
     */
    function recordPurchase(uint256 referralId, address buyer, uint256 volumeUsd8, uint256 commission)
        external
        returns (address referrer);

    /// Commission owed on a purchase, in USD (8 decimals). 0 if the id is unknown.
    function commissionUsd8(uint256 referralId, address buyer, uint256 volumeUsd8)
        external
        view
        returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.