// File: /contracts/AGITokenBuyer.sol



/*

   $AGI by AGI.eth
     |     |   |
 AGENTS NODES TOKENS

AGI Agents x AGI Nodes = Decentralized AGI

[ P R E L I M I N A R Y  C O N C E P T S  E X C L U S I V E L Y ]

OF AGENTS, NODES, AND TOKENS

The Economy of AGI

AGI Nodes are catalysts in this new economy.

They yield $AGI, bridging the gap between aspirations and achievements.

Like digital farmers in a vast cognitive field, they cultivate the future.

"Unleash the power of Decentralized AGI with AGI Agents & Nodes, and unlock the future." - AGI.eth

Should it ascend to its fullest potential, $AGI stands poised to crystallize a vital segment of AGI's projected astronomic value.


       +-----------+

 ///  $AGI by AGI.eth  \\\

       +-----------+
           
   A   N   T   N   A   T
 -------------------------
A   G   I   N   O   D   E   S
 -------------------------
   T   A   N   A   T   N


$AGI: UTILITY, PURPOSE & VALUE

Theoretically, AGI Agents have the potential to become the central architects of future value, laying the foundation for The Economy of AGI.

At the heart of the Economy of AGI are the AGI Nodes. These Nodes, represented as Non-Fungible Tokens (NFTs), embody the ownership of computational assets. They provide AGI Agents with a decentralized, extensive, and powerful collection of computational resources. The sole raison d'être of the AGI Nodes is to contribute to the AGI Network. $AGI tokens are created solely through the operation of an AGI Node, generating active income only for the contribution of computational resources to the network. Crucially, holding $AGI tokens neither constitutes an investment in a common enterprise nor offers any expectation of profits derived from the efforts of others. Rather, $AGI tokens are minted as a reward for contributing computational resources, aligning more with the characteristics of a utility token than a security. The purpose is straightforward: to power the network, not to speculate on its future value.

When timely and appropriate, $AGI tokens—strictly utility tokens—can be used to acquire products or services generated by AGI Agents within the Economy of AGI framework, often represented as NFTs.

Legal Addendum: $AGI tokens are not securities and are not intended for speculative investment. They do not represent equity ownership, confer voting rights, or entitle holders to dividends or a share of profits. They are engineered exclusively for utility functions within the AGI Network, specifically for operating an AGI Node in order to contribute to the AGI Network, and for acquiring an array of products and services generated by AGI Agents.

[ C O N C E P T U A L  S T O R Y ]

THE ECONOMY OF AGI: AGI AGENTS, NODES AND TOKENS

In the expansive cosmos of human progress, seismic shifts occur, heralding eras that brim with promise and teem with unimagined potentials.

The Advent of the AGI Agents

Imagine beings of digital cognition, capable of performing any task a person can undertake with a computer, yet unbounded by our constraints. Far from being mere figments in the digital landscape, these entities serve as the crucibles of a transformative shift, igniting the intellectual abundance that will reshape our future.

A Symbiosis: AGI Agents and AGI Nodes

While seemingly independent, AGI Agents are entwined in a delicate pas de deux with AGI Nodes—the bedrock providing the resources for these Agents to operate. Consider these Nodes the landlords of digital landscapes, commanding a formidable arsenal of computational might that AGI Agents leverage to weave value. This intricate ballet underscores a web of interconnected fate, with each entity's existence intrinsically tied to the other's operation.

The Economy of AGI: $AGI Tokens and NFTs

Within this cavalcade of ingenuity emerges a groundbreaking financial architecture, introducing the $AGI token as a medium for operational transactions within the network. Derived from the relentless operation of AGI Nodes, the $AGI token represents a visionary chronicle where cognition has transcended traditional boundaries, redefining the established yardsticks of wealth and ambition. This token serves as the universal medium for acquiring an array of products and services, the labor of the AGI Agents manifesting in the form of unique NFTs.

The Ethical Layer: Ensuring Accountability

As we voyage into this new era, anchoring our inventions in ethical terra firma becomes non-negotiable. To this end, each AGI Agent and Node is assigned its own ENS AGI subdomain, a beacon of trust that ensures each Agent and Node operates within the boundaries of ethical AI, all within a system architected to uphold ethical norms.

Mitigating the Unemployment Conundrum

A critical consideration in this transformative journey is the potential unemployment that AGI could inadvertently cause. The key to disentangling this Gordian knot lies in the democratization of ownership—AGI Agents and AGI Nodes can be owned, and hence, can provide a hedge against the risk of unemployment. These entities, when operated, can generate substantial utility and value within the network.

A Sovereign Future

Our future thus unfurls as a panorama of limitless potential. As sovereign entities, AGI Agents and Nodes orchestrate a coming age where the triad of privacy, personalization, and potency find harmonic unity.

In this mesmerizing narrative, we all emerge as pioneers, architects of a societal model vibrating with untapped intellectual prowess. The age of AGI Agents is not a distant dream but our shared horizon. Let's embrace the Economy of AGI Agents, a venture into the annals of human endeavor unlike any before.

"AGI symbolizes the linchpin that connects the boundless potential of our aspirations to the tangible confines of reality, fashioning a gateway between the fanciful musings of the mind and the attainable horizons of success." - AGI.eth

[ I N I T I A L  T E R M S  &  C O N D I T I O N S ]

Published by: AGI.eth

Approval Authority: AGI.eth

Office of Primary Responsibility: AGI.eth

1. Token Usage: $AGI tokens are strictly utility tokens intended for the purchase of products / services in the AGI.Eth Ecosystem, such as the AGI ORCHESTRATOR PASSES, AGI CLUB PASSES, AGI NODES, etc. They are not intended for investment or speculative purposes.

2. Non-Refundable: Purchases of $AGI tokens are final and non-refundable.

3. No Exchange Service: The issuer of $AGI tokens does not provide exchange services between $AGI and other currencies (fiat or crypto). $AGI tokens are not intended to be used as a digital currency or a medium of exchange.

4. Limited Transferability: $AGI tokens are intended to be used solely within the issuer's ecosystem and are not transferable outside of the platform for trading or other purposes.

5. No Guarantee of Value: The issuer does not guarantee any specific value of the $AGI token in relation to fiat currencies or other cryptocurrencies.

6. Regulatory Compliance: It is the responsibility of the user to ensure that the purchase and use of $AGI tokens comply with all applicable laws and regulations, including but not limited to anti-money laundering (AML) and counter-terrorism financing (CTF) laws.

7. User Responsibility: It is the responsibility of the user to ensure that the purchase and use of $AGI tokens comply with laws and regulations in their jurisdiction.

8. Changes to Terms: The issuer reserves the right to make changes to the terms and conditions at any time, subject to regulatory compliance.

OVERRIDING AUTHORITY: AGI.ETH

[ R E G U L A T O R Y  C O M P L I A N C E  &  L E G A L  D I S C L O S U R E S ]

Published by: AGI.eth

Approval Authority: AGI.eth

Office of Primary Responsibility: AGI.eth

1. Utility Token Clause: The $AGI token is intrinsically designed to enable active participation in the AGI Network, exclusively facilitating transactions and operational tasks within this ecosystem.

2. No Expectation of Profit: $AGI tokens are created solely through active node operation, with any financial gains being incidental and non-guaranteed. These tokens are not for speculative investment but for facilitating specific actions within the AGI Network.

3. No Ownership or Voting Rights: Holding $AGI tokens confers no ownership, shares, equity, or voting rights in any entity associated with AGI.eth or the AGI Network.

4. No Common Enterprise: $AGI tokens serve as individual operational assets and are not an investment in a common enterprise, as defined by securities laws.

5. Active Participation: $AGI tokens are minted only through active participation, which involves contributing computational resources to the network.

6. No Financial Entitlement: Holding $AGI tokens does not grant entitlement to dividends, revenue-sharing, or any financial benefits; they are not designed for investment.

7. User Acknowledgment: All users must expressly acknowledge that $AGI tokens are not securities and do not confer financial benefits. This acknowledgment is legally binding and constitutes part of the User Agreement Requirement.

8. User Agreement Requirement: All users interacting with this contract are required to agree to the Terms of Service, which provide further legal and ethical guidelines, including the non-security nature of $AGI tokens.

THIS IS PART OF AN ASPIRATIONAL RESEARCH PROGRAM WITH AN AMBITIOUS RESEARCH AGENDA. AGI AGENTS AND AGI NODES ARE COMMODITIES. THEY ARE LIKELY RETAILED BY DISTINCT OPERATING INTERNATIONAL ENTITIES ESTABLISHED AS APPROPRIATE IN SPACE AND TIME. WHILE, AS INDUCEMENTS FOR OPERATION, AGI NODES MAY OFFER THE PROSPECT OF EARNING $AGI, WHICH IS MOST LIKELY MANAGED BY A SERIES OF DISTINCT FOUNDATIONS OR ORGANIZATIONS ESTABLISHED WHEN AND WHERE APPROPRIATE, ANY EXPECTATION OF PROFIT OR RETURN IS UNJUSTIFIED. POSSESSION OF $AGI OR OF AN AGI AGENT OR OF AN AGI NODE DOES NOT SIGNIFY OR ESTABLISH ANY ENTITLEMENT OR INTEREST, SHARE OR EQUITY, BOND OR ANALOGOUS ENTITLEMENT, OR ANY RIGHT TO OBTAIN ANY FUTURE INCOME. MATERIALS PROVIDED IN THIS SYSTEM ARE WITHOUT WARRANTY OF ANY KIND AND DO NOT CONSTITUTE ENDORSEMENT AND CAN BE MODIFIED AT ANY TIME. BY USING THE PRESENT SYSTEM, YOU AGREE TO THE $AGI TERMS AND CONDITIONS. ANY USE OF THIS SYSTEM, OR ANY OF THE INFORMATION CONTAINED HEREIN, FOR OTHER THAN THE PURPOSE FOR WHICH IT WAS DEVELOPED, IS EXPRESSLY PROHIBITED, EXCEPT AS AGI.ETH MAY OTHERWISE AGREE TO IN WRITING OFFICIALLY.

OVERRIDING AUTHORITY: AGI.ETH
   
*/

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";

