AIGNPresale

Description:

Proxy contract enabling upgradeable smart contract patterns. Delegates calls to an implementation contract.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

// 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: @openzeppelin/contracts/token/ERC20/IERC20.sol


// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

// File: @openzeppelin/contracts/interfaces/IERC20.sol


// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;


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


// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

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

// File: @openzeppelin/contracts/interfaces/IERC165.sol


// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;


// File: @openzeppelin/contracts/interfaces/IERC1363.sol


// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;



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

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


// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;



/**
 * @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 Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(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);
    }
}

// File: AIGNPresale.sol


pragma solidity ^0.8.20;




interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function description() external view returns (string memory);
    function version() external view returns (uint256);
    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 price,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

contract AIGNPresale is ReentrancyGuard {
    using SafeERC20 for IERC20;

    address public owner;
    address public immutable aignToken; 
    address public treasuryWallet;

    // Use SafeERC20 for USDT token
    IERC20 public immutable usdtToken;  

    // Chainlink ETH/USD price oracle (Sepolia testnet)
    AggregatorV3Interface internal immutable ethUsdPriceFeed; 

    uint256 public currentStage = 1;
    uint256 public constant TOTAL_STAGES = 30;
    uint256 public constant OVERSELL_PERCENTAGE = 25; // 25% oversell allowed per stage
    bool public saleActive = true;

    // Bonus control variables
    uint256 public constant DEFAULT_MAX_BONUS = 10; // Default maximum 10% bonus
    uint256 public currentMaxBonus = DEFAULT_MAX_BONUS; // Current maximum bonus
    bool public bonusEnabled = true; // Bonus function enabled by default for email collection

    // Global tracking for total tokens sold
    uint256 public totalTokensSold = 0;
    uint256 public constant TOTAL_PRESALE_TOKENS = 2000000000 * 10 ** 18; // 2 billion tokens

    // Stage information
    struct StageInfo {
        uint256 priceUSD; // Price in USD (4 decimals: $0.001 = 1000)
        uint256 tokenAmount; // Base tokens available per stage
        uint256 tokensSold; // Actual tokens sold (can exceed tokenAmount by 25%)
        uint256 fundCreditedUSD; // USD value credited this stage (6 decimals) - includes bonus
        uint256 fundPaidUSD; // USD actually paid this stage (6 decimals) - real money received
        bool isPrivateSale; // First 5 stages are private sale
    }

    struct PurchaseResult {
        uint256 actualCostUSD;
        uint256 creditedUSD; // New: Calculation value (including bonus)
        uint256 tokensToBuy;
    }

    mapping(uint256 => StageInfo) public stages;
    mapping(address => uint256) public userPurchases;
    mapping(uint256 => uint256) public stagePurchaseLimits;
    mapping(uint256 => mapping(address => uint256)) public userStageCredited; // Token value obtained at what calculation value
    mapping(uint256 => mapping(address => uint256)) public userStagePaid; // Actual amount paid

    // Claim system
    mapping(address => uint256) public claimableTokens; // User claimable tokens
    bool public claimEnabled = false; // Whether claim is enabled

    event TokensPurchased(
        address indexed buyer,
        uint256 stage,
        uint256 tokensAmount,
        uint256 paidUSD, // Actual payment
        uint256 creditedUSD, // Calculation value (including bonus)
        string paymentMethod
    );
    event StageCompleted(uint256 stage);
    event StageChanged(uint256 newStage);
    event ETHPriceUpdated(uint256 newPrice);
    event BonusSettingsChanged(uint256 newMaxBonus, bool enabled);
    event TokensClaimed(address indexed user, uint256 amount);
    event ClaimStatusChanged(bool enabled);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    modifier onlyOwner() {
        require(msg.sender == owner, "Only owner");
        _;
    }

    modifier saleIsActive() {
        require(saleActive, "Sale is not active");
        _;
    }

    constructor(
        address _aignToken,
        address _usdtToken,
        address _treasuryWallet
    ) {
        // check zero address
        require(_aignToken != address(0), "Invalid token");
        require(_usdtToken != address(0), "Invalid USDT");
        require(_treasuryWallet != address(0), "Invalid treasury");

        owner = msg.sender;
        aignToken = _aignToken;
        usdtToken = IERC20(_usdtToken);
        treasuryWallet = _treasuryWallet;

        // Ethereum ETH/USD price oracle address
        ethUsdPriceFeed = AggregatorV3Interface(
            0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
        );

        _initializeStages();
        _initializePurchaseLimits();
    }

    function _initializeStages() private {
        // Private Sale Stages (1-5)
        stages[1] = StageInfo(1000, 66666667 * 10 ** 18, 0, 0, 0, true); // $0.001
        stages[2] = StageInfo(1200, 66666667 * 10 ** 18, 0, 0, 0, true); // $0.0012
        stages[3] = StageInfo(1400, 66666667 * 10 ** 18, 0, 0, 0, true); // $0.0014
        stages[4] = StageInfo(1600, 66666667 * 10 ** 18, 0, 0, 0, true); // $0.0016
        stages[5] = StageInfo(1800, 66666667 * 10 ** 18, 0, 0, 0, true); // $0.0018

        // Pre Sale Stages (6-30)
        stages[6] = StageInfo(2400, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0024
        stages[7] = StageInfo(3000, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.003
        stages[8] = StageInfo(3600, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0036
        stages[9] = StageInfo(4200, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0042
        stages[10] = StageInfo(4800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0048
        stages[11] = StageInfo(5800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0058
        stages[12] = StageInfo(6800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0068
        stages[13] = StageInfo(7800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0078
        stages[14] = StageInfo(8800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0088
        stages[15] = StageInfo(9800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0098
        stages[16] = StageInfo(10800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0108
        stages[17] = StageInfo(11800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0118
        stages[18] = StageInfo(12800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0128
        stages[19] = StageInfo(13800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0138
        stages[20] = StageInfo(14800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0148
        stages[21] = StageInfo(16800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0168
        stages[22] = StageInfo(18800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0188
        stages[23] = StageInfo(20800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0208
        stages[24] = StageInfo(22800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0228
        stages[25] = StageInfo(24800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0248
        stages[26] = StageInfo(26800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0268
        stages[27] = StageInfo(28800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0288
        stages[28] = StageInfo(30800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0308
        stages[29] = StageInfo(32800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0328
        stages[30] = StageInfo(34800, 66666667 * 10 ** 18, 0, 0, 0, false); // $0.0348
    }

    function _initializePurchaseLimits() private {
        for (uint256 i = 1; i <= TOTAL_STAGES; i++) {
            stagePurchaseLimits[i] = 1000000 * 10 ** 6; // $1,000,000 max per user per stage
        }
    }

    function getETHPrice() public view returns (uint256) {
        (, int256 price, , uint256 updatedAt, ) = ethUsdPriceFeed
            .latestRoundData();
        require(price > 0, "Invalid price from oracle");
        require(block.timestamp - updatedAt <= 3600, "Price data too old");

        return uint256(price) * 10 ** 10;
    }

    function usdToEth(
        uint256 usdAmount,
        uint256 ethPrice
    ) public pure returns (uint256) {
        return (usdAmount * 10 ** 18) / (ethPrice / 10 ** 12);
    }

    function ethToUsd(
        uint256 ethAmount,
        uint256 ethPrice
    ) public pure returns (uint256) {
        return (ethAmount * ethPrice) / 10 ** 30; // ethAmount * ethPrice / 1e30 = USD value in 6 decimals
    }

    function buyWithETH() external payable nonReentrant saleIsActive {
        require(msg.value > 0, "Must send ETH");
        require(currentStage <= TOTAL_STAGES, "Sale ended");

        uint256 ethPrice = getETHPrice();
        uint256 usdValue = ethToUsd(msg.value, ethPrice);
        require(usdValue >= 10 * 10 ** 6, "Minimum purchase is $10");

        PurchaseResult memory result = _calculatePurchase(msg.sender, usdValue);

        // Update state first (CEI pattern)
        _updatePurchaseState(msg.sender, result);

        // Transfer ETH to treasury (no refunds in simplified logic)
        (bool success, ) = payable(treasuryWallet).call{value: msg.value}("");
        require(success, "ETH transfer to treasury failed");

        // Tokens are now added to claimableTokens in _updatePurchaseState()

        emit TokensPurchased(
            msg.sender,
            currentStage,
            result.tokensToBuy,
            usdValue,
            result.creditedUSD,
            "ETH"
        );
    }

    function buyWithETHBonus(
        uint256 tokenCalculationValueUSD
    ) external payable nonReentrant saleIsActive {
        require(bonusEnabled, "Bonus purchases are currently disabled");
        require(msg.value > 0, "Must send ETH");
        require(
            tokenCalculationValueUSD > 0,
            "Must specify calculation amount"
        );
        require(currentStage <= TOTAL_STAGES, "Sale ended");

        uint256 ethPrice = getETHPrice();
        uint256 usdValue = ethToUsd(msg.value, ethPrice);
        require(usdValue >= 10 * 10 ** 6, "Minimum purchase is $10");

        // Core bonus validation logic
        uint256 maxAllowedCalculation = (usdValue * (100 + currentMaxBonus)) /
            100;
        require(
            tokenCalculationValueUSD <= maxAllowedCalculation,
            "Bonus exceeds current maximum"
        );
        require(
            tokenCalculationValueUSD >= usdValue,
            "Invalid bonus calculation"
        );

        // Use bonus-specific calculation function
        PurchaseResult memory result = _calculateBonusPurchase(
            msg.sender,
            usdValue, // Actual USD amount paid
            tokenCalculationValueUSD // Bonus calculation amount
        );

        // Update state using the bonus calculation amount
        _updatePurchaseState(msg.sender, result);

        // Transfer actual ETH sent by user
        (bool success, ) = payable(treasuryWallet).call{value: msg.value}("");
        require(success, "ETH transfer to treasury failed");

        // Tokens are now added to claimableTokens in _updatePurchaseState()

        emit TokensPurchased(
            msg.sender,
            currentStage,
            result.tokensToBuy,
            result.actualCostUSD,
            result.creditedUSD,
            "ETH"
        );
    }

    function buyWithUSDT(
        uint256 usdtAmount
    ) external nonReentrant saleIsActive {
        require(usdtAmount > 0, "Must specify USDT amount");
        require(currentStage <= TOTAL_STAGES, "Sale ended");
        require(usdtAmount >= 10 * 10 ** 6, "Minimum purchase is $10");

        PurchaseResult memory result = _calculatePurchase(
            msg.sender,
            usdtAmount
        );

        // Update state first (CEI pattern)
        _updatePurchaseState(msg.sender, result);

        // Transfer USDT from user to treasury
        usdtToken.safeTransferFrom(msg.sender, treasuryWallet, usdtAmount);

        // Tokens are added to claimableTokens in _updatePurchaseState()

        emit TokensPurchased(
            msg.sender,
            currentStage,
            result.tokensToBuy,
            result.actualCostUSD,
            result.creditedUSD,
            "USDT"
        );
    }

    function buyWithUSDTBonus(
        uint256 paymentAmount,
        uint256 tokenCalculationAmount
    ) external nonReentrant saleIsActive {
        require(bonusEnabled, "Bonus purchases are currently disabled");
        require(paymentAmount > 0, "Must specify payment amount");
        require(tokenCalculationAmount > 0, "Must specify calculation amount");
        require(currentStage <= TOTAL_STAGES, "Sale ended");
        require(paymentAmount >= 10 * 10 ** 6, "Minimum purchase is $10");

        // Core bonus validation logic
        uint256 maxAllowedCalculation = (paymentAmount *
            (100 + currentMaxBonus)) / 100;
        require(
            tokenCalculationAmount <= maxAllowedCalculation,
            "Bonus exceeds current maximum"
        );
        require(
            tokenCalculationAmount >= paymentAmount,
            "Invalid bonus calculation"
        );

        // Use bonus-specific calculation function
        PurchaseResult memory result = _calculateBonusPurchase(
            msg.sender,
            paymentAmount, // Actual payment amount
            tokenCalculationAmount // Bonus calculation amount
        );

        // Update state using the bonus calculation amount
        _updatePurchaseState(msg.sender, result);

        // But only charge the user the payment amount
        usdtToken.safeTransferFrom(msg.sender, treasuryWallet, paymentAmount);

        // Tokens are added to claimableTokens in _updatePurchaseState()

        emit TokensPurchased(
            msg.sender,
            currentStage,
            result.tokensToBuy,
            result.actualCostUSD,
            result.creditedUSD,
            "USDT"
        );
    }

    function _calculatePurchase(
        address buyer,
        uint256 usdAmount
    ) private returns (PurchaseResult memory) {
        _autoAdvanceStageIfNeeded();

        require(currentStage <= TOTAL_STAGES, "All stages completed");

        StageInfo memory stage = stages[currentStage];

        // Limit check: use credited amount (prevent bypassing limits through small payments to get large amounts of tokens)
        require(
            userStageCredited[currentStage][buyer] + usdAmount <=
                stagePurchaseLimits[currentStage],
            "Exceeds stage purchase limit"
        );

        // Calculate tokens based on USD amount and current stage price
        uint256 requestedTokens = (usdAmount * 10 ** 18) / stage.priceUSD;
        require(requestedTokens > 0, "Purchase amount too small");

        // Check only current stage 25% oversell limit (global limit is automatically maintained)
        uint256 stageMaxTokens = (stage.tokenAmount *
            (100 + OVERSELL_PERCENTAGE)) / 100;
        require(
            stage.tokensSold + requestedTokens <= stageMaxTokens,
            "Exceeds stage oversell limit"
        );

        // Normal purchase: payment amount = calculation amount
        return
            PurchaseResult({
                actualCostUSD: usdAmount,
                creditedUSD: usdAmount,
                tokensToBuy: requestedTokens
            });
    }

    function _calculateBonusPurchase(
        address buyer,
        uint256 paymentAmount,
        uint256 calculationAmount
    ) private returns (PurchaseResult memory) {
        _autoAdvanceStageIfNeeded();

        require(currentStage <= TOTAL_STAGES, "All stages completed");

        StageInfo memory stage = stages[currentStage];

        // Limit check: use credited amount (calculation value) instead of payment amount
        // This prevents users from bypassing limits through small payment + high bonus to get large amounts of tokens
        require(
            userStageCredited[currentStage][buyer] + calculationAmount <=
                stagePurchaseLimits[currentStage],
            "Exceeds stage purchase limit"
        );

        // Calculate tokens based on the bonus calculation amount
        uint256 requestedTokens = (calculationAmount * 10 ** 18) /
            stage.priceUSD;
        require(requestedTokens > 0, "Purchase amount too small");

        // Check oversell limit based on calculated tokens
        uint256 stageMaxTokens = (stage.tokenAmount *
            (100 + OVERSELL_PERCENTAGE)) / 100;
        require(
            stage.tokensSold + requestedTokens <= stageMaxTokens,
            "Exceeds stage oversell limit"
        );

        return
            PurchaseResult({
                actualCostUSD: paymentAmount, // Actual payment amount
                creditedUSD: calculationAmount, // Calculation value (including bonus)
                tokensToBuy: requestedTokens
            });
    }

    function _autoAdvanceStageIfNeeded() private {
        // STAGE ADVANCE PATH 1: Alignment only
        // Advances currentStage to the first stage that hasn't reached its base capacity
        // This ensures currentStage reflects the actual state before processing new purchases
        while (
            currentStage <= TOTAL_STAGES &&
            stages[currentStage].tokensSold >= stages[currentStage].tokenAmount
        ) {
            if (currentStage < TOTAL_STAGES) {
                currentStage++;
                emit StageChanged(currentStage);
            } else {
                saleActive = false;
                break;
            }
        }
    }

    function _updatePurchaseState(
        address buyer,
        PurchaseResult memory result
    ) private {
        // Update stage data
        StageInfo storage stage = stages[currentStage];
        stage.tokensSold += result.tokensToBuy;
        stage.fundCreditedUSD += result.creditedUSD; // Calculation value
        stage.fundPaidUSD += result.actualCostUSD; // Actual money received

        // Update user data
        userPurchases[buyer] += result.tokensToBuy;
        userStageCredited[currentStage][buyer] += result.creditedUSD; // Record credited value
        userStagePaid[currentStage][buyer] += result.actualCostUSD; // Record actual payment
        totalTokensSold += result.tokensToBuy;

        // Record claimable tokens instead of direct transfer
        claimableTokens[buyer] += result.tokensToBuy;

        // STAGE ADVANCE PATH 2: Post-transaction advancement
        // Advances currentStage if THIS transaction caused the stage to reach its base capacity
        // This prepares currentStage for the next transaction
        if (stage.tokensSold >= stage.tokenAmount) {
            emit StageCompleted(currentStage);

            // Advance to next stage
            if (currentStage < TOTAL_STAGES) {
                currentStage++;
                emit StageChanged(currentStage);
            } else {
                saleActive = false;
            }
        }

        // Final check for sale completion
        if (currentStage > TOTAL_STAGES) {
            saleActive = false;
        }
    }

    function getCurrentStage() external view returns (uint256) {
        return currentStage;
    }

    function getStageInfo(
        uint256 stageId
    )
        external
        view
        returns (
            uint256 priceInUSD,
            uint256 baseTokenAmount,
            uint256 tokensSold,
            uint256 fundCreditedUSD, // USD for token calculation
            uint256 fundPaidUSD, // actual received payment
            bool isPrivateSale,
            uint256 tokensRemaining // Base remaining tokens
        )
    {
        require(stageId >= 1 && stageId <= TOTAL_STAGES, "Invalid stage");
        StageInfo memory stage = stages[stageId];

        // Simple calculation: base amount minus sold amount, show 0 if negative (oversold)
        uint256 remaining = stage.tokensSold < stage.tokenAmount
            ? stage.tokenAmount - stage.tokensSold
            : 0;

        return (
            stage.priceUSD,
            stage.tokenAmount,
            stage.tokensSold,
            stage.fundCreditedUSD,
            stage.fundPaidUSD,
            stage.isPrivateSale,
            remaining
        );
    }

    // Calculate tokens for USDT purchase
    function calculateTokensForUSDT(
        uint256 usdtAmount
    ) external view returns (uint256) {
        StageInfo memory stage = stages[currentStage];
        return (usdtAmount * 10 ** 18) / stage.priceUSD;
    }

    // Calculate tokens for ETH purchase
    function calculateTokensForETH(
        uint256 ethAmount
    ) external view returns (uint256) {
        uint256 ethPrice = getETHPrice();
        uint256 usdValue = ethToUsd(ethAmount, ethPrice);
        StageInfo memory stage = stages[currentStage];
        return (usdValue * 10 ** 18) / stage.priceUSD;
    }

    function getUserRemainingLimit(
        address user,
        uint256 stageId
    ) external view returns (uint256) {
        return stagePurchaseLimits[stageId] - userStageCredited[stageId][user];
    }

    function getUserStageInfo(
        address user,
        uint256 stageId
    )
        external
        view
        returns (
            uint256 creditedAmount, // Token value obtained at what calculation value
            uint256 paidAmount, // Actual amount paid
            uint256 remainingLimit // Remaining limit
        )
    {
        return (
            userStageCredited[stageId][user],
            userStagePaid[stageId][user],
            stagePurchaseLimits[stageId] - userStageCredited[stageId][user]
        );
    }

    function getStagePurchaseLimit(
        uint256 stageId
    ) external view returns (uint256) {
        return stagePurchaseLimits[stageId];
    }

    function isSaleActive() external view returns (bool) {
        return saleActive;
    }

    // New: Query bonus settings
    function getBonusSettings()
        external
        view
        returns (uint256 maxBonus, bool enabled)
    {
        return (currentMaxBonus, bonusEnabled);
    }

    // Claim system functions
    function claim() external {
        require(claimEnabled, "Claim not yet enabled");
        uint256 amount = claimableTokens[msg.sender];
        require(amount > 0, "No tokens to claim");

        claimableTokens[msg.sender] = 0;
        IERC20(aignToken).safeTransfer(msg.sender, amount);

        emit TokensClaimed(msg.sender, amount);
    }

    function setClaimEnabled(bool enabled) external onlyOwner {
        claimEnabled = enabled;
        emit ClaimStatusChanged(enabled);
    }

    function getClaimableAmount(address user) external view returns (uint256) {
        return claimableTokens[user];
    }

    function isClaimEnabled() external view returns (bool) {
        return claimEnabled;
    }

    // Get overall oversell status - OWNER ONLY
    function getOversellStatus()
        external
        view
        onlyOwner
        returns (
            uint256 totalSold,
            uint256 globalOversellPercentage,
            uint256 actualLimit
        )
    {
        uint256 oversellPercentage = totalTokensSold > TOTAL_PRESALE_TOKENS
            ? ((totalTokensSold - TOTAL_PRESALE_TOKENS) * 100) /
                TOTAL_PRESALE_TOKENS
            : 0;
        uint256 maxLimit = (TOTAL_PRESALE_TOKENS *
            (100 + OVERSELL_PERCENTAGE)) / 100;

        return (totalTokensSold, oversellPercentage, maxLimit);
    }

    // Get cumulative funds raised from stage 1 to specified stage
    function getCumulativeFundsRaised(
        uint256 upToStage
    )
        external
        view
        returns (
            uint256 totalCredited, // Total calculation value
            uint256 totalPaid // Total actual income
        )
    {
        require(upToStage >= 1 && upToStage <= TOTAL_STAGES, "Invalid stage");

        uint256 credited = 0;
        uint256 paid = 0;

        for (uint256 i = 1; i <= upToStage; i++) {
            credited += stages[i].fundCreditedUSD;
            paid += stages[i].fundPaidUSD;
        }

        return (credited, paid);
    }

    // Calculate total target funds
    function getCumulativeTargetFunds(
        uint256 upToStage
    ) external view returns (uint256) {
        require(upToStage >= 1 && upToStage <= TOTAL_STAGES, "Invalid stage");

        uint256 totalTargetFunds = 0;
        for (uint256 i = 1; i <= upToStage; i++) {
            // Each target fund = tokenAmount * priceUSD
            // tokenAmount is 66666667 * 10**18, priceUSD has 4 digits (e.g. 1000 is $0.001)
            // Result needs to be in 6 decimal USD format
            uint256 stageTarget = (stages[i].tokenAmount * stages[i].priceUSD) /
                10 ** 18;
            totalTargetFunds += stageTarget;
        }

        return totalTargetFunds;
    }

    // Owner functions
    function setStage(uint256 newStage) external onlyOwner {
        require(newStage >= 1 && newStage <= TOTAL_STAGES, "Invalid stage");
        currentStage = newStage;
        emit StageChanged(newStage);
    }

    function adjustFundRaised(
        uint256 stageId,
        uint256 newCreditedAmount,
        uint256 newPaidAmount
    ) external onlyOwner {
        require(stageId >= 1 && stageId <= TOTAL_STAGES, "Invalid stage");
        stages[stageId].fundCreditedUSD = newCreditedAmount;
        stages[stageId].fundPaidUSD = newPaidAmount;
    }

    function adjustTokensSold(
        uint256 stageId,
        uint256 newAmount
    ) external onlyOwner {
        require(stageId >= 1 && stageId <= TOTAL_STAGES, "Invalid stage");

        // For manual adjustments (like private sales), only allow up to base amount
        // Oversell should only happen through normal purchase flow, not manual adjustment
        require(
            newAmount <= stages[stageId].tokenAmount,
            "Manual adjustment cannot exceed base stage limit"
        );

        // Update global total
        totalTokensSold =
            totalTokensSold -
            stages[stageId].tokensSold +
            newAmount;
        stages[stageId].tokensSold = newAmount;

        // Emit StageCompleted event if stage meets base requirement
        if (newAmount >= stages[stageId].tokenAmount) {
            emit StageCompleted(stageId);
        }
    }

    function setSaleActive(bool active) external onlyOwner {
        saleActive = active;
    }

    function setPurchaseLimit(
        uint256 stageId,
        uint256 newLimit
    ) external onlyOwner {
        require(stageId >= 1 && stageId <= TOTAL_STAGES, "Invalid stage");
        stagePurchaseLimits[stageId] = newLimit;
    }

    function setTreasuryWallet(address newTreasury) external onlyOwner {
        treasuryWallet = newTreasury;
    }
    // add onwership transfer
    function transferOwnership(address newOwner) external onlyOwner {
        require(newOwner != address(0), "New owner is zero address");
        require(newOwner != owner, "New owner is current owner");

        address oldOwner = owner;
        owner = newOwner;

        emit OwnershipTransferred(oldOwner, newOwner);
    }

    // New: Bonus control functions
    function setBonusSettings(
        uint256 newMaxBonus,
        bool enabled
    ) external onlyOwner {
        require(newMaxBonus <= 50, "Bonus cannot exceed 50%"); // Hard limit 50%
        currentMaxBonus = newMaxBonus;
        bonusEnabled = enabled;
        emit BonusSettingsChanged(newMaxBonus, enabled);
    }

    function disableBonus() external onlyOwner {
        bonusEnabled = false;
        emit BonusSettingsChanged(currentMaxBonus, false);
    }

    function enableBonus() external onlyOwner {
        bonusEnabled = true;
        emit BonusSettingsChanged(currentMaxBonus, true);
    }

    // Unified funds recovery function
    function recoverFunds(address token, uint256 amount) external onlyOwner {
        if (token == address(0)) {
            // Withdraw ETH
            uint256 ethAmount = amount == 0 ? address(this).balance : amount;
            require(treasuryWallet != address(0), "Invalid treasury");
            (bool success, ) = payable(treasuryWallet).call{value: ethAmount}(
                ""
            );
            require(success, "ETH withdrawal failed");
        } else {
            // Withdraw ERC20 tokens (USDT / AIGN / other mistakenly sent tokens)
            uint256 tokenAmount = amount == 0
                ? IERC20(token).balanceOf(address(this))
                : amount;
            IERC20(token).safeTransfer(treasuryWallet, tokenAmount);
        }
    }
}

Tags:
ERC20, ERC165, Proxy, Upgradeable, Factory, Oracle|addr:0xbc6317641ada076d931450fb3a6c982da337077b|verified:true|block:23522423|tx:0x58eb375d7f641fb65f56e12928cfd30339b41233d83f01d7ac7cd4cd1dbd563c|first_check:1759824391

Submitted on: 2025-10-07 10:06:31

Comments

Log in to comment.

No comments yet.