Skip to content
Verified contractExactMIT

MWARPresale

Address0x9593de69a0f9d2ed566e674a8578975b52ba26e4
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
23,874,824
Creation transaction
0x002222c072…afca30a856

contracts/mwar/MWARPresale.sol

// SPDX-License-Identifier: MIT
/*
  __  __      _        __        __          
 |  \/  | ___| |_ __ _ \ \      / /__ _ _ __ 
 | |\/| |/ _ \ __/ _` | \ \ /\ / / _ ` | '__|
 | |  | |  __/ || (_| |  \ V  V / (_)| | |   
 |_|  |_|\___|\__\__,_|   \_/\_/ \___,_|_|   
*/
pragma solidity ^0.8.20;

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 {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./_Errors.sol";

interface StakeInterface {
  function stakeByPresale(address user, uint256 amount) external;
}

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

interface ReferralRewardsInterface {
  function addReferrerReward(address buyer, address referrer, uint256 tokenAmount, uint256 usdPrice) external returns (uint256 bonusAmount);
}

/**
 * @title Presale
 * @dev Presale contract for buying tokens
 */
contract MWARPresale is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable {
  using SafeERC20 for IERC20;

  uint256 public BASE_MULTIPLIER = (10**18);
  address public saleToken;           // Address of the token to be sold

  uint256 public usdRaised;           // Total amount raised in USD
  uint256 public totalTokensSold;     // Total number of tokens sold

  uint256 public currentPhase;        // Current phase
  uint256 public totalPhases;         // Total number of phases
  struct Phase {    
    uint256 price;                    // Token price in USD
    uint256 tokensToSell;             // Number of tokens to sell
  } 
  mapping(uint256 => Phase) public phases;

  StakeInterface public stakeInterface; // Staking address

  IERC20 public USDTInterface;
  IERC20 public USDCInterface;  
  Aggregator public aggregatorETHInterface;
  
  address public fundReceiver;                            // Fund receiver address
  uint256[] public percentages;
  address[] public wallets;

  bool public saleStatus;                                 // Sale status

  address[] public buyers;                                // Array of buyer addresses
  mapping(address => bool) public buyerExists;            // Buyer existence status
  mapping(address => uint256) public buyerAmount;         // Number of tokens per buyer
  mapping(address => uint256) public buyerDeposits;       // Number of unstaked tokens per buyer
  uint256 public totalBuyers;                             // Number of buyers

  uint256 public claimStart;
  mapping(address => uint256) public buyerClaimed;        // Buyer claim time

  mapping(address => bool) public wertWhitelisted;       // Whitelist status

  struct Conversion {
    uint256 amount;
    uint256 airdropAmount;
  }
  mapping(address => Conversion) public conversions;

  address[] public paymentUSDs;
  mapping(address => bool) public paymentUSDExists;

  ReferralRewardsInterface public referralRewardsInterface;

  event TokenPurchased(
    address indexed user, 
    bytes32 indexed token,
    uint256 amountPaid,
    uint256 usdPrice,
    uint256 purchasedAmount,
    bool stake,
    uint256 timestamp
  );
  event PresaleUpdated(uint256 indexed stage, uint256 timestamp);

  event ClaimStartUpdated(uint256 prevValue, uint256 newValue, uint256 timestamp);
  event TokensClaimed(address indexed user, uint256 amount, uint256 timestamp);
  event TokensClaimedAndStaked(address indexed user, uint256 amount, uint256 timestamp);

  modifier saleEnabled() {
      require(saleStatus == true, "MWARPresale: is not enabled");
      _;
  }

  modifier saleStoped() {
      require(saleStatus == false, "MWARPresale: is not stopped");
      _;
  }

  /**
   * @dev To initialize the contract with price feed address
   * @param _priceFeed price feed address
   * @param _usdtAddress USDT address
   * @param _usdcAddress USDC address
   * @param _fundReceiver fund receiver address
   */
  function initialize(
    address _priceFeed,
    address _usdtAddress,
    address _usdcAddress,
    address _fundReceiver,
    address _admin
  ) public initializer {
    __Ownable_init(_admin);  // Initialize owner
    saleStatus = false;
    BASE_MULTIPLIER = 1000000000000000000;
    aggregatorETHInterface = Aggregator(_priceFeed);
    USDTInterface = IERC20(_usdtAddress);
    USDCInterface = IERC20(_usdcAddress);
    fundReceiver = _fundReceiver;
  }

  /**
   * @dev to initialize
   */
  function initializeUpgrade(address _referralRewardsInterface) public reinitializer(5) {
    referralRewardsInterface = ReferralRewardsInterface(_referralRewardsInterface);
  }

  function stopSale() external onlyOwner saleEnabled {
    saleStatus = false;
  }

  function resumeSale() external onlyOwner saleStoped {
    saleStatus = true;
  }

  /**
   * @dev To check the sale state
   * @param _amount amount to check
   */
  modifier checkSaleState(uint256 _amount) {
    if (!saleStatus) revert SaleNotActive();
    if (_amount == 0) revert InvalidAmount();
    if (currentPhase >= totalPhases) revert InvalidPhase();
    _;
  }

  /**
   * @dev To calculate the price in USD for given amount of tokens.
   * @param _amount No of tokens
   */
  function calculatePrice(uint256 _amount) public view returns (uint256) {
    uint256 USDTAmount;
    Phase storage currentPhaseData = phases[currentPhase];
    
    if (_amount + totalTokensSold > currentPhaseData.tokensToSell) {
      // Number of tokens available for purchase in the current phase
      uint256 tokensForCurrentPrice = currentPhaseData.tokensToSell - totalTokensSold;
      // Calculate at the current phase price
      USDTAmount = tokensForCurrentPrice * currentPhaseData.price;      
      // Remaining number of tokens
      uint256 remainingTokens = _amount - tokensForCurrentPrice;
      
      // If there is a next phase
      if (currentPhase + 1 < totalPhases) {
        Phase storage nextPhaseData = phases[currentPhase + 1];
        USDTAmount += remainingTokens * nextPhaseData.price;
      } else {
        // If there is no next phase, calculate at the current phase price
        USDTAmount += remainingTokens * currentPhaseData.price;
      }
    } else {
      // If all can be purchased in the current phase
      USDTAmount = _amount * currentPhaseData.price;
    }
    
    return USDTAmount;
  }

  /**
   * @dev To get latest ETH price in 10**18 format
   */
  function getLatestPrice() public view returns (uint256) {
      (, int256 price, , , ) = aggregatorETHInterface.latestRoundData();
      price = price * (10 ** 10); // ETH/USD price with 18 decimals
      return uint256(price);
  }  

  function getCoinPrice(address _feedAddress) public view returns (uint256) {
    Aggregator aggregator = Aggregator(_feedAddress);
    (, int256 price, , , ) = aggregator.latestRoundData();
    price = price * (10 ** 10); // ETH/USD price with 18 decimals
    return uint256(price);
  }

  /**
   * @dev To check the current round
   * @param _amount amount to check
   */
  function _checkCurrentRound(uint256 _amount) internal {
    totalTokensSold += _amount;

    // Get data of the current phase
    Phase storage currentPhaseData = phases[currentPhase];    
    // Check if the sales limit of the current phase is exceeded
    if (totalTokensSold >= currentPhaseData.tokensToSell) {
      // Transition to the next phase
      if (currentPhase + 1 < totalPhases) {
        currentPhase++;
        emit PresaleUpdated(currentPhase, block.timestamp);
      }
    }
  }

  function _buyToken(
    address _user,
    bytes32 _purchaseToken,
    uint256 _amountPaid,
    uint256 _usdPrice,
    uint256 _tokenAmount,
    bool _stake,
    address _referrer
  ) internal {

    uint256 bonusAmount = 0;
    if (_referrer != _user && address(referralRewardsInterface) != address(0) && _tokenAmount > 0) {
      bonusAmount = referralRewardsInterface.addReferrerReward(_user, _referrer, _tokenAmount, _usdPrice);
    }

    uint256 depositAmount = _tokenAmount * BASE_MULTIPLIER;

    _checkCurrentRound(_tokenAmount);
    usdRaised += _usdPrice;

    if (_stake) {
      stakeInterface.stakeByPresale(_user, depositAmount);
    } else {
      buyerDeposits[_user] += depositAmount + (bonusAmount * BASE_MULTIPLIER);
    }

    if (!buyerExists[_user]) {
      buyers.push(_user);
      buyerExists[_user] = true;
      totalBuyers++;
    }
    buyerAmount[_user] += depositAmount;

    emit TokenPurchased(_user, _purchaseToken, _amountPaid, _usdPrice, _tokenAmount, _stake, block.timestamp);
  }

  /**
   * @dev To buy into a presale using USD
   * @param _purchaseToken purchase token symbol
   * @param _token token address
   * @param _usdAmount No of USD
   * @param _stake stake flag
   * @param _referrer referrer address
   */
  function buyWithUSD(bytes32 _purchaseToken, address _token, uint256 _usdAmount, bool _stake, address _referrer) external 
    checkSaleState(_usdAmount) 
    whenNotPaused 
    nonReentrant 
    returns (uint256) 
  {
    if (_token != address(USDTInterface) && _token != address(USDCInterface) && !paymentUSDExists[_token]) {
      revert InvalidToken();
    }

    uint256 usdDecimals;
    try IERC20Metadata(_token).decimals() returns (uint8 decimals) {
      usdDecimals = decimals;
    } catch {
      revert InvalidToken();
    }

    uint256 usdPrice = _usdAmount * (10 ** (18 - usdDecimals));
    uint256 tokens = usdToTokens(usdPrice);
    
    if (tokens == 0) revert InvalidAmount();    

    _buyToken(msg.sender, _purchaseToken, _usdAmount, usdPrice, tokens, _stake, _referrer);

    splitERC20Value(_token, msg.sender, _usdAmount);
    return tokens;
  }

  /**
   * @dev To buy into a presale using ETH
   * @param _stake stake flag
   * @param _referrer referrer address
   */
  function buyWithEth(bool _stake, address _referrer) external payable 
    checkSaleState(msg.value) 
    whenNotPaused 
    nonReentrant 
    returns (uint256) 
  {
    uint256 latestPrice = getLatestPrice();
    if (latestPrice == 0) revert InvalidPrice();
    
    // Convert ETH to USD (18 digits)
    uint256 usdPrice = (msg.value * latestPrice) / BASE_MULTIPLIER;
    uint256 tokens = usdToTokens(usdPrice);
    
    if (tokens == 0) revert InvalidAmount();
    
    _buyToken(msg.sender, bytes32("ETH"), msg.value, usdPrice, tokens, _stake, _referrer);

    splitETHValue(msg.value);
    return tokens;
  }

  /**
   * @dev To buy tokens through proxy
   * @param _user user address
   * @param _purchaseToken purchase token address
   * @param _amountPaid amount paid
   * @param _usdPrice USD price
   * @param _tokenAmount no of tokens to buy
   * @param _stake stake flag
   * @param _referrer referrer address
   */
  function buyByProxy(
    address _user,
    bytes32 _purchaseToken,
    uint256 _amountPaid,
    uint256 _usdPrice,
    uint256 _tokenAmount,
    bool _stake,
    address _referrer
  ) external 
    checkSaleState(_tokenAmount)
    whenNotPaused 
    nonReentrant 
    returns (bool) 
  {
    // Basic verification
    if (!wertWhitelisted[_msgSender()]) revert NotWhitelisted();
    if (_user == address(0)) revert InvalidAddress();

    _buyToken(_user, _purchaseToken, _amountPaid, _usdPrice, _tokenAmount, _stake, _referrer);
    return true;
  }
  
  /**
   * @dev Helper funtion to get tokens for given usdt amount
   * @param _amount No of usdt
   */
  function usdToTokens(uint256 _amount)
    public
    view
    returns (uint256 _tokens)
  {
    if (_amount == 0) return 0;
    if (currentPhase >= totalPhases) return 0;
    
    Phase storage currentPhaseData = phases[currentPhase];
    
    // Number of tokens available for purchase in the current phase
    uint256 availableTokensInCurrentPhase = currentPhaseData.tokensToSell - totalTokensSold;
    
    // Number of tokens that can be purchased at the current phase price
    uint256 tokensFromCurrentPrice = _amount / currentPhaseData.price;
    
    if (tokensFromCurrentPrice <= availableTokensInCurrentPhase) {
      // All can be purchased in the current phase
      return tokensFromCurrentPrice;
    } else {
      // Purchase some in the current phase and the rest in the next phase
      uint256 usdForCurrentPhase = availableTokensInCurrentPhase * currentPhaseData.price;
      uint256 remainingUsd18 = _amount - usdForCurrentPhase;
      
      // If there is a next phase
      if (currentPhase + 1 < totalPhases) {
        Phase storage nextPhaseData = phases[currentPhase + 1];
        uint256 tokensFromNextPrice = remainingUsd18 / nextPhaseData.price;
        return availableTokensInCurrentPhase + tokensFromNextPrice;
      } else {
        // If there is no next phase, calculate at the current phase price
        return tokensFromCurrentPrice;
      }
    }
  }

  /**
   * @dev Helper funtion to get ETH price for given amount
   * @param _amount No of tokens to buy
   */
  function ethBuyHelper(uint256 _amount) external view returns (uint256 ethAmount) {
    uint256 usdPrice = calculatePrice(_amount);
    ethAmount = (usdPrice * BASE_MULTIPLIER) / getLatestPrice();
  }

  /**
   * @dev Helper funtion to get USDT price for given amount
   * @param _amount No of tokens to buy
   */
  function usdBuyHelper(uint256 _amount) external view returns (uint256 usdAmount) {
    usdAmount = calculatePrice(_amount);
    usdAmount = usdAmount / (10 ** 12);
  }

  /**
   * @dev To split the ERC20 value to the wallets
   * @param _token token address
   * @param _user user address
   * @param _amount amount to split
   */
  function splitERC20Value(address _token, address _user, uint256 _amount) internal {
    if (wallets.length == 0) {
      if (fundReceiver == address(0)) revert InvalidAddress();
      (bool success, ) = _token.call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _user, fundReceiver, _amount));
      if (!success) revert TransferFailed();
    } else {
      uint256 tempCalc;
      for (uint256 i = 0; i < wallets.length; i++) {
        uint256 amountToTransfer = (_amount * percentages[i]) / 100;
        (bool success, ) = _token.call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _user, wallets[i], amountToTransfer));
        if (!success) revert TransferFailed();
        tempCalc += amountToTransfer;
      }
      if ((_amount - tempCalc) > 0) {
        (bool success, ) = _token.call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _user, wallets[wallets.length - 1], _amount - tempCalc));
        if (!success) revert TransferFailed();
      }
    }
  }

  /**
   * @dev To split the ETH value to the wallets
   * @param _amount amount to split
   */
  function splitETHValue(uint256 _amount) internal {
    if (wallets.length == 0) {
      if (fundReceiver == address(0)) revert InvalidAddress();
      sendValue(payable(fundReceiver), _amount);
    } else {
      uint256 tempCalc;
      for (uint256 i = 0; i < wallets.length; i++) {
        uint256 amountToTransfer = (_amount * percentages[i]) / 100;
        sendValue(payable(wallets[i]), amountToTransfer);
        tempCalc += amountToTransfer;
      }
      if ((_amount - tempCalc) > 0) {
        sendValue(payable(wallets[wallets.length - 1]), _amount - tempCalc);
      }
    }
  }

  /**
   * @dev To send ETH value
   * @param recipient address to send ETH to
   * @param amount amount to send
   */
  function sendValue(address payable recipient, uint256 amount) internal {
    if (address(this).balance < amount) revert InsufficientPayment(amount, address(this).balance);
    (bool success, ) = recipient.call{value: amount}("");
    if (!success) revert TransferFailed();
  }

  /**
    * @dev To update the fund receiving wallet
    * @param _wallet address of wallet to update
    */
  function changeFundWallet(address _wallet) external onlyOwner {
    if (_wallet == address(0)) revert InvalidAddress();
    fundReceiver = _wallet;
  }

  /**
   * @dev To set the splits for the fund receiving wallets
   * @param _wallets addresses of wallets to update
   * @param _percentages percentages of the wallets
   */
  function setSplits(address[] memory _wallets, uint256[] memory _percentages) public onlyOwner {
    if (_wallets.length == 0) revert InvalidAddress();
    if (_percentages.length == 0) revert InvalidAmount();
    if (_wallets.length != _percentages.length) revert InvalidAmount();

    delete wallets;
    delete percentages;
    uint256 totalPercentage = 0;

    for (uint256 i = 0; i < _wallets.length; i++) {
      if (_percentages[i] == 0) revert InvalidAmount();
      totalPercentage += _percentages[i];
      wallets.push(_wallets[i]);
      percentages.push(_percentages[i]);
    }

    if (totalPercentage != 100) revert InvalidAmount();
  }
  
  /**
    * @dev To update the USDT Token address
    * @param _newAddress Sale token address
    */
  function changeUSDTToken(address _newAddress) external onlyOwner {
    if (_newAddress == address(0)) revert InvalidAddress();
    USDTInterface = IERC20(_newAddress);
  }

  /**
    * @dev To update the USDC Token address
    * @param _newAddress Sale token address
    */
  function changeUSDCToken(address _newAddress) external onlyOwner {
    if (_newAddress == address(0)) revert InvalidAddress();
    USDCInterface = IERC20(_newAddress);
  }

  /**
    * @dev To update the referral rewards interface
    * @param _newAddress referral rewards interface address
    */
  function changeReferralRewardsInterface(address _newAddress) external onlyOwner {
    if (_newAddress == address(0)) revert InvalidAddress();
    referralRewardsInterface = ReferralRewardsInterface(_newAddress);
  }

  function addPaymentUSD(address _newAddress) external onlyOwner {
    if (_newAddress == address(0)) revert InvalidAddress();
    if (_newAddress == address(USDTInterface) || _newAddress == address(USDCInterface)) revert InvalidAddress();
    if (paymentUSDExists[_newAddress]) revert InvalidAddress();
    
    paymentUSDs.push(_newAddress);
    paymentUSDExists[_newAddress] = true;
  }

  function removePaymentUSD(address _newAddress) external onlyOwner {
    if (_newAddress == address(0)) revert InvalidAddress();
    if (_newAddress == address(USDTInterface) || _newAddress == address(USDCInterface)) revert InvalidAddress();
    if (!paymentUSDExists[_newAddress]) revert InvalidAddress();
    
    paymentUSDExists[_newAddress] = false;
    
    // 배열에서 제거
    for (uint256 i = 0; i < paymentUSDs.length; i++) {
      if (paymentUSDs[i] == _newAddress) {
        paymentUSDs[i] = paymentUSDs[paymentUSDs.length - 1];
        paymentUSDs.pop();
        break;
      }
    }
  }

  /**
   * @dev Get all payment USD addresses
   * @return Array of payment USD addresses
   */
  function getPaymentUSDs() external view returns (address[] memory) {
    return paymentUSDs;
  }

  /**
   * @dev Check if address is a valid payment token
   * @param _token token address to check
   * @return bool true if valid payment token
   */
  function isValidPaymentToken(address _token) external view returns (bool) {
    return _token == address(USDTInterface) || 
           _token == address(USDCInterface) || 
           paymentUSDExists[_token];
  }

  /**
   * @dev To start the sale
   * @param _totalTokensforSale no of tokens to add to the contract
   * @param _saleToken sale token address
   * @param _stakeAddress stake address
   */
  function startSale(uint256 _totalTokensforSale, address _saleToken, address _stakeAddress) external onlyOwner returns (bool) {
    if (_saleToken == address(0)) revert InvalidAddress();

    saleToken = _saleToken;
    stakeInterface = StakeInterface(_stakeAddress);
    IERC20(_saleToken).approve(_stakeAddress, type(uint256).max);
    
    IERC20(_saleToken).safeTransferFrom(msg.sender, address(this), _totalTokensforSale);

    return true;
  }

  /**
   * @dev To change the claim start time by the owner
   * @param _claimStart new claim start time
   */
  function changeClaimStart(uint256 _claimStart) external onlyOwner {
    if (claimStart == 0) revert InvalidClaimStart();
    if (_claimStart <= block.timestamp) revert ClaimStartInPast();
    uint256 prevValue = claimStart;
    claimStart = _claimStart;
    emit ClaimStartUpdated(prevValue, _claimStart, block.timestamp);
  }

  /**
   * @dev Token claim
   */
  function claim() external whenNotPaused nonReentrant returns (bool) {
    if (saleToken == address(0)) revert InvalidAddress();
    if (block.timestamp < claimStart) revert ClaimNotStarted();

    uint256 amount = buyerDeposits[msg.sender];
    if (amount == 0) revert InvalidAmount();
    delete buyerDeposits[_msgSender()];

    buyerClaimed[_msgSender()] = block.timestamp;

    IERC20(saleToken).safeTransfer(_msgSender(), amount);
    emit TokensClaimed(_msgSender(), amount, block.timestamp);
    return true;    
  }

  /**
   * @dev To claim and stake tokens
   */
  function claimAndStake() external whenNotPaused nonReentrant returns (bool) {
    if (saleToken == address(0)) revert InvalidAddress();
    uint256 amount = buyerDeposits[_msgSender()];
    if (amount == 0) revert InvalidAmount();

    stakeInterface.stakeByPresale(_msgSender(), amount);
    delete buyerDeposits[_msgSender()];
    emit TokensClaimedAndStaked(_msgSender(), amount, block.timestamp);
    return true;    
  }

  /**
   * @dev To change the phases data
   * @param _phases new phases data
   */
  function changePhasesData(Phase[] memory _phases) external onlyOwner {
    // Delete existing phases data
    for (uint256 i = 0; i < totalPhases; i++) {
      delete phases[i];
    }
    
    // Set new phases data
    totalPhases = _phases.length;
    for (uint256 i = 0; i < _phases.length; i++) {
      phases[i] = _phases[i];
    }
  }

  /**
   * @dev Function to get the phase state
   * @return totalTokensSold The total tokens sold
   * @return totalUsdRaised The total USD raised
   * @return currentPhase The current phase
   * @return currentPhasePrice Price of tokens in the current phase
   * @return currentPhaseTokensToSell Number of tokens to sell in the current phase
   * @return nextPhasePrice Price of tokens in the next phase
   */
  function getPhaseState() external view returns (
    uint256,
    uint256,
    uint256,
    uint256,
    uint256,
    uint256
  ) {
    if (currentPhase >= totalPhases) revert InvalidPhase();
    Phase storage phase = phases[currentPhase];
    
    uint256 nextPhasePrice;
    if (currentPhase + 1 < totalPhases) {
      nextPhasePrice = phases[currentPhase + 1].price;
    } else {
      nextPhasePrice = 0;
    }

    return (
      totalTokensSold,
      usdRaised,
      currentPhase,
      phase.price,
      phase.tokensToSell,
      nextPhasePrice
    );
  }  

  /**
   * @dev To add wert contract addresses to whitelist
   * @param _addressesToWhitelist addresses of the contract
   */
  function whitelistUsersForWERT(address[] calldata _addressesToWhitelist) external onlyOwner {
    for (uint256 i = 0; i < _addressesToWhitelist.length; i++) {
      wertWhitelisted[_addressesToWhitelist[i]] = true;
    }
  }

  /**
   * @dev To remove wert contract addresses to whitelist
   * @param _addressesToRemoveFromWhitelist addresses of the contracts
   */
  function removeFromWhitelistForWERT(address[] calldata _addressesToRemoveFromWhitelist) external onlyOwner {
    for (uint256 i = 0; i < _addressesToRemoveFromWhitelist.length; i++) {
      wertWhitelisted[_addressesToRemoveFromWhitelist[i]] = false;
    }
  }

  /**
   * @dev Function to update presale phase variables
   * @param _totalTokensSold Total tokens sold
   * @param _usdRaised Total USD raised
   * @param _currentPhase Current phase
   */
  function updatePresalePhase(
    uint256 _totalTokensSold,
    uint256 _usdRaised,
    uint256 _currentPhase
  ) external onlyOwner {
    totalTokensSold = _totalTokensSold;
    usdRaised = _usdRaised;
    currentPhase = _currentPhase;
  }

  /**
   * @dev Function to batch update buyer amounts
   * @param users The users to update the amounts for
   * @param amounts The amounts to update the amounts with
   * @param airdropAmounts The airdrop amounts to update the amounts with
   */
  function batchConversionAmount(
    address[] calldata users,
    uint256[] calldata amounts,
    uint256[] calldata airdropAmounts
  ) external onlyOwner {
    if (users.length != amounts.length || users.length != airdropAmounts.length) revert LengthMismatch();

    for (uint256 i = 0; i < users.length; i++) {
      if (buyerExists[users[i]]) {
        conversions[users[i]].amount += amounts[i];
        conversions[users[i]].airdropAmount += airdropAmounts[i];
      } else {
        conversions[users[i]] = Conversion(amounts[i], airdropAmounts[i]);
        buyers.push(users[i]);
        buyerExists[users[i]] = true;
        totalBuyers++;
      }
    }
  }  

  receive() external payable {}
}