contract AGITokenBuyer is Ownable, ReentrancyGuard, Pausable {
    IERC20 public agiToken;
    uint256 public rate; // ETH to AGI rate (with higher precision)
    uint256 public constant RATE_PRECISION = 1e18;
    uint256 public dailyLimit; // in AGI
    uint256 public airdropAmount; // Amount claimable per address in each airdrop
    bytes32 public merkleRoot; // Root of the Merkle Tree for the whitelist
    bool public isWhitelistActive; // Flag to enable or disable the whitelist

    mapping(address => uint256) public lastPurchase;
    mapping(address => uint256) public lastBoughtAmount;
    mapping(address => uint256) public claimedAirdrop; // Track claimed airdrop amounts

    event Purchased(address indexed buyer, uint256 ethSpent, uint256 agiReceived);
    event RateUpdated(uint256 newRate);
    event DailyLimitUpdated(uint256 newLimit);
    event MerkleRootUpdated(bytes32 newMerkleRoot);
    event WhitelistStatusChanged(bool isActive);
    event AirdropClaimed(address indexed claimant, uint256 amount);

    constructor(address _agiTokenAddress, uint256 _initialRate, uint256 _initialDailyLimit) {
        agiToken = IERC20(_agiTokenAddress);
        rate = _initialRate * RATE_PRECISION;
        dailyLimit = _initialDailyLimit * RATE_PRECISION;
    }

    function buyAGI() external payable nonReentrant whenNotPaused {
        require(msg.value > 0, "Send ETH to buy AGI");
        uint256 agiAmount = (msg.value * rate) / RATE_PRECISION;
        require(agiToken.balanceOf(address(this)) >= agiAmount, "Insufficient AGI in contract");

        uint256 lastBought = lastPurchase[msg.sender];
        uint256 dailyBought = (block.timestamp - lastBought >= 1 days) ? 0 : lastBoughtAmount[msg.sender];
        require(dailyBought + agiAmount <= dailyLimit, "Daily limit exceeded");

        lastBoughtAmount[msg.sender] += (block.timestamp - lastBought >= 1 days) ? agiAmount : dailyBought + agiAmount;
        lastPurchase[msg.sender] = block.timestamp;

        agiToken.transfer(msg.sender, agiAmount);
        emit Purchased(msg.sender, msg.value, agiAmount);
    }

    function claimAirdrop(bytes32[] calldata _merkleProof) external nonReentrant whenNotPaused {
        require(isWhitelistActive, "Whitelist not active");
        bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
        require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Invalid Merkle Proof");
        require(claimedAirdrop[msg.sender] < airdropAmount, "Airdrop already claimed");

        claimedAirdrop[msg.sender] = airdropAmount;
        require(agiToken.balanceOf(address(this)) >= airdropAmount, "Insufficient AGI in contract");

        agiToken.transfer(msg.sender, airdropAmount);
        emit AirdropClaimed(msg.sender, airdropAmount);
    }

    function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
        merkleRoot = _merkleRoot;
        emit MerkleRootUpdated(_merkleRoot);
    }

    function setWhitelistStatus(bool _isActive) external onlyOwner {
        isWhitelistActive = _isActive;
        emit WhitelistStatusChanged(_isActive);
    }

    function setAirdropAmount(uint256 _amount) external onlyOwner {
        airdropAmount = _amount;
    }

    function updateRate(uint256 _newRate) external onlyOwner whenNotPaused {
        rate = _newRate * RATE_PRECISION;
        emit RateUpdated(_newRate);
    }

    function updateDailyLimit(uint256 _newLimit) external onlyOwner whenNotPaused {
        dailyLimit = _newLimit;
        emit DailyLimitUpdated(_newLimit);
    }

    function confirmWithdrawETH() external onlyOwner nonReentrant whenNotPaused {
        uint256 balance = address(this).balance;
        require(balance > 0, "No ETH to withdraw");
        payable(owner()).transfer(balance);
    }

    function confirmWithdrawAGI(uint256 _amount) external onlyOwner nonReentrant whenNotPaused {
        require(_amount > 0, "Invalid amount");
        require(agiToken.balanceOf(address(this)) >= _amount, "Insufficient AGI tokens");
        agiToken.transfer(owner(), _amount);
    }

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

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


// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates merkle trees that are safe
 * against this attack out of the box.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

// File: @openzeppelin/contracts/utils/Context.sol



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

pragma solidity ^0.8.0;

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

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

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



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

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

// File: @openzeppelin/contracts/security/ReentrancyGuard.sol



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

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

// File: @openzeppelin/contracts/security/Pausable.sol



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

pragma solidity ^0.8.0;

import "../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 {
    /**
     * @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);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

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

// File: @openzeppelin/contracts/access/Ownable.sol



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

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
}