TokenPreSale

Description:

ERC20 token contract with Factory capabilities. Standard implementation for fungible tokens on Ethereum.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol


// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

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

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

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

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

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

// File: PresaleStakeTreasury.sol


pragma solidity ^0.8.0;

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address recipient, uint256 amount) external returns (bool);
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

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

abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }
    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

abstract contract Ownable is Context {
    address private _owner;
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    constructor() {
        _owner = _msgSender();
        emit OwnershipTransferred(address(0), _owner);
    }
    function owner() public view virtual returns (address) {
        return _owner;
    }
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

library SafeMath {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }
}


/* Minimal interface to interact with the staking contract */
interface IStaking {
    function stakeFor(address user, uint256 amount) external;
}

contract TokenPreSale is Ownable, ReentrancyGuard {
    using SafeMath for uint256;

    IERC20 public token;
    IERC20 public usdt;
    AggregatorV3Interface public priceFeed;

    address public treasuryWallet;
    address public stakingContract; // new

    // Hard cap and soft cap (both in USD value, 18 decimals)
    uint256 public constant HARD_CAP = 7_560_000 * 1e18; // $7,560,000
    uint256 public constant SOFT_CAP = HARD_CAP / 100;  // $75,600

    uint256 public totalETHRaised;
    uint256 public totalUSDTRaised;
    uint256 public totalSold;

    // Token price set to $0.000005 per token
    uint256 public tokenPriceInUSDT = 0.000005 ether;

    bool public saleActive = true;
    bool public claimEnabled = false;

    mapping(address => uint256) public pendingTokens;

    event Sell(address indexed buyer, uint256 tokenAmount, uint256 value, string paymentMethod);
    event SellAndStake(address indexed buyer, uint256 tokenAmount, uint256 value, string paymentMethod);
    event Withdraw(address indexed owner, uint256 amount);
    event ClaimStatusChanged(bool newStatus);
    event TokenPriceUpdated(uint256 newPrice);
    event TokensClaimed(address indexed user, uint256 amount);

    constructor(
        address _token,
        address _usdt,
        address _priceFeed,
        address _treasuryWallet,
        address _stakingContract
    ) {
        require(_token != address(0), "Invalid token address");
        require(_usdt != address(0), "Invalid USDT address");
        require(_priceFeed != address(0), "Invalid price feed address");
        require(_treasuryWallet != address(0), "Invalid treasury address");
        require(_stakingContract != address(0), "Invalid staking address");

        token = IERC20(_token);
        usdt = IERC20(_usdt);
        priceFeed = AggregatorV3Interface(_priceFeed);
        treasuryWallet = _treasuryWallet;
        stakingContract = _stakingContract;
    }

    receive() external payable {
        buyAndStakeWithETH();
    }

    // ==================== PRICE HELPERS ====================
    function getLatestETHPrice() public view returns (uint256) {
        (, int256 price, , , ) = priceFeed.latestRoundData();
        return uint256(price).mul(1e10); // convert from 8 to 18 decimals
    }

    function getTokenPriceInETH() public view returns (uint256) {
        uint256 ethPriceInUSD = getLatestETHPrice();
        return tokenPriceInUSDT.mul(1e18).div(ethPriceInUSD);
    }

    function getTotalRaisedInUSD() public view returns (uint256) {
        uint256 ethUSD = getLatestETHPrice(); // 1 ETH = X USD (18 decimals)
        uint256 totalETHinUSD = totalETHRaised.mul(ethUSD).div(1e18);
        uint256 totalUSDTinUSD = totalUSDTRaised; // USDT already 1:1 USD
        return totalETHinUSD.add(totalUSDTinUSD);
    }

    // ==================== BUY WITH ETH ====================
    function buyWithETH() public payable nonReentrant {
        require(saleActive, "Sale not active");
        require(msg.value > 0, "No ETH sent");

        uint256 ethAmount = msg.value;
        uint256 newRaisedUSD = getTotalRaisedInUSD();
        uint256 ethValueUSD = ethAmount.mul(getLatestETHPrice()).div(1e18);
        require(newRaisedUSD.add(ethValueUSD) <= HARD_CAP, "Hard cap reached");

        uint256 tokenPriceInETH = getTokenPriceInETH();
        uint256 tokenAmount = ethAmount.mul(1e18).div(tokenPriceInETH);
        require(token.balanceOf(address(this)) >= tokenAmount, "Not enough tokens");

        totalETHRaised = totalETHRaised.add(ethAmount);
        pendingTokens[msg.sender] = pendingTokens[msg.sender].add(tokenAmount);

        (bool success, ) = treasuryWallet.call{value: ethAmount}("");
        require(success, "ETH transfer failed");

        emit Sell(msg.sender, tokenAmount, ethAmount, "ETH");
    }

    // ==================== BUY WITH USDT ====================
    function buyWithUSDT(uint256 usdtAmount) public nonReentrant {
        require(saleActive, "Sale not active");
        require(usdtAmount > 0, "Invalid USDT amount");

        uint256 newRaisedUSD = getTotalRaisedInUSD();
        require(newRaisedUSD.add(usdtAmount) <= HARD_CAP, "Hard cap reached");

        uint256 tokenAmount = usdtAmount.mul(1e18).div(tokenPriceInUSDT);
        require(token.balanceOf(address(this)) >= tokenAmount, "Not enough tokens");

        totalUSDTRaised = totalUSDTRaised.add(usdtAmount);
        pendingTokens[msg.sender] = pendingTokens[msg.sender].add(tokenAmount);

        require(usdt.transferFrom(msg.sender, treasuryWallet, usdtAmount), "USDT transfer failed");

        emit Sell(msg.sender, tokenAmount, usdtAmount, "USDT");
    }

    // ==================== NEW: BUY AND STAKE WITH ETH ====================
    function buyAndStakeWithETH() public payable nonReentrant {
        require(saleActive, "Sale not active");
        require(msg.value > 0, "No ETH sent");
        require(stakingContract != address(0), "Staking not set");

        uint256 ethAmount = msg.value;
        uint256 newRaisedUSD = getTotalRaisedInUSD();
        uint256 ethValueUSD = ethAmount.mul(getLatestETHPrice()).div(1e18);
        require(newRaisedUSD.add(ethValueUSD) <= HARD_CAP, "Hard cap reached");

        uint256 tokenPriceInETH = getTokenPriceInETH();
        uint256 tokenAmount = ethAmount.mul(1e18).div(tokenPriceInETH);
        require(token.balanceOf(address(this)) >= tokenAmount, "Not enough tokens in presale");

        totalETHRaised = totalETHRaised.add(ethAmount);

        // Transfer ETH immediately to treasury
        (bool success, ) = treasuryWallet.call{value: ethAmount}("");
        require(success, "ETH transfer failed");

        // Transfer tokens from presale contract to staking contract
        require(token.transfer(stakingContract, tokenAmount), "Token transfer to staking failed");

        // Call staking contract to record the stake on behalf of buyer
        IStaking(stakingContract).stakeFor(msg.sender, tokenAmount);

        emit SellAndStake(msg.sender, tokenAmount, ethAmount, "ETH");
    }

    // ==================== NEW: BUY AND STAKE WITH USDT ====================
    function buyAndStakeWithUSDT(uint256 usdtAmount) public nonReentrant {
        require(saleActive, "Sale not active");
        require(usdtAmount > 0, "Invalid USDT amount");
        require(stakingContract != address(0), "Staking not set");

        uint256 newRaisedUSD = getTotalRaisedInUSD();
        require(newRaisedUSD.add(usdtAmount) <= HARD_CAP, "Hard cap reached");

        uint256 tokenAmount = usdtAmount.mul(1e18).div(tokenPriceInUSDT);
        require(token.balanceOf(address(this)) >= tokenAmount, "Not enough tokens in presale");

        totalUSDTRaised = totalUSDTRaised.add(usdtAmount);

        // Transfer USDT to treasury
        require(usdt.transferFrom(msg.sender, treasuryWallet, usdtAmount), "USDT transfer failed");

        // Transfer tokens from presale contract to staking contract
        require(token.transfer(stakingContract, tokenAmount), "Token transfer to staking failed");

        // Call staking contract to record the stake on behalf of buyer
        IStaking(stakingContract).stakeFor(msg.sender, tokenAmount);

        emit SellAndStake(msg.sender, tokenAmount, usdtAmount, "USDT");
    }

    // ==================== CLAIM TOKENS ====================
    function claimTokens() public nonReentrant {
        require(claimEnabled, "Claim not enabled");
        uint256 amount = pendingTokens[msg.sender];
        require(amount > 0, "No tokens to claim");

        pendingTokens[msg.sender] = 0;
        require(token.transfer(msg.sender, amount), "Token transfer failed");

        emit TokensClaimed(msg.sender, amount);
    }

    // ==================== ADMIN FUNCTIONS ====================
    function setClaimEnabled(bool _enabled) external onlyOwner {
        claimEnabled = _enabled;
        emit ClaimStatusChanged(_enabled);
    }

    function withdraw() public onlyOwner nonReentrant {
        uint256 balance = address(this).balance;
        require(balance > 0, "No ETH to withdraw");
        payable(msg.sender).transfer(balance);
        emit Withdraw(msg.sender, balance);
    }

    function setSaleStatus(bool _status) external onlyOwner {
        saleActive = _status;
    }

    function endSale() public onlyOwner {
        uint256 remaining = token.balanceOf(address(this));
        if (remaining > 0) token.transfer(msg.sender, remaining);
        saleActive = false;
    }

    function updateTokenPriceInUSDT(uint256 _newPrice) external onlyOwner {
        require(_newPrice > 0, "Invalid price");
        tokenPriceInUSDT = _newPrice;
        emit TokenPriceUpdated(_newPrice);
    }

    function emergencyWithdrawTokens() external onlyOwner nonReentrant {
        uint256 remaining = token.balanceOf(address(this));
        require(token.transfer(msg.sender, remaining), "Token transfer failed");
    }

    function setStakingContract(address _staking) external onlyOwner {
        require(_staking != address(0), "Invalid staking");
        stakingContract = _staking;
    }
}

Tags:
ERC20, Token, Factory|addr:0xf46edd04252350889f12873a7936654c5edda8a9|verified:true|block:23725859|tx:0x3df4d1b157988ce9f6c76c29d1a21721d05a80b6ec3058d7706dfcc07a3748d2|first_check:1762261719

Submitted on: 2025-11-04 14:08:41

Comments

Log in to comment.

No comments yet.