@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    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;
    }
}

@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable
    struct PausableStorage {
        bool _paused;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;

    function _getPausableStorage() private pure returns (PausableStorage storage $) {
        assembly {
            $.slot := PausableStorageLocation
        }
    }

    /**
     * @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 Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        PausableStorage storage $ = _getPausableStorage();
        $._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) {
        PausableStorage storage $ = _getPausableStorage();
        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 {
        PausableStorage storage $ = _getPausableStorage();
        $._paused = true;
        emit Paused(_msgSender());
    }

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

@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.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].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // 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;

    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
    struct ReentrancyGuardStorage {
        uint256 _status;
    }

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

    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
        assembly {
            $.slot := ReentrancyGuardStorageLocation
        }
    }

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

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        $._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 {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if ($._status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        $._status = ENTERED;
    }

    function _nonReentrantAfter() private {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        // 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) {
        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
        return $._status == ENTERED;
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

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

pragma solidity ^0.8.20;

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {Address} from "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

@openzeppelin/contracts/utils/Address.sol

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

pragma solidity ^0.8.20;

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

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

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

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

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

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

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

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

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

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

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

@openzeppelin/contracts/utils/Errors.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity ^0.8.20;

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

contracts/mwar/ReferralRewards.sol

// SPDX-License-Identifier: MIT
/*
  __  __      _        __        __          
 |  \/  | ___| |_ __ _ \ \      / /__ _ _ __ 
 | |\/| |/ _ \ __/ _` | \ \ /\ / / _ ` | '__|
 | |  | |  __/ || (_| |  \ V  V / (_)| | |   
 |_|  |_|\___|\__\__,_|   \_/\_/ \___,_|_|   
*/
pragma solidity ^0.8.20;

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 {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./_Errors.sol";

/**
 * @title ReferralRewards
 * @dev Contract for managing referral rewards and buyer bonuses
 */
contract ReferralRewards is Initializable, ReentrancyGuardUpgradeable, OwnableUpgradeable {
  using SafeERC20 for IERC20;

  // Total bonus received per buyer (decimals 0)
  mapping(address => uint256) public buyerBonusTotal;

  // Total USD received per referrer (decimals 18)
  mapping(address => uint256) public referrerUSDTotal;

  // Bonus tier settings for buyers
  struct BonusTier {
    uint256 minUSDPrice;  // Minimum USD price (decimals 18)
    uint256 bonusPercent; // Bonus percent (ex: 6 = 6%)
  }
  BonusTier[] public buyerBonusTiers;

  // Referrer reward percent (ex: 10 = 10%)
  uint256 public referrerRewardPercent;

  // Presale contract address
  address public presaleContract;

  // USDT interface
  IERC20 public USDTInterface;

  // Minimum withdrawal amount
  uint256 public minWithdrawalUSD;

  // Total withdrawn amount per referrer (decimals 18)
  mapping(address => uint256) public referrerUSDWithdrawn;

  uint256 public totalReferralRewards;
  uint256 public totalBuyerBonuses;
  uint256 public totalUSDWithdrawn;

  // Events
  event ReferrerRewardAdded(
    address indexed buyer,
    address indexed referrer,
    uint256 tokenAmount,
    uint256 usdPrice,
    uint256 bonusAmount,
    uint256 referrerRewardUSD,
    uint256 timestamp
  );
  event USDWithdrawn(address indexed referrer, uint256 usdtAmount, uint256 timestamp);
  event BuyerBonusTiersUpdated(BonusTier[] tiers, uint256 timestamp);
  event ReferrerRewardPercentUpdated(uint256 oldPercent, uint256 newPercent, uint256 timestamp);
  event MinWithdrawalUSDUpdated(uint256 oldAmount, uint256 newAmount, uint256 timestamp);

  modifier onlyPresale() {
    if (msg.sender != presaleContract) revert NotWhitelisted();
    _;
  }

  /**
   * @dev Initialization function
   * @param _presaleContract Presale contract address
   * @param _usdtAddress USDT token address
   * @param _admin Owner address
   */
  function initialize(
    address _presaleContract,
    address _usdtAddress,
    address _admin
  ) public initializer {
    __Ownable_init(_admin);
    __ReentrancyGuard_init();
    
    if (_presaleContract == address(0)) revert InvalidAddress();
    if (_usdtAddress == address(0)) revert InvalidAddress();
    
    presaleContract = _presaleContract;
    USDTInterface = IERC20(_usdtAddress);
    minWithdrawalUSD = 30 * 10**18;
    referrerRewardPercent = 10; // Default 10%

    // Default buyer bonus tiers
    // $100+: 5%, $200+: 7%, $500+: 10%, $1000+: 15%
    buyerBonusTiers.push(BonusTier({
      minUSDPrice: 100 * 10**18,
      bonusPercent: 5
    }));
    buyerBonusTiers.push(BonusTier({
      minUSDPrice: 200 * 10**18,
      bonusPercent: 7
    }));
    buyerBonusTiers.push(BonusTier({
      minUSDPrice: 500 * 10**18,
      bonusPercent: 10
    }));    
    buyerBonusTiers.push(BonusTier({
      minUSDPrice: 1000 * 10**18,
      bonusPercent: 15
    }));
  }

  /**
   * @dev to initialize
   */
  function initializeUpgrade() public reinitializer(6) {
  }

  /**
   * @dev Add referral reward and calculate buyer bonus
   * @param buyer Buyer's address
   * @param referrer Referrer's address
   * @param tokenAmount Token amount purchased (decimals 0)
   * @param usdPrice USD value of the purchased tokens (decimals 18)
   * @return bonusAmount Bonus token amount for the buyer (decimals 0)
   */
  function addReferrerReward(
    address buyer,
    address referrer,
    uint256 tokenAmount,
    uint256 usdPrice
  ) external onlyPresale returns (uint256 bonusAmount) {
    if (buyer == address(0)) revert InvalidAddress();
    if (buyer == referrer) revert InvalidAddress();
    if (tokenAmount == 0) revert InvalidAmount();
    if (usdPrice == 0) revert InvalidAmount();

    // Calculate buyer bonus
    bonusAmount = calculateBuyerBonus(usdPrice, tokenAmount);
    
    // Update buyer bonus total
    if (bonusAmount > 0) {
      buyerBonusTotal[buyer] += bonusAmount;
      totalBuyerBonuses += bonusAmount;
    }

    // Calculate referrer reward (referrerRewardPercent% of USD)
    uint256 referrerRewardUSD = (usdPrice * referrerRewardPercent) / 100;
    
    // Update referrer USD total
    if (referrerRewardUSD > 0 && referrer != address(0)) {
      referrerUSDTotal[referrer] += referrerRewardUSD;
      totalReferralRewards += referrerRewardUSD;
    } else {
      referrerRewardUSD = 0;
    }

    if (referrerRewardUSD > 0 && referrer != address(0) || bonusAmount > 0) {
      emit ReferrerRewardAdded(
        buyer,
        referrer,
        tokenAmount,
        usdPrice,
        bonusAmount,
        referrerRewardUSD,
        block.timestamp
      );
    }
    
    return bonusAmount;
  }

  /**
   * @dev Calculate buyer bonus
   * @param usdPrice USD price (decimals 18)
   * @param tokenAmount Token amount (decimals 0)
   * @return bonusAmount Bonus token amount (decimals 0)
   */
  function calculateBuyerBonus(uint256 usdPrice, uint256 tokenAmount) public view returns (uint256 bonusAmount) {
    if (buyerBonusTiers.length == 0) return 0;

    // Find the highest bonus percent tier
    uint256 maxBonusPercent = 0;
    
    for (uint256 i = 0; i < buyerBonusTiers.length; i++) {
      if (usdPrice >= buyerBonusTiers[i].minUSDPrice) {
        if (buyerBonusTiers[i].bonusPercent > maxBonusPercent) {
          maxBonusPercent = buyerBonusTiers[i].bonusPercent;
        }
      }
    }

    // Calculate bonus
    if (maxBonusPercent > 0) {
      bonusAmount = (tokenAmount * maxBonusPercent) / 100;
    }

    return bonusAmount;
  }

  /**
   * @dev Withdraw referrer USD
   */
  function withdrawUSD() external nonReentrant {
    uint256 amount = referrerUSDTotal[msg.sender];
    
    if (amount < minWithdrawalUSD) {
      revert InvalidAmount(); // Under minimum withdrawal amount
    }

    // Check USDT decimals (usually 6)
    uint256 usdtDecimals;
    try IERC20Metadata(address(USDTInterface)).decimals() returns (uint8 decimals) {
      usdtDecimals = decimals;
    } catch {
      usdtDecimals = 6; // Default
    }

    // Convert from 18 decimals to USDT decimals
    uint256 usdtAmount = amount / (10 ** (18 - usdtDecimals));

    // Track withdrawn amount (store original USD value)
    referrerUSDWithdrawn[msg.sender] += amount;
    totalUSDWithdrawn += amount;
    
    // Reset total
    referrerUSDTotal[msg.sender] = 0;

    // Transfer USDT
    USDTInterface.safeTransfer(msg.sender, usdtAmount);

    emit USDWithdrawn(msg.sender, usdtAmount, block.timestamp);
  }

  /**
   * @dev Update buyer bonus tiers (Owner only)
   * @param _tiers New bonus tier array
   */
  function setBuyerBonusTiers(BonusTier[] memory _tiers) external onlyOwner {
    delete buyerBonusTiers;

    for (uint256 i = 0; i < _tiers.length; i++) {
      if (_tiers[i].bonusPercent > 100) revert InvalidAmount(); // Cannot exceed 100%
      buyerBonusTiers.push(_tiers[i]);
    }

    emit BuyerBonusTiersUpdated(_tiers, block.timestamp);
  }

  /**
   * @dev Set referrer reward percent (Owner only)
   * @param _percent New reward percent
   */
  function setReferrerRewardPercent(uint256 _percent) external onlyOwner {
    if (_percent > 100) revert InvalidAmount(); // Cannot exceed 100%
    
    uint256 oldPercent = referrerRewardPercent;
    referrerRewardPercent = _percent;

    emit ReferrerRewardPercentUpdated(oldPercent, _percent, block.timestamp);
  }

  /**
   * @dev Set minimum withdrawal amount (Owner only)
   * @param _minWithdrawalUSD Minimum withdrawal amount
   */
  function setMinWithdrawalUSD(uint256 _minWithdrawalUSD) external onlyOwner {
    uint256 oldAmount = minWithdrawalUSD;
    minWithdrawalUSD = _minWithdrawalUSD;
    emit MinWithdrawalUSDUpdated(oldAmount, _minWithdrawalUSD, block.timestamp);
  }

  /**
   * @dev Update presale contract address (Owner only)
   * @param _presaleContract New presale contract address
   */
  function setPresaleContract(address _presaleContract) external onlyOwner {
    if (_presaleContract == address(0)) revert InvalidAddress();
    presaleContract = _presaleContract;
  }

  /**
   * @dev Update USDT interface (Owner only)
   * @param _usdtAddress New USDT address
   */
  function setUSDTInterface(address _usdtAddress) external onlyOwner {
    if (_usdtAddress == address(0)) revert InvalidAddress();
    USDTInterface = IERC20(_usdtAddress);
  }

  /**
   * @dev Get buyer bonus info
   * @param buyer Buyer address
   * @return totalBonus Total bonus token amount (decimals 0)
   */
  function getBuyerBonus(address buyer) external view returns (uint256 totalBonus) {
    return buyerBonusTotal[buyer];
  }

  /**
   * @dev Get referrer USD info
   * @param referrer Referrer address
   * @return totalUSD Total USD amount (decimals 18)
   * @return canWithdraw Whether withdrawal is available
   */
  function getReferrerUSD(address referrer) external view returns (uint256 totalUSD, bool canWithdraw) {
    totalUSD = referrerUSDTotal[referrer];
    canWithdraw = totalUSD >= minWithdrawalUSD;
    return (totalUSD, canWithdraw);
  }

  /**
   * @dev Get all buyer bonus tiers
   * @return tiers Bonus tier array
   */
  function getBuyerBonusTiers() external view returns (BonusTier[] memory tiers) {
    return buyerBonusTiers;
  }

  /**
   * @dev Get count of buyer bonus tiers
   * @return count Number of tiers
   */
  function getBuyerBonusTiersCount() external view returns (uint256 count) {
    return buyerBonusTiers.length;
  }

  /**
   * @dev Get bonuses for multiple buyers at once
   * @param buyers Array of buyer addresses
   * @return bonuses Array of bonuses for each buyer
   */
  function getBuyerBonusesBatch(address[] memory buyers) 
    external 
    view 
    returns (uint256[] memory bonuses) 
  {
    bonuses = new uint256[](buyers.length);
    for (uint256 i = 0; i < buyers.length; i++) {
      bonuses[i] = buyerBonusTotal[buyers[i]];
    }
    return bonuses;
  }

  /**
   * @dev Get USD info for multiple referrers at once
   * @param referrers Array of referrer addresses
   * @return totalUSDs Array of total USD values per referrer
   * @return withdrawnUSDs Array of withdrawn USD per referrer
   * @return canWithdraws Array of withdrawal availability per referrer
   */
  function getReferrerUSDBatch(address[] memory referrers)
    external
    view
    returns (
      uint256[] memory totalUSDs,
      uint256[] memory withdrawnUSDs,
      bool[] memory canWithdraws
    )
  {
    totalUSDs = new uint256[](referrers.length);
    withdrawnUSDs = new uint256[](referrers.length);
    canWithdraws = new bool[](referrers.length);
    
    for (uint256 i = 0; i < referrers.length; i++) {
      totalUSDs[i] = referrerUSDTotal[referrers[i]];
      withdrawnUSDs[i] = referrerUSDWithdrawn[referrers[i]];
      canWithdraws[i] = totalUSDs[i] >= minWithdrawalUSD;
    }
    
    return (totalUSDs, withdrawnUSDs, canWithdraws);
  }

  /**
   * @dev Emergency: Withdraw USDT tokens (Owner only)
   * @param _token Token address
   * @param _to Receiving address
   * @param _amount Amount
   */
  function emergencyWithdraw(address _token, address _to, uint256 _amount) external onlyOwner {
    if (_to == address(0)) revert InvalidAddress();
    IERC20(_token).safeTransfer(_to, _amount);
  }
}

contracts/mwar/_Errors.sol

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

error SaleNotActive();
error InvalidPhase();
error InvalidAmount();
error InvalidAddress();
error InvalidPrice();
error InvalidToken();
error TransferFailed();
error InvalidClaimStart();
error ClaimStartInPast();
error ClaimNotStarted();
error InvalidMinTokenToBuy();
error LengthMismatch();
error NotWhitelisted();

error InsufficientPayment(uint256 required, uint256 received);
Compiler settingsShow
{
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.