KWTToken

Description:

Multi-signature wallet contract requiring multiple confirmations for transaction execution.

Blockchain: Ethereum

Source Code: View Code On The Blockchain

Solidity Source Code:

// SPDX-License-Identifier: MIT
// 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/token/ERC20/extensions/IERC20Metadata.sol


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

pragma solidity >=0.6.2;


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

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


// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// File: @openzeppelin/contracts/interfaces/draft-IERC6093.sol


// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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


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

pragma solidity ^0.8.20;





/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /// @inheritdoc IERC20
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /// @inheritdoc IERC20
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /// @inheritdoc IERC20
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

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


// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;


/**
 * @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 Ownable is Context {
    address private _owner;

    /**
     * @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.
     */
    constructor(address initialOwner) {
        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) {
        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 {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

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


// OpenZeppelin Contracts (last updated v5.1.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.20;


/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

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


// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;


/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

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

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

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

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

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

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

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

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

// File: @openzeppelin/contracts/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: @chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol


pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(
    uint80 _roundId
  ) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

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

// File: CDNR.sol


pragma solidity ^0.8.20;






/**
 * @title KWTToken (CD纳尔代币)
 * @dev 已完全固定初始所有者和国库地址,部署时无需输入任何参数
 * 自动配置ChainLink Oracle地址为以太坊主网常用地址
 */
contract KWTToken is ERC20, Ownable2Step, Pausable, ReentrancyGuard {
    // ============================ 核心常量与固定地址 ============================
    uint8 public constant TOKEN_DECIMALS = 18;
    string public constant TOKEN_FULL_NAME = unicode"沙鸥I";
    string public constant TOKEN_SYMBOL = "SOOO";
    uint256 public constant INITIAL_SUPPLY = 10000 * 10 ** TOKEN_DECIMALS;

    // 固定地址(已验证校验和)
    address public constant INITIAL_OWNER = 0x10947558C9E1CA185317665f512AC9c4406B7286;
    address public constant TREASURY_WALLET = 0x48587D60E877c7154548511883349D65BcD434c6;

    // 固定ChainLink Oracle地址(以太坊主网)
    address public constant ETH_USD_ORACLE = 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419;
    address public constant USD_CNY_ORACLE = 0x8A753747A1Fa494EC906cE90E9f37563A8AF630e;

    // 经济模型参数
    uint256 public constant PURCHASE_FEE_RATE = 100; // 1% (1/10000精度)
    uint256 public constant CRASH_THRESHOLD = 3000; // 30% (1/10000精度)
    uint256 public constant AUTO_MINT_THRESHOLD = 100 * 10 ** TOKEN_DECIMALS;
    uint256 public constant AUTO_MINT_AMOUNT = 1000 * 10 ** TOKEN_DECIMALS;
    uint256 public constant MAX_AIRDROP_BATCH = 1000;
    uint256 public constant ORACLE_EXPIRY = 1 hours;

    // 汇率与精度常量
    uint256 public constant KWD_USD_RATE = 33000; // 1 KWD = 3.3 USD (1/10000)
    uint256 public constant RATE_PRECISION = 10000;
    uint256 public constant PRICE_PRECISION = 100;

    // ============================ 状态变量定义 ============================
    uint256 public totalMinted;
    uint256 public totalBurned;
    uint256 public mintRound;

    // 滚池机制
    uint256 public poolEthBalance;
    uint256 public poolTokenBalance;
    mapping(address => uint256) public userPoolDeposit;

    // 价格体系
    uint256 public naturalPriceCny; // 单位:分/枚
    uint256 public currentFloorPriceCny; // 单位:分/枚
    uint256 public currentFloorPriceKwd; // 单位:厘/枚
    uint256 public lastStablePriceCny; // 单位:分/枚

    // 价格阶梯
    struct PriceStep {
        uint256 totalSupplyThreshold;
        uint256 floorPriceCny;
        uint256 floorPriceKwd;
    }
    PriceStep[] public priceSteps;

    // 空投管理
    mapping(uint256 => bool) public completedAirdropBatch;
    uint256 public totalAirdropAmount;

    // 功能开关
    bool public isFeeEnabled = true;
    bool public isCrashProtectionEnabled = true;
    bool public isCrashProtectionActive;

    // 外部依赖(ChainLink Oracle)
    AggregatorV3Interface public immutable ethUsdOracle;
    AggregatorV3Interface public immutable usdCnyOracle;

    // ============================ 事件定义 ============================
    event TokensMinted(address indexed minter, uint256 amount, uint256 totalSupply, uint256 round);
    event TokensPurchased(
        address indexed buyer,
        uint256 tokenAmount,
        uint256 ethPaid,
        uint256 feeAmount,
        uint256 effectivePriceCny
    );
    event TokensSold(
        address indexed seller,
        uint256 tokenAmount,
        uint256 ethReceived,
        uint256 effectivePriceCny
    );
    event TokensBurned(address indexed burner, uint256 amount);
    event PriceFloorUpdated(
        uint256 newFloorPriceCny,
        uint256 newFloorPriceKwd,
        uint256 currentTotalSupply
    );
    event AutoMinted(
        uint256 mintAmount,
        uint256 round,
        uint256 ownerBalanceAfter
    );
    event CrashProtectionToggled(
        bool isActive,
        uint256 triggerPriceCny,
        uint256 lastStablePriceCny
    );
    event AirdropInitiated(uint256 totalBatches, uint256 totalAddresses, uint256 totalAmount);
    event AirdropBatchProcessed(
        uint256 batchId,
        uint256 addressCount,
        uint256 amountInBatch
    );
    event AirdropCompleted(uint256 totalBatches, uint256 totalAmount);
    event PoolUpdated(uint256 ethBalance, uint256 tokenBalance, uint256 timestamp);

    // ============================ 错误定义 ============================
    error ZeroAmount();
    error InsufficientBalance(address account, uint256 required, uint256 available);
    error InsufficientEth(uint256 required, uint256 provided);
    error InvalidAddress(address invalidAddr);
    error EthTransferFailed(address recipient, uint256 amount);
    error OracleDataInvalid(string oracleType, int256 rate);
    error OracleDataExpired(string oracleType, uint256 lastUpdated);
    error PoolEmpty(string poolType);
    error CrashProtectionActive();
    error BatchAlreadyCompleted(uint256 batchId);
    error BatchSizeExceedsLimit(uint256 requested, uint256 max);
    error AirdropParamsMismatch(uint256 recipientCount, uint256 amountCount);
    error FunctionDisabled(string functionName);
    error InvalidTokenAmount();

    // ============================ 构造函数 ============================
    /**
     * @dev 完全无参数构造函数,所有关键地址已在合约内部固定
     * 自动配置为以太坊主网环境
     */
    constructor() ERC20(TOKEN_FULL_NAME, TOKEN_SYMBOL) Ownable(INITIAL_OWNER) {
        // 初始化ChainLink Oracle
        ethUsdOracle = AggregatorV3Interface(ETH_USD_ORACLE);
        usdCnyOracle = AggregatorV3Interface(USD_CNY_ORACLE);

        // 初始化价格阶梯
        _initializePriceSteps();

        // 初始化价格
        naturalPriceCny = 1;
        currentFloorPriceCny = 1;
        currentFloorPriceKwd = 0;
        lastStablePriceCny = naturalPriceCny;

        // 初始发行
        _mint(INITIAL_OWNER, INITIAL_SUPPLY);
        totalMinted = INITIAL_SUPPLY;

        emit TokensMinted(INITIAL_OWNER, INITIAL_SUPPLY, totalMinted, mintRound);
    }

    /**
     * @dev 初始化价格阶梯
     */
    function _initializePriceSteps() internal {
        priceSteps.push(PriceStep(100000 * 10 ** TOKEN_DECIMALS, 10000, 0));    // 10万枚:100元/枚
        priceSteps.push(PriceStep(350000 * 10 ** TOKEN_DECIMALS, 32000, 0));    // 35万枚:320元/枚
        priceSteps.push(PriceStep(650000 * 10 ** TOKEN_DECIMALS, 0, 2000));     // 65万枚:2 KWD/枚
        priceSteps.push(PriceStep(700000 * 10 ** TOKEN_DECIMALS, 0, 100000));   // 70万枚:100 KWD/枚
        priceSteps.push(PriceStep(800000 * 10 ** TOKEN_DECIMALS, 0, 2000000));  // 80万枚:2000 KWD/枚
        priceSteps.push(PriceStep(900000 * 10 ** TOKEN_DECIMALS, 0, 5000000));  // 90万枚:5000 KWD/枚
        priceSteps.push(PriceStep(1000000 * 10 ** TOKEN_DECIMALS, 0, 20000000));// 100万枚:20000 KWD/枚
        priceSteps.push(PriceStep(1100000 * 10 ** TOKEN_DECIMALS, 0, 100000000));// 110万枚:100000 KWD/枚
        priceSteps.push(PriceStep(1150000 * 10 ** TOKEN_DECIMALS, 0, 500000000));// 115万枚:500000 KWD/枚
        priceSteps.push(PriceStep(1160000 * 10 ** TOKEN_DECIMALS, 0, 800000000));// 116万枚:800000 KWD/枚
        priceSteps.push(PriceStep(1200000 * 10 ** TOKEN_DECIMALS, 0, 1000000000));// 120万枚:1000000 KWD/枚
    }

    // ============================ 管理员功能 ============================
    function mintTokens(uint256 amount) external onlyOwner whenNotPaused {
        if (amount == 0) revert ZeroAmount();
        if (isCrashProtectionActive) revert CrashProtectionActive();

        _mint(owner(), amount);
        totalMinted += amount;
        mintRound++;

        _updatePriceFloor();
        emit TokensMinted(owner(), amount, totalMinted, mintRound);
    }

    function initiateAirdrop(
        address[] calldata recipients,
        uint256[] calldata amounts,
        uint256 batchSize
    ) external onlyOwner whenNotPaused returns (uint256, uint256) {
        if (recipients.length == 0) revert ZeroAmount();
        if (recipients.length != amounts.length) revert AirdropParamsMismatch(recipients.length, amounts.length);
        if (batchSize == 0 || batchSize > MAX_AIRDROP_BATCH) revert BatchSizeExceedsLimit(batchSize, MAX_AIRDROP_BATCH);

        uint256 totalAmount = 0;
        for (uint256 i = 0; i < recipients.length; i++) {
            if (recipients[i] == address(0)) revert InvalidAddress(recipients[i]);
            if (amounts[i] == 0) revert ZeroAmount();
            totalAmount += amounts[i];
        }

        if (balanceOf(owner()) < totalAmount) {
            revert InsufficientBalance(owner(), totalAmount, balanceOf(owner()));
        }

        uint256 totalBatches = (recipients.length + batchSize - 1) / batchSize;
        emit AirdropInitiated(totalBatches, recipients.length, totalAmount);
        return (totalBatches, totalAmount);
    }

    function processAirdropBatch(
        address[] calldata recipients,
        uint256[] calldata amounts,
        uint256 batchSize,
        uint256 batchId
    ) external onlyOwner whenNotPaused nonReentrant returns (bool) {
        if (recipients.length == 0) revert ZeroAmount();
        if (recipients.length != amounts.length) revert AirdropParamsMismatch(recipients.length, amounts.length);
        if (batchSize == 0 || batchSize > MAX_AIRDROP_BATCH) revert BatchSizeExceedsLimit(batchSize, MAX_AIRDROP_BATCH);
        if (completedAirdropBatch[batchId]) revert BatchAlreadyCompleted(batchId);

        uint256 startIndex = batchId * batchSize;
        uint256 endIndex = startIndex + batchSize;
        if (startIndex >= recipients.length) revert ZeroAmount();
        if (endIndex > recipients.length) endIndex = recipients.length;

        uint256 batchAmount = 0;
        for (uint256 i = startIndex; i < endIndex; i++) {
            address recipient = recipients[i];
            uint256 amount = amounts[i];

            if (recipient == address(0)) revert InvalidAddress(recipient);
            if (amount == 0) revert ZeroAmount();

            _transfer(owner(), recipient, amount);
            batchAmount += amount;
        }

        completedAirdropBatch[batchId] = true;
        totalAirdropAmount += batchAmount;
        bool isLastBatch = endIndex >= recipients.length;

        emit AirdropBatchProcessed(batchId, endIndex - startIndex, batchAmount);

        if (isLastBatch) {
            uint256 totalAmount = 0;
            for (uint256 i = 0; i < amounts.length; i++) {
                totalAmount += amounts[i];
            }
            emit AirdropCompleted(batchId + 1, totalAmount);
        }

        return isLastBatch;
    }

    function togglePause() external onlyOwner {
        if (paused()) _unpause();
        else _pause();
    }

    function toggleFee(bool _enabled) external onlyOwner {
        isFeeEnabled = _enabled;
    }

    function toggleCrashProtection(bool _enabled) external onlyOwner {
        isCrashProtectionEnabled = _enabled;
        if (!_enabled && isCrashProtectionActive) {
            isCrashProtectionActive = false;
            emit CrashProtectionToggled(false, naturalPriceCny, lastStablePriceCny);
        }
    }

    function disableCrashProtection() external onlyOwner {
        if (isCrashProtectionActive) {
            isCrashProtectionActive = false;
            lastStablePriceCny = naturalPriceCny;
            emit CrashProtectionToggled(false, naturalPriceCny, lastStablePriceCny);
        }
    }

    function withdrawTreasuryEth() external onlyOwner nonReentrant {
        uint256 balance = address(this).balance - poolEthBalance;
        if (balance == 0) revert InsufficientEth(1, 0);

        (bool success, ) = payable(TREASURY_WALLET).call{value: balance}("");
        if (!success) revert EthTransferFailed(TREASURY_WALLET, balance);
    }

    // ============================ 用户功能 ============================
    function buyKWT(uint256 amount) external payable whenNotPaused nonReentrant {
        if (amount == 0) revert ZeroAmount();
        if (amount % (10 ** TOKEN_DECIMALS) != 0) revert InvalidTokenAmount();
        if (isCrashProtectionActive) revert CrashProtectionActive();

        _checkAndAutoMint();
        
        uint256 effectivePrice = _getEffectivePrice();
        uint256 ethNeeded = _calculateEthForKWT(amount, effectivePrice);

        if (msg.value < ethNeeded) revert InsufficientEth(ethNeeded, msg.value);

        uint256 fee = isFeeEnabled ? (amount * PURCHASE_FEE_RATE) / RATE_PRECISION : 0;
        uint256 netAmount = amount - fee;

        if (balanceOf(owner()) < netAmount + fee) {
            revert InsufficientBalance(owner(), netAmount + fee, balanceOf(owner()));
        }

        // 执行转账
        _transfer(owner(), msg.sender, netAmount);
        if (fee > 0) {
            _transfer(owner(), TREASURY_WALLET, fee);
        }

        // 更新滚池
        userPoolDeposit[msg.sender] += netAmount;
        poolTokenBalance += netAmount;
        poolEthBalance += ethNeeded;

        // 更新价格
        _updateNaturalPrice();

        // 退还多余ETH
        if (msg.value > ethNeeded) {
            (bool success, ) = payable(msg.sender).call{value: msg.value - ethNeeded}("");
            if (!success) revert EthTransferFailed(msg.sender, msg.value - ethNeeded);
        }

        emit TokensPurchased(msg.sender, amount, ethNeeded, fee, effectivePrice);
        emit PoolUpdated(poolEthBalance, poolTokenBalance, block.timestamp);
    }

    function sellKWT(uint256 amount) external whenNotPaused nonReentrant {
        if (amount == 0) revert ZeroAmount();
        if (amount % (10 ** TOKEN_DECIMALS) != 0) revert InvalidTokenAmount();
        if (poolTokenBalance == 0) revert PoolEmpty("token");
        if (poolEthBalance == 0) revert PoolEmpty("eth");

        if (userPoolDeposit[msg.sender] < amount) {
            revert InsufficientBalance(msg.sender, amount, userPoolDeposit[msg.sender]);
        }

        uint256 effectivePrice = _getEffectivePrice();
        uint256 ethAmount = _calculateEthForKWT(amount, effectivePrice);

        if (poolEthBalance < ethAmount) revert InsufficientEth(ethAmount, poolEthBalance);

        // 更新滚池
        userPoolDeposit[msg.sender] -= amount;
        poolTokenBalance -= amount;
        poolEthBalance -= ethAmount;

        // 执行转账
        _transfer(msg.sender, owner(), amount);

        // 支付ETH
        (bool success, ) = payable(msg.sender).call{value: ethAmount}("");
        if (!success) revert EthTransferFailed(msg.sender, ethAmount);

        // 更新价格和检查崩盘
        _updateNaturalPrice();
        if (isCrashProtectionEnabled) {
            _checkCrashCondition();
        }

        emit TokensSold(msg.sender, amount, ethAmount, effectivePrice);
        emit PoolUpdated(poolEthBalance, poolTokenBalance, block.timestamp);
    }

    function burnTokens(uint256 amount) external whenNotPaused {
        if (amount == 0) revert ZeroAmount();

        uint256 userBalance = balanceOf(msg.sender);
        if (userBalance < amount) revert InsufficientBalance(msg.sender, amount, userBalance);

        // 从滚池移除
        if (userPoolDeposit[msg.sender] >= amount) {
            userPoolDeposit[msg.sender] -= amount;
            poolTokenBalance -= amount;
            _updateNaturalPrice();
            emit PoolUpdated(poolEthBalance, poolTokenBalance, block.timestamp);
        }

        _burn(msg.sender, amount);
        totalBurned += amount;
        emit TokensBurned(msg.sender, amount);
    }

    // ============================ 内部功能 ============================
    function _updatePriceFloor() internal {
        uint256 currentTotalSupply = totalMinted;
        uint256 newFloorCny = currentFloorPriceCny;
        uint256 newFloorKwd = currentFloorPriceKwd;

        // 找到当前发行量对应的价格阶梯
        for (uint256 i = 0; i < priceSteps.length; i++) {
            if (currentTotalSupply >= priceSteps[i].totalSupplyThreshold) {
                newFloorCny = priceSteps[i].floorPriceCny;
                newFloorKwd = priceSteps[i].floorPriceKwd;
            }
        }

        bool updated = false;
        if (newFloorCny != currentFloorPriceCny) {
            currentFloorPriceCny = newFloorCny;
            updated = true;
        }
        if (newFloorKwd != currentFloorPriceKwd) {
            currentFloorPriceKwd = newFloorKwd;
            updated = true;
        }

        if (updated) {
            emit PriceFloorUpdated(newFloorCny, newFloorKwd, currentTotalSupply);
        }
    }

    function _updateNaturalPrice() internal {
        if (poolTokenBalance == 0 || poolEthBalance == 0) {
            return;
        }

        uint256 ethUsd = _getEthUsdRate();
        uint256 usdCny = _getUsdCnyRate();
        uint256 ethCny = (ethUsd * usdCny) / PRICE_PRECISION; // 分/ETH

        // 计算自然价格:(滚池ETH * ETH/CNY) / 滚池代币总量
        naturalPriceCny = (poolEthBalance * ethCny) / poolTokenBalance;

        // 价格恢复时关闭崩盘防护
        if (isCrashProtectionActive && naturalPriceCny >= lastStablePriceCny) {
            isCrashProtectionActive = false;
            emit CrashProtectionToggled(false, naturalPriceCny, lastStablePriceCny);
        }
    }

    function _getEffectivePrice() internal view returns (uint256) {
        if (currentFloorPriceKwd > 0) {
            uint256 usdCny = _getUsdCnyRate();
            uint256 kwdCny = (KWD_USD_RATE * usdCny) / RATE_PRECISION;
            uint256 floorPriceCny = (currentFloorPriceKwd * kwdCny) / 10; // 厘转分
            return naturalPriceCny > floorPriceCny ? naturalPriceCny : floorPriceCny;
        }
        
        return naturalPriceCny > currentFloorPriceCny ? naturalPriceCny : currentFloorPriceCny;
    }

    function _checkCrashCondition() internal {
        if (isCrashProtectionActive) return;

        uint256 priceDrop = (lastStablePriceCny - naturalPriceCny) * RATE_PRECISION / lastStablePriceCny;
        
        if (priceDrop >= CRASH_THRESHOLD) {
            isCrashProtectionActive = true;
            emit CrashProtectionToggled(true, naturalPriceCny, lastStablePriceCny);
        } else {
            lastStablePriceCny = naturalPriceCny;
        }
    }

    function _calculateEthForKWT(uint256 kwtAmount, uint256 price) internal view returns (uint256) {
        uint256 ethUsd = _getEthUsdRate();
        uint256 usdCny = _getUsdCnyRate();
        uint256 ethCny = (ethUsd * usdCny) / PRICE_PRECISION; // 分/ETH
        
        return (kwtAmount * price) / (ethCny * PRICE_PRECISION);
    }

    function _checkAndAutoMint() internal {
        if (balanceOf(owner()) < AUTO_MINT_THRESHOLD && !isCrashProtectionActive) {
            _mint(owner(), AUTO_MINT_AMOUNT);
            totalMinted += AUTO_MINT_AMOUNT;
            mintRound++;
            
            _updatePriceFloor();
            emit AutoMinted(AUTO_MINT_AMOUNT, mintRound, balanceOf(owner()));
        }
    }

    // ============================ Oracle相关 ============================
    function _getEthUsdRate() internal view returns (uint256) {
        (uint80 roundId, int256 rate, , uint256 updatedAt, uint80 answeredInRound) = ethUsdOracle.latestRoundData();
        if (rate <= 0) revert OracleDataInvalid("ETH/USD", rate);
        if (answeredInRound < roundId) revert OracleDataExpired("ETH/USD", updatedAt);
        if (block.timestamp - updatedAt > ORACLE_EXPIRY) revert OracleDataExpired("ETH/USD", updatedAt);
        return uint256(rate);
    }

    function _getUsdCnyRate() internal view returns (uint256) {
        (uint80 roundId, int256 rate, , uint256 updatedAt, uint80 answeredInRound) = usdCnyOracle.latestRoundData();
        if (rate <= 0) revert OracleDataInvalid("USD/CNY", rate);
        if (answeredInRound < roundId) revert OracleDataExpired("USD/CNY", updatedAt);
        if (block.timestamp - updatedAt > ORACLE_EXPIRY) revert OracleDataExpired("USD/CNY", updatedAt);
        return uint256(rate);
    }

    // ============================ 辅助功能 ============================
    function calculateAirdropBatches(uint256 totalAddresses, uint256 batchSize) public pure returns (uint256) {
        if (totalAddresses == 0 || batchSize == 0) return 0;
        return (totalAddresses + batchSize - 1) / batchSize;
    }

    function isAirdropCompleted(uint256 totalBatches) external view returns (bool) {
        for (uint256 i = 0; i < totalBatches; i++) {
            if (!completedAirdropBatch[i]) return false;
        }
        return true;
    }

    function getTokenStats() external view returns (
        uint256 remainingTokens,
        uint256 totalIssued,
        uint256 naturalPrice,
        uint256 priceFloor,
        uint256 mintRoundCount,
        uint256 burnedAmount,
        uint256 poolBal,
        uint256 poolTokens,
        bool crashProtection
    ) {
        remainingTokens = balanceOf(owner());
        totalIssued = totalMinted;
        naturalPrice = naturalPriceCny;
        priceFloor = currentFloorPriceCny > 0 ? currentFloorPriceCny : currentFloorPriceKwd;
        mintRoundCount = mintRound;
        burnedAmount = totalBurned;
        poolBal = poolEthBalance;
        poolTokens = poolTokenBalance;
        crashProtection = isCrashProtectionActive;
    }

    // 拒绝意外ETH转入
    receive() external payable { revert(); }
}

Tags:
ERC20, Multisig, Upgradeable, Multi-Signature, Factory, Oracle|addr:0x04ef21d4fee3c65602b19f53b5d5098ed7ae4a30|verified:true|block:23462040|tx:0x9d4465383453ecee5256719be925d0dcb13aad38e741ec989b4be91cb5a26fc2|first_check:1759069568

Submitted on: 2025-09-28 16:26:09

Comments

Log in to comment.

No comments yet.