Skip to content
Verified contractExactMIT

Web3PaymentsPresaleV2

Address0xcfd385776eaac51897010dfe4e7cc957ffb38491
Balance

0 ETH

 

Transactions

87

 

Compiler

solc 0.8.9

 

Same code

4 more contracts

 

Details

Compiler
solc 0.8.9+commit.e5eed63a
Language
solidity
Optimization
Yes, 200 runs
EVM version
london
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
21,390,882
Creation transaction
0x6122c3a451…04cce3a469

contracts/ETH/Web3PaymentsPresaleV2.sol

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

/// @title Presale Contract - v1
/// @notice This contract manages a token presale with options to buy using ETH or USDT.
/// @dev This contract utilizes OpenZeppelin's libraries for additional security.

// External dependencies
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

/// @dev Interface for fetching the latest ETH/USD price data.
interface Aggregator {
    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

contract Web3PaymentsPresaleV2 is Ownable, Pausable, ReentrancyGuard {
    // Presale variables
    uint256 public totalTokensSold; // Total number of tokens sold during the sale.
    uint256 public startTime; // Start timestamp of the sale.
    uint256 public endTime; // End timestamp of the sale.
    uint256 public claimStart; // Timestamp when buyers can claim their tokens.
    address public saleToken; // ERC20 token that is on sale.
    uint256 public constant baseDecimals = 10 ** 18; // Base unit for token and ETH calculations.

    // Purchase and pricing variables
    uint256 public usdRaised; // USD amount accumulated from the sale.
    uint256 public tokensToBeSold; // Total number of tokens available for sale.
    uint256 public tokenPrice; // Price of the token in terms of USD.

    // Wallets and commission
    address public paymentWallet; // Address where the funds (ETH/USDT) from sale will be sent.
    address public commissionWallet; // Address which receives the commission.
    uint256 public commissionPercentage; // Commission rate in percentage.
    address public adminWallet; // Address which has admin role.

    // External contract interfaces
    IERC20 public USDTInterface; // Interface for the USDT token functions.
    Aggregator public aggregatorInterface; // Interface to fetch latest ETH/USD prices.

    // Trackers for user data
    mapping(address => uint256) public userDeposits; // Track how many tokens each user has bought.
    mapping(address => bool) public hasClaimed; // Track if a user has claimed their tokens after the sale.

    // Events to record notable contract actions
    /// @dev Emitted when the sale's start and end times are set.
    event SaleTimeSet(
        uint256 indexed _start,
        uint256 indexed _end,
        uint256 indexed timestamp
    );

    /// @dev Emitted when specific sale details, like token count or price, are updated.
    event SaleDetailsUpdated(
        bytes32 indexed key,
        uint256 prevValue,
        uint256 newValue,
        uint256 timestamp
    );

    /// @dev Emitted when either the sale's start or end time is updated.
    event SaleTimeUpdated(
        bytes32 indexed key,
        uint256 prevValue,
        uint256 newValue,
        uint256 timestamp
    );

    /// @dev Emitted when tokens are bought by users.
    event TokensBought(
        address indexed user,
        uint256 indexed tokensBought,
        address indexed purchaseToken,
        uint256 amountPaid,
        uint256 usdEq,
        uint256 timestamp,
        uint256 usdRaised,
        uint256 totalTokensSold
    );

    /// @dev Emitted when tokens are added to the contract for selling or claiming.
    event TokensAdded(
        address indexed token,
        uint256 noOfTokens,
        uint256 timestamp
    );

    /// @dev Emitted when a user claims their purchased tokens after the sale.
    event TokensClaimed(
        address indexed user,
        uint256 amount,
        uint256 timestamp
    );

    /// @dev Emitted when the time users can start claiming their tokens is updated.
    event ClaimStartUpdated(
        uint256 prevValue,
        uint256 newValue,
        uint256 timestamp
    );

    /// @dev Emitted when the maximum number of tokens that can be bought is updated.
    event MaxTokensUpdated(
        uint256 prevValue,
        uint256 newValue,
        uint256 timestamp
    );
    /// @dev Emitted when Payment wallet is updated.
    event PaymentWalletUpdated(
        address prevAddress,
        address newAddress,
        uint256 timestamp
    );
    /// @dev Emitted when Commission wallet is updated.
    event CommissionWalletUpdated(
        address prevAddress,
        address newAddress,
        uint256 timestamp
    );
    /// @dev Emitted when the Commission Percentage is updated.
    event CommissionPercentageUpdated(
        uint256 prevValue,
        uint256 newValue,
        uint256 timestamp
    );
    /// @dev Emitted when Admin wallet is updated.
    event AdminWalletUpdated(
        address prevAddress,
        address newAddress,
        uint256 timestamp
    );
    /// @dev Emitted when Oracle Address is updated.
    event OracleAddressUpdated(
        address prevAddress,
        address newAddress,
        uint256 timestamp
    );

    /// @dev Constructor to initialize the presale contract with specific parameters.
    /// @param _oracle Address of the price aggregator for ETH/USD.
    /// @param _usdt Address of the USDT token contract.
    /// @param _startTime Start time of the presale.
    /// @param _endTime End time of the presale.
    /// @param _tokensToBeSold Number of tokens available for presale.
    /// @param _tokenPrice Price of each token in USD.
    /// @param _paymentWallet Wallet address to which the sale funds will be transferred.
    /// @param _commissionWallet Address to receive commission.
    /// @param _commissionPercentage Percentage of sales as commission.
    constructor(
        address _oracle,
        address _usdt,
        uint256 _startTime,
        uint256 _endTime,
        uint256 _tokensToBeSold,
        uint256 _tokenPrice,
        address _paymentWallet,
        address _commissionWallet,
        uint256 _commissionPercentage,
        address _adminWallet
    ) {
        // Validation
        require(_oracle != address(0), "Zero aggregator address");
        require(_usdt != address(0), "Zero USDT address");
        require(_paymentWallet != address(0), "Zero address");
        require(
            _commissionWallet != address(0),
            "Zero commission wallet address"
        );
        require(
            _startTime > block.timestamp && _endTime > _startTime,
            "Invalid time"
        );

        // Assigning values
        aggregatorInterface = Aggregator(_oracle);
        USDTInterface = IERC20(_usdt);
        startTime = _startTime;
        endTime = _endTime;
        tokensToBeSold = _tokensToBeSold;
        tokenPrice = _tokenPrice;
        paymentWallet = _paymentWallet;
        commissionPercentage = _commissionPercentage;
        commissionWallet = _commissionWallet;
        adminWallet = _adminWallet;
        emit SaleTimeSet(startTime, endTime, block.timestamp);
    }

    /// @notice Pause the sale.
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Resume the sale.
    function unpause() external onlyOwner {
        _unpause();
    }

    /**
    @notice Calculate the price in USDT for a given amount of tokens.
    @dev The function takes into account the token price set in the contract 
    and multiplies it by the amount of tokens to derive the USDT price.
    @param _amount Number of tokens for which the USDT price needs to be calculated.
    @return The USDT price for the specified amount of tokens.
    */
    function calculatePrice(uint256 _amount) public view returns (uint256) {
        // Ensure that selling this amount of tokens won't exceed the total tokens designated for sale
        require(
            _amount + totalTokensSold <= tokensToBeSold,
            "Insufficient tokens available for sale."
        );

        // Calculate the total price in USDT by multiplying the amount of tokens with the token's price
        uint256 USDTAmount = _amount * tokenPrice;

        return USDTAmount;
    }

    /// @notice Update the start and end times for the sale.
    /// @param _startTime The new start time for the sale.
    /// @param _endTime The new end time for the sale.
    function changeSaleTimes(
        uint256 _startTime,
        uint256 _endTime
    ) external onlyOwner {
        // Ensure either startTime or endTime is valid
        require(_startTime > 0 || _endTime > 0, "Invalid parameters");

        // If startTime is specified and is still in the future, update it
        if (_startTime > 0) {
            // Ensure sale hasn't started
            require(block.timestamp < startTime, "Sale already started");
            require(block.timestamp < _startTime, "Sale time in past");

            // Emit the update and then change the startTime
            emit SaleTimeUpdated(
                bytes32("START"),
                startTime,
                _startTime,
                block.timestamp
            );
            startTime = _startTime;
        }

        // If endTime is specified and is still in the future, update it
        if (_endTime > 0) {
            // Ensure sale hasn't ended
            require(block.timestamp < endTime, "Sale already ended");
            require(_endTime > startTime, "Invalid endTime");

            // Emit the update and then change the endTime
            emit SaleTimeUpdated(
                bytes32("END"),
                endTime,
                _endTime,
                block.timestamp
            );
            endTime = _endTime;
        }
    }

    /// @notice Get the latest Ether price in USD with 18 decimals.
    /// @return The latest Ether price in 10^18 format.
    function getLatestPrice() public view returns (uint256) {
        // Fetch the latest round data from the oracle aggregator
        (, int256 price, , , ) = aggregatorInterface.latestRoundData();

        // Convert the price to 10^18 format
        price = price * (10 ** 10);

        // Ensure price is non-negative and cast to uint256 before returning
        require(price >= 0, "Negative price returned from the aggregator");
        return uint256(price);
    }

    /**
    @dev A modifier to check whether the sale is active based on the current timestamp and a specified token purchase amount.
    @param amount The amount of tokens the user intends to buy.
    */
    modifier checkSaleState(uint256 amount) {
        // Ensure the current timestamp is within the sale start and end time
        require(
            block.timestamp >= startTime && block.timestamp <= endTime,
            "Outside of sale period"
        );

        // Ensure the specified purchase amount is valid
        require(amount > 0, "Invalid purchase amount");

        _; // Placeholder for the modified function's body
    }
    /**
    @dev A modifier to check whether the caller is Admin or not.
    */
    modifier onlyAdmin() {
        // Ensure the current is admin
        require(_msgSender() == adminWallet, "Admin : Caller is not the Admin");

        _; // Placeholder for the modified function's body
    }

    /// @notice Purchase tokens using USDT.
    /// @param amount Number of tokens to purchase.
    /// @return A boolean indicating whether the purchase was successful.
    function buyWithUSDT(
        uint256 amount
    ) external checkSaleState(amount) whenNotPaused returns (bool) {
        // Calculate the USD price for the desired token amount
        uint256 usdPrice = calculatePrice(amount);

        // Convert the price into USDT (taking into account USDT's decimals)
        uint256 price = usdPrice / (10 ** 12);

        // Calculate commission based on set commissionPercentage
        uint256 commission = (price * commissionPercentage) / 10000;

        // Increment the total tokens sold and USD raised
        totalTokensSold += amount;
        usdRaised += usdPrice;

        // Record the token purchase amount for the user
        userDeposits[_msgSender()] += (amount * baseDecimals);

        // Ensure user has set enough USDT allowance for this contract to deduct funds
        uint256 ourAllowance = USDTInterface.allowance(
            _msgSender(),
            address(this)
        );
        require(price <= ourAllowance, "Make sure to add enough allowance");

        // Transfer funds from user to paymentWallet and commissionWallet
        // This uses low-level call for flexibility and error handling
        (bool success, ) = address(USDTInterface).call(
            abi.encodeWithSignature(
                "transferFrom(address,address,uint256)",
                _msgSender(),
                paymentWallet,
                price - commission
            )
        );
        // Ensure transfers were successful
        require(success, "Payment Wallet Token payment failed");

        (bool commissionSuccess, ) = address(USDTInterface).call(
            abi.encodeWithSignature(
                "transferFrom(address,address,uint256)",
                _msgSender(),
                commissionWallet,
                commission
            )
        );
        // Ensure transfers were successful
        require(commissionSuccess, "Commission Wallet Token payment failed");

        // Emit an event recording this purchase
        emit TokensBought(
            _msgSender(),
            amount,
            address(USDTInterface),
            price,
            usdPrice,
            block.timestamp,
            usdRaised,
            totalTokensSold
        );

        return true;
    }

    /// @notice Purchase tokens using Ether.
    /// @param amount Number of tokens to purchase.
    /// @return A boolean indicating whether the purchase was successful.
    function buyWithEth(
        uint256 amount
    )
        external
        payable
        checkSaleState(amount)
        whenNotPaused
        nonReentrant
        returns (bool)
    {
        // Calculate the USD price for the desired token amount
        uint256 usdPrice = calculatePrice(amount);

        // Convert the USD price to its equivalent in Ether
        uint256 ethAmount = (usdPrice * baseDecimals) / getLatestPrice();

        // Calculate commission based on set commissionPercentage
        uint256 commission = (ethAmount * commissionPercentage) / 10000;

        // Ensure the Ether sent with the transaction is enough
        require(msg.value >= ethAmount, "Insufficient payment");

        // Calculate any excess Ether sent
        uint256 excess = msg.value - ethAmount;

        // Update total tokens sold and the total USD raised
        totalTokensSold += amount;
        usdRaised += usdPrice;

        // Record the token purchase amount for the user
        userDeposits[_msgSender()] += (amount * baseDecimals);

        // Transfer Ether to the payment and commission wallets
        sendValue(payable(paymentWallet), ethAmount - commission);
        sendValue(payable(commissionWallet), commission);

        // Refund any excess Ether sent by the buyer
        if (excess > 0) sendValue(payable(_msgSender()), excess);

        // Emit an event to log the purchase details
        emit TokensBought(
            _msgSender(),
            amount,
            address(0),
            ethAmount,
            usdPrice,
            block.timestamp,
            usdRaised,
            totalTokensSold
        );

        return true;
    }

    /// @notice Helper function to compute the Ether amount required for a given token purchase.
    /// @param amount The number of tokens intended for purchase.
    /// @return The Ether amount required for the purchase.
    function ethBuyHelper(uint256 amount) external view returns (uint256) {
        // Use the internal calculatePrice function to compute the USD price for the amount
        uint256 usdPrice = calculatePrice(amount);

        // Convert the USD price to its Ether equivalent
        return (usdPrice * baseDecimals) / getLatestPrice();
    }

    /// @notice Helper function to compute the USDT amount required for a given token purchase.
    /// @param amount The number of tokens intended for purchase.
    /// @return The USDT amount required for the purchase.
    function usdtBuyHelper(uint256 amount) external view returns (uint256) {
        // Use the internal calculatePrice function to compute the USD price for the amount
        uint256 usdPrice = calculatePrice(amount);

        // Adjust for the USDT's decimal places (typically 6 decimals)
        return usdPrice / (10 ** 12);
    }

    /// @dev A utility function to safely send Ether to a specified address.
    /// @param recipient The address to receive the Ether.
    /// @param amount The amount of Ether to send in wei.
    function sendValue(address payable recipient, uint256 amount) internal {
        // Ensure the contract has enough Ether before attempting the transfer
        require(address(this).balance >= amount, "Insufficient funds");

        // Use call instead of transfer or send for better gas efficiency and to avoid the 2300 gas stipend limitation
        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Ether transfer failed");
    }

    /// @notice Set the claiming period and add sale tokens for user
    /// @param _claimStart Timestamp when users can start claiming tokens.
    /// @param noOfTokens Amount of tokens to add for claiming.
    /// @param _saleToken Address of the token being sold.
    /// @return A boolean indicating whether the operation was successful.
    function startClaim(
        uint256 _claimStart,
        uint256 noOfTokens,
        address _saleToken
    ) external onlyOwner returns (bool) {
        // Check that the claim start is set appropriately and tokens are available
        require(
            _claimStart > endTime && _claimStart > block.timestamp,
            "Invalid claim start time"
        );
        require(_saleToken != address(0), "Token address cannot be zero");
        require(claimStart == 0, "Claim period already set");

        // Set the claim start time and sale token address.
        claimStart = _claimStart;
        saleToken = _saleToken;

        // Transfer the sale tokens to this contract
        bool success = IERC20(_saleToken).transferFrom(
            _msgSender(),
            address(this),
            noOfTokens
        );
        require(success, "Token transfer failed");

        // Emit event logging added tokens
        emit TokensAdded(saleToken, noOfTokens, block.timestamp);

        return true;
    }

    /// @notice Change the starting timestamp for token claims after the sale ends.
    /// @param _claimStart The new timestamp when users can start claiming their tokens.
    /// @return A boolean indicating if the operation was successful.
    function changeClaimStart(
        uint256 _claimStart
    ) external onlyOwner returns (bool) {
        // Ensure that the claim period has been set
        require(claimStart > 0, "Initial claim data not set");

        // Validate the new claim start time
        require(_claimStart > endTime, "Sale is still in progress");
        require(_claimStart > block.timestamp, "Claim start is in the past");

        // Emit an event for the claim start change and update the claim start
        emit ClaimStartUpdated(claimStart, _claimStart, block.timestamp);
        claimStart = _claimStart;

        return true;
    }

    /// @notice Allows users to claim the tokens they bought after the claim period starts.
    /// @return A boolean indicating whether the claim was successful.
    function claim() external whenNotPaused returns (bool) {
        // Ensure that the sale token has been set and the claim period has started
        require(
            block.timestamp >= claimStart,
            "Claim period has not started yet"
        );

        // Check that the user hasn't already claimed their tokens
        require(!hasClaimed[_msgSender()], "Tokens already claimed");
        hasClaimed[_msgSender()] = true;

        // Get the amount of tokens the user is allowed to claim
        uint256 amount = userDeposits[_msgSender()];

        // Ensure the user has tokens to claim
        require(amount > 0, "No tokens to claim");

        // Remove the user's token deposit data to prevent re-entrancy
        delete userDeposits[_msgSender()];

        // Transfer the tokens to the user
        bool success = IERC20(saleToken).transfer(_msgSender(), amount);
        require(success, "Token transfer failed");

        // Emit an event to record the token claim
        emit TokensClaimed(_msgSender(), amount, block.timestamp);

        return true;
    }

    /// @notice Update the number of tokens available for sale and their price.
    /// @param _tokensToBeSold The new number of tokens available for sale.
    /// @param _tokenPrice The new token price.
    function changeRoundsData(
        uint256 _tokensToBeSold,
        uint256 _tokenPrice
    ) external onlyOwner {
        // Validate and update the token price if needed
        if (_tokenPrice > 0) {
            require(block.timestamp < endTime, "Sale has already ended");
            emit SaleDetailsUpdated(
                bytes32("PRICE"),
                tokenPrice,
                _tokenPrice,
                block.timestamp
            );
            tokenPrice = _tokenPrice;
        }

        // Validate and update the number of tokens for sale if needed
        if (_tokensToBeSold > 0) {
            require(
                _tokensToBeSold > totalTokensSold,
                "Amount less then already sold tokens"
            );
            require(block.timestamp < endTime, "Sale has already ended");
            emit SaleDetailsUpdated(
                bytes32("TOKENSTOBESOLD"),
                tokensToBeSold,
                _tokensToBeSold,
                block.timestamp
            );
            tokensToBeSold = _tokensToBeSold;
        }
    }

    /// @notice Update the payment wallet address.
    /// @param _newPaymentWallet The new payment wallet address.
    function setPaymentWallet(address _newPaymentWallet) external onlyOwner {
        // Ensure the new address is valid
        require(_newPaymentWallet != address(0), "Invalid address");
        emit PaymentWalletUpdated(
            paymentWallet,
            _newPaymentWallet,
            block.timestamp
        );
        paymentWallet = _newPaymentWallet;
    }

    /// @notice Update the address for commission collection.
    /// @param _commissionWallet The new commission collection address.
    function setCommissionWallet(address _commissionWallet) external onlyAdmin {
        // Ensure the new commission address is valid
        require(_commissionWallet != address(0), "Invalid address");
        emit CommissionWalletUpdated(
            commissionWallet,
            _commissionWallet,
            block.timestamp
        );
        commissionWallet = _commissionWallet;
    }

    /// @notice Update the percentage of commissions taken on each purchase.
    /// @param _commissionPercentage The new commission percentage.
    function setCommissionPercentage(
        uint256 _commissionPercentage
    ) external onlyAdmin {
        // Ensure that the new commission percentage is valid
        require(
            _commissionPercentage <= 10000,
            "Invalid commission percentage"
        );
        emit CommissionPercentageUpdated(
            commissionPercentage,
            _commissionPercentage,
            block.timestamp
        );
        commissionPercentage = _commissionPercentage;
    }

    /// @notice Update the address for admin wallet.
    /// @param _adminWallet The new admin wallet address.
    function setAdminWallet(address _adminWallet) external onlyAdmin {
        // Ensure the new admin address is valid
        require(_adminWallet != address(0), "Invalid address");
        emit AdminWalletUpdated(adminWallet, _adminWallet, block.timestamp);
        adminWallet = _adminWallet;
    }

    /// @notice Update the ETH/USD oracle
    /// @param _newOracleAddress The new oracle Address
    function setOracle(address _newOracleAddress) external onlyAdmin {
        // Ensure the new admin address is valid
        require(_newOracleAddress != address(0), "Invalid address");
        emit OracleAddressUpdated(
            address(aggregatorInterface),
            _newOracleAddress,
            block.timestamp
        );
        aggregatorInterface = Aggregator(_newOracleAddress);
    }
}

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

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

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

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

@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;
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